cordova-plugin-pushizo 0.1.0 → 0.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.
@@ -1,465 +1,600 @@
1
- import Foundation
2
- import Pushizo
3
- // SPM: ayrı modül; CocoaPods alt spec'leri tek "Pushizo" modülünde derlenir.
4
- #if canImport(PushizoCore)
5
- import PushizoCore
6
- #endif
7
- import UIKit
8
- import UserNotifications
9
-
10
- /// Köprü metot sonucu: başarıda isteğe bağlı sözlük, hatada kod ve mesaj.
11
- enum PushizoBridgeResult {
12
- case success([String: Any]?)
13
- case failure(code: String, message: String)
14
- }
15
-
16
- /// JS `initialize` ayarlarının kalıcı kopyası (yalnızca herkese açık değerler; gizli bilgi tutulmaz).
17
- struct PushizoBridgeConfig {
18
- static let defaultsKey = "pushizo_bridge_config"
19
- let appId: String
20
- let apiUrl: String?
21
- let requiresPrivacyConsent: Bool
22
- let logLevel: String
23
-
24
- func save() {
25
- var dict: [String: Any] = ["appId": appId, "requiresPrivacyConsent": requiresPrivacyConsent, "logLevel": logLevel]
26
- if let apiUrl { dict["apiUrl"] = apiUrl }
27
- UserDefaults.standard.set(dict, forKey: Self.defaultsKey)
28
- }
29
-
30
- static func load() -> PushizoBridgeConfig? {
31
- guard let dict = UserDefaults.standard.dictionary(forKey: defaultsKey),
32
- let appId = dict["appId"] as? String, !appId.isEmpty else { return nil }
33
- return PushizoBridgeConfig(appId: appId, apiUrl: dict["apiUrl"] as? String,
34
- requiresPrivacyConsent: dict["requiresPrivacyConsent"] as? Bool ?? false,
35
- logLevel: dict["logLevel"] as? String ?? "warn")
36
- }
37
-
38
- /// SDK'yı bu ayarlarla başlatır.
39
- func initializeSdk() {
40
- Pushizo.initialize(appId) { options in
41
- if let apiUrl { options.apiUrl = apiUrl }
42
- options.requiresPrivacyConsent = requiresPrivacyConsent
43
- options.logLevel = PushizoBridgeCore.logLevel(logLevel)
44
- }
45
- }
46
- }
47
-
48
- /**
49
- Köprüden bağımsız iOS çekirdeği: JS metot adlarını Pushizo iOS SDK çağrılarına çevirir ve SDK olaylarını
50
- `emit(tür, veri)` ile köprüye iletir. SDK dinleyicileri kaldırılamadığından süreç başına bir kez eklenir ve
51
- o anki etkin çekirdeğe yönlendirilir.
52
- */
53
- final class PushizoBridgeCore: NSObject {
54
- /// Olayların iletileceği etkin çekirdek (köprü yeniden yüklenirse güncellenir).
55
- fileprivate static weak var active: PushizoBridgeCore?
56
- private static var listenersRegistered = false
57
- private static let maxPendingForeground = 32
58
- private static let notInitialized = "Önce Pushizo.initialize çağrılmalı"
59
-
60
- private let emit: (String, [String: Any]) -> Void
61
- /// JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır.
62
- var foregroundHandlerEnabled = false
63
- private var foregroundSeq = 0
64
- private var pendingForeground: [String: HSForegroundEvent] = [:]
65
- private var pendingOrder: [String] = []
66
- private let lock = NSLock()
67
-
68
- init(emit: @escaping (String, [String: Any]) -> Void) {
69
- self.emit = emit
70
- super.init()
71
- Self.active = self
72
- }
73
-
74
- // MARK: Olaylar
75
-
76
- /// SDK başlatılmışsa (kayıtlı ayarlarla) dinleyicileri bağlar.
77
- func attachIfInitialized() {
78
- if Pushizo.isInitialized { registerListeners() }
79
- }
80
-
81
- private func registerListeners() {
82
- Self.active = self
83
- guard !Self.listenersRegistered else { return }
84
- Self.listenersRegistered = true
85
- Pushizo.Notifications.addClickListener { e in
86
- Self.active?.emit("click", ["notification": Self.map(e.notification),
87
- "result": ["actionId": Self.orNull(e.actionId), "url": Self.orNull(e.url)]])
88
- }
89
- Pushizo.Notifications.addForegroundLifecycleListener { e in
90
- guard let core = Self.active else { return }
91
- core.onForeground(e)
92
- }
93
- Pushizo.User.pushSubscription.addObserver { s in
94
- guard let core = Self.active else { return }
95
- core.emit("pushSubscriptionChange", Self.map(s))
96
- }
97
- // Yerel SDK izin gözlemcisi: izin isteği sonucu ve uygulama yeniden etkinleştiğinde (izin Ayarlar'dan
98
- // değişmiş olabilir) etkin izin değiştiyse çağrılır.
99
- Pushizo.Notifications.addPermissionObserver { granted in
100
- Self.active?.emit("permissionChange", ["permission": granted])
101
- }
102
- Pushizo.InAppMessages.addClickListener { e in
103
- Self.active?.emit("inAppClick", ["message": ["id": e.messageId], "result": ["actionId": e.actionId, "url": Self.orNull(e.url)]])
104
- }
105
- Pushizo.InAppMessages.addLifecycleListener(PushizoBridgeLifecycleForwarder.shared)
106
- // Canlı sohbet olayları → JS `chatEvent`; sohbet bildirimi tıklaması → `chatOpen` (cephe bekletir).
107
- Pushizo.Chat.addListener { event in
108
- var body = event.payload
109
- body["type"] = event.type
110
- Self.active?.emit("chatEvent", body)
111
- }
112
- Pushizo.Chat.addOpenListener { info in
113
- Self.active?.emit("chatOpen", info.dictionary)
114
- }
115
- }
116
-
117
- private func onForeground(_ event: HSForegroundEvent) {
118
- lock.lock()
119
- foregroundSeq += 1
120
- let id = "fg-\(foregroundSeq)"
121
- let pending = foregroundHandlerEnabled
122
- if pending {
123
- // Yerel gösterim ertelenir; JS `display()` çağırırsa veya hiçbir dinleyici engellemezse gösterilir
124
- // (yanıt gelmezse SDK 25 sn sonra bildirimi göstermeden kapatır).
125
- event.preventDefault()
126
- pendingForeground[id] = event
127
- pendingOrder.append(id)
128
- while pendingOrder.count > Self.maxPendingForeground {
129
- pendingForeground.removeValue(forKey: pendingOrder.removeFirst())
130
- }
131
- }
132
- lock.unlock()
133
- emit("foregroundWillDisplay", ["notificationId": id, "pending": pending, "notification": Self.map(event.notification)])
134
- }
135
-
136
- private func takePending(_ id: String) -> HSForegroundEvent? {
137
- lock.lock()
138
- defer { lock.unlock() }
139
- pendingOrder.removeAll { $0 == id }
140
- return pendingForeground.removeValue(forKey: id)
141
- }
142
-
143
- fileprivate func emitLifecycle(_ event: String, _ message: HSInAppMessage) {
144
- emit("inAppLifecycle", ["event": event, "message": ["id": message.id]])
145
- }
146
-
147
- // MARK: Metotlar
148
-
149
- /// Metodu çalıştırır; bilinmeyen metotta false döner.
150
- func handle(_ method: String, _ args: [String: Any], reply: @escaping (PushizoBridgeResult) -> Void) -> Bool {
151
- func ok(_ data: [String: Any]? = nil) { reply(.success(data)) }
152
- func invalid(_ message: String) { reply(.failure(code: "INVALID_ARGUMENT", message: message)) }
153
- func string(_ key: String) -> String? {
154
- guard let value = args[key] as? String, !value.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
155
- return value
156
- }
157
- func stringMap(_ key: String) -> [String: String] {
158
- (args[key] as? [String: Any] ?? [:]).compactMapValues { value in
159
- if value is NSNull { return nil }
160
- return (value as? String) ?? "\(value)"
161
- }
162
- }
163
- func stringList(_ key: String) -> [String] { (args[key] as? [Any] ?? []).compactMap { $0 as? String } }
164
-
165
- switch method {
166
- case "initialize":
167
- guard let appId = string("appId") else { invalid("appId gerekli"); return true }
168
- let config = PushizoBridgeConfig(appId: appId, apiUrl: string("apiUrl"),
169
- requiresPrivacyConsent: args["requiresPrivacyConsent"] as? Bool ?? false,
170
- logLevel: string("logLevel") ?? "warn")
171
- // Soğuk başlatmada (bildirim tıklaması) SDK köprü yüklenir yüklenmez başlatılabilsin diye saklanır.
172
- config.save()
173
- config.initializeSdk()
174
- registerListeners()
175
- ok()
176
- case "setConsentGiven": Pushizo.setConsentGiven(args["given"] as? Bool ?? false); ok()
177
- case "login":
178
- guard let externalId = string("externalId") else { invalid("externalId gerekli"); return true }
179
- let identityHash = string("identityHash"), jwt = string("jwt")
180
- // Kanıt app kipine uymuyorsa Android köprüsündeki gibi reddedilir (yerel SDK yalnızca loglar).
181
- if let message = Pushizo.loginProofError(identityHash: identityHash, jwt: jwt) {
182
- reply(.failure(code: "NOT_READY", message: message)); return true
183
- }
184
- Pushizo.login(externalId, identityHash: identityHash, jwt: jwt); ok()
185
- case "updateUserJwt":
186
- guard let jwt = string("jwt") else { invalid("jwt gerekli"); return true }
187
- do {
188
- try Pushizo.updateUserJwt(jwt); ok()
189
- } catch {
190
- reply(.failure(code: "NOT_READY", message: "Önce login ile kullanıcı kimliklendirilmeli"))
191
- }
192
- case "logout": Pushizo.logout(); ok()
193
-
194
- case "addTags": Pushizo.User.addTags(stringMap("tags")); ok()
195
- case "removeTags": Pushizo.User.removeTags(stringList("keys")); ok()
196
- case "getTags": ok(["tags": Pushizo.User.getTags()])
197
- case "addAliases": Pushizo.User.addAliases(stringMap("aliases")); ok()
198
- case "removeAlias":
199
- guard let label = string("label") else { invalid("label gerekli"); return true }
200
- Pushizo.User.removeAlias(label); ok()
201
- case "setLanguage":
202
- guard let code = string("code") else { invalid("code gerekli"); return true }
203
- Pushizo.User.setLanguage(code); ok()
204
- case "addEmail", "removeEmail":
205
- let email = args["email"] as? String ?? ""
206
- guard HSContacts.normalizeEmail(email) != nil else { invalid("Geçersiz e-posta adresi."); return true }
207
- if method == "addEmail" { Pushizo.User.addEmail(email) } else { Pushizo.User.removeEmail(email) }
208
- ok()
209
- case "addSms", "removeSms":
210
- let phone = args["phoneNumber"] as? String ?? ""
211
- guard HSContacts.normalizePhone(phone) != nil else { invalid("Geçersiz telefon numarası (E.164 bekleniyor)."); return true }
212
- if method == "addSms" { Pushizo.User.addSms(phone) } else { Pushizo.User.removeSms(phone) }
213
- ok()
214
- case "getUser": ok(["id": Self.orNull(Pushizo.User.id), "externalId": Self.orNull(Pushizo.User.externalId)])
215
- case "getContacts": ok(["emails": Pushizo.User.emails, "smsNumbers": Pushizo.User.smsNumbers])
216
- // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
217
- case "getPreferences":
218
- inbox(reply) { Self.map(try await Pushizo.User.getPreferences()) }
219
- case "setPreferences":
220
- guard let raw = args["preferences"] as? [Any] else { invalid("preferences gerekli"); return true }
221
- let items = raw.compactMap { $0 as? [String: Any] }
222
- guard items.count == raw.count else { invalid("preferences öğeleri nesne olmalı"); return true }
223
- let inputs = items.map {
224
- HSPreferenceInput(category: $0["category"] as? String ?? "", channel: $0["channel"] as? String, optedIn: $0["optedIn"] as? Bool ?? false)
225
- }
226
- inbox(reply) { Self.map(try await Pushizo.User.setPreferences(inputs)) }
227
-
228
- case "getPushSubscription":
229
- Task {
230
- let state = await Pushizo.User.pushSubscription.state()
231
- DispatchQueue.main.async { ok(Self.map(state)) }
232
- }
233
- case "optIn": Pushizo.User.pushSubscription.optIn(); ok()
234
- case "optOut": Pushizo.User.pushSubscription.optOut(); ok()
235
-
236
- case "getPermission":
237
- Task {
238
- let status = await Pushizo.Notifications.permission()
239
- DispatchQueue.main.async { ok(["permission": Self.granted(status)]) }
240
- }
241
- case "requestPermission":
242
- // İzin değiştiyse `permissionChange` olayını yerel SDK izin gözlemcisi gönderir.
243
- Pushizo.Notifications.requestPermission { granted in
244
- DispatchQueue.main.async { ok(["permission": granted]) }
245
- }
246
- case "clearAll": Pushizo.Notifications.clearAll(); ok()
247
- // iOS kimliği `UNNotificationRequest.identifier` metnidir; tamsayı verilirse metne çevrilerek aranır.
248
- case "removeNotification":
249
- let requested = string("identifier") ?? (args["id"] as? NSNumber).map { "\($0.intValue)" }
250
- guard let identifier = requested else { invalid("identifier gerekli"); return true }
251
- Pushizo.Notifications.removeNotification(identifier: identifier); ok()
252
- case "removeGroupedNotifications":
253
- guard let group = string("group") else { invalid("group gerekli"); return true }
254
- Pushizo.Notifications.removeGroupedNotifications(group); ok()
255
- case "setForegroundHandlerEnabled": foregroundHandlerEnabled = args["enabled"] as? Bool ?? false; ok()
256
- case "displayNotification":
257
- guard let id = string("notificationId") else { invalid("notificationId gerekli"); return true }
258
- guard let event = takePending(id) else {
259
- reply(.failure(code: "NOT_FOUND", message: "Bildirim bulunamadı veya zaten gösterildi."))
260
- return true
261
- }
262
- event.display()
263
- ok()
264
-
265
- case "sendEvent":
266
- guard let name = string("name") else { invalid("name gerekli"); return true }
267
- Pushizo.Session.sendEvent(name, properties: args["properties"] as? [String: Any] ?? [:], value: (args["value"] as? NSNumber)?.doubleValue)
268
- ok()
269
- case "setLogLevel": Pushizo.Debug.setLogLevel(Self.logLevel(args["level"] as? String)); ok()
270
-
271
- case "addTriggers": Pushizo.InAppMessages.addTriggers(stringMap("triggers")); ok()
272
- case "removeTriggers": Pushizo.InAppMessages.removeTriggers(stringList("keys")); ok()
273
- case "clearTriggers": Pushizo.InAppMessages.clearTriggers(); ok()
274
- case "getTriggers": ok(["triggers": Pushizo.InAppMessages.getTriggers()])
275
- case "setScreen": Pushizo.InAppMessages.setScreen(args["name"] as? String); ok()
276
- case "setInAppPaused": Pushizo.InAppMessages.paused = args["paused"] as? Bool ?? false; ok()
277
- case "getInAppPaused": ok(["paused": Pushizo.InAppMessages.paused])
278
-
279
- case "inboxList":
280
- let limit = (args["limit"] as? NSNumber)?.intValue ?? 50
281
- let cursor = string("cursor")
282
- inbox(reply) { Self.map(try await Pushizo.Inbox.list(limit: limit, cursor: cursor)) }
283
- case "inboxMarkRead":
284
- guard let id = string("id") else { invalid("id gerekli"); return true }
285
- inbox(reply) { Self.map(try await Pushizo.Inbox.markRead(id)) }
286
- case "inboxMarkAllRead":
287
- inbox(reply) { ["unreadCount": try await Pushizo.Inbox.markAllRead()] }
288
- case "inboxArchive":
289
- guard let id = string("id") else { invalid("id gerekli"); return true }
290
- inbox(reply) { try await Pushizo.Inbox.archive(id); return nil }
291
- case "inboxUnreadCount":
292
- inbox(reply) { ["unreadCount": try await Pushizo.Inbox.unreadCount()] }
293
-
294
- // Konum (v2 Faz 17b; yalnızca ön plan): yerel SDK başlatılmadan çağrılırsa sessizce yok sayılmaz, NOT_READY döner.
295
- case "setLocationShared":
296
- guard Pushizo.isInitialized else { reply(.failure(code: "NOT_READY", message: Self.notInitialized)); return true }
297
- Pushizo.Location.setShared(args["shared"] as? Bool ?? false); ok()
298
- case "isLocationShared": ok(["shared": Pushizo.Location.isShared])
299
- case "requestLocationPermission":
300
- guard Pushizo.isInitialized else { reply(.failure(code: "NOT_READY", message: Self.notInitialized)); return true }
301
- // Açıklama uyarısı + `requestWhenInUseAuthorization`; sonuç ana iş parçacığında döner.
302
- Pushizo.Location.requestPermission(rationale: string("rationale")) { granted in ok(["permission": granted]) }
303
-
304
- // Canlı sohbet (ADR-0040): kimlik, kuyruk, akış ve push yerel SDK'dadır.
305
- case "chatStart":
306
- let name = string("name"), email = string("email"), language = string("language")
307
- inbox(reply) { try await Pushizo.Chat.start(name: name, email: email, language: language).dictionary }
308
- case "chatGetConfig":
309
- let language = string("language")
310
- inbox(reply) { try await Pushizo.Chat.getConfig(language: language).dictionary }
311
- case "chatGetConversation":
312
- inbox(reply) { try await Pushizo.Chat.getConversation().dictionary }
313
- case "chatGetMessages":
314
- let after = (args["afterSeq"] as? NSNumber)?.intValue
315
- let before = (args["beforeSeq"] as? NSNumber)?.intValue
316
- let limit = (args["limit"] as? NSNumber)?.intValue ?? 50
317
- inbox(reply) { try await Pushizo.Chat.getMessages(afterSeq: after, beforeSeq: before, limit: limit).dictionary }
318
- case "chatSendMessage":
319
- guard let text = string("text") else { invalid("text gerekli"); return true }
320
- let optionId = string("optionId")
321
- inbox(reply) { try await Pushizo.Chat.sendMessage(text, optionId: optionId).dictionary }
322
- case "chatSendAttachment":
323
- guard let fileName = string("fileName"), let mimeType = string("mimeType") else { invalid("fileName ve mimeType gerekli"); return true }
324
- let text = string("text")
325
- let data: Data
326
- if let base64 = string("base64") {
327
- guard let decoded = Data(base64Encoded: base64, options: .ignoreUnknownCharacters) else { invalid("base64 içerik çözülemedi"); return true }
328
- data = decoded
329
- } else if let uri = string("uri"), let url = URL(string: uri), url.isFileURL, let contents = try? Data(contentsOf: url) {
330
- data = contents
331
- } else {
332
- invalid("base64 veya okunabilir bir file:// uri gerekli"); return true
333
- }
334
- inbox(reply) { try await Pushizo.Chat.sendAttachment(data, fileName: fileName, mimeType: mimeType, text: text).dictionary }
335
- case "chatMarkRead":
336
- let seq = (args["seq"] as? NSNumber)?.intValue ?? 0
337
- inbox(reply) { ["unreadCount": try await Pushizo.Chat.markRead(seq)] }
338
- case "chatRefreshUnreadCount":
339
- inbox(reply) { ["unreadCount": try await Pushizo.Chat.refreshUnreadCount()] }
340
- case "chatGetUnreadCount": ok(["unreadCount": Pushizo.Chat.unreadCount])
341
- case "chatLeaveOfflineMessage":
342
- guard let email = string("email"), let text = string("text") else { invalid("email ve text gerekli"); return true }
343
- let name = string("name")
344
- inbox(reply) { try await Pushizo.Chat.leaveOfflineMessage(email: email, text: text, name: name).dictionary }
345
- case "chatSetTyping": Pushizo.Chat.setTyping(args["typing"] as? Bool ?? false); ok()
346
- case "chatStartListening": Pushizo.Chat.startListening(); ok()
347
- case "chatStopListening": Pushizo.Chat.stopListening(); ok()
348
- case "chatAttachmentUrl":
349
- guard let attachmentId = string("attachmentId") else { invalid("attachmentId gerekli"); return true }
350
- let download = args["download"] as? Bool ?? false
351
- inbox(reply) { ["url": try Pushizo.Chat.attachmentUrl(attachmentId, download: download).absoluteString] }
352
- case "chatGetVisitorId": ok(["visitorId": Self.orNull(Pushizo.Chat.visitorId)])
353
-
354
- // Live Activities (ADR-0024): genel `PushizoDefaultLiveActivityAttributes` türü; değer doğrulaması yerel SDK'dadır.
355
- case "setupDefaultLiveActivity":
356
- liveActivity(reply) { try Pushizo.LiveActivities.setupDefaultLiveActivity() }
357
- case "startDefaultLiveActivity":
358
- guard let activityId = string("activityId") else { invalid("activityId gerekli"); return true }
359
- guard let attributes = args["attributes"] as? [String: Any], let contentState = args["contentState"] as? [String: Any] else {
360
- invalid("attributes ve contentState nesne olmalı"); return true
361
- }
362
- liveActivity(reply) {
363
- try Pushizo.LiveActivities.startDefaultLiveActivity(activityId: activityId, attributes: attributes, contentState: contentState)
364
- }
365
- default:
366
- return false
367
- }
368
- return true
369
- }
370
-
371
- /// Bildirim kutusu çağrısı: sonuç ana iş parçacığında döner; hata kodu `HSApiError.code` veya SDK durumu.
372
- private func inbox(_ reply: @escaping (PushizoBridgeResult) -> Void, _ body: @escaping () async throws -> [String: Any]?) {
373
- Task {
374
- do {
375
- let value = try await body()
376
- DispatchQueue.main.async { reply(.success(value)) }
377
- } catch let error as HSApiError {
378
- DispatchQueue.main.async { reply(.failure(code: error.code, message: error.message)) }
379
- } catch HSChatError.invalidArgument(let message) {
380
- DispatchQueue.main.async { reply(.failure(code: "INVALID_ARGUMENT", message: message)) }
381
- } catch let error as HSError {
382
- let code: String
383
- switch error {
384
- case .invalidArgument: code = "INVALID_ARGUMENT"
385
- case .invalidResponse: code = "HS_ERROR"
386
- default: code = "NOT_READY"
387
- }
388
- DispatchQueue.main.async { reply(.failure(code: code, message: "\(error)")) }
389
- } catch {
390
- DispatchQueue.main.async { reply(.failure(code: "HS_ERROR", message: error.localizedDescription)) }
391
- }
392
- }
393
- }
394
-
395
- /// Live Activity çağrısı: `HSLiveActivityError` kodu ve mesajı aynen iletilir; beklenmeyen hata `LIVE_ACTIVITY_FAILED`.
396
- private func liveActivity(_ reply: (PushizoBridgeResult) -> Void, _ body: () throws -> Void) {
397
- do {
398
- try body()
399
- reply(.success(nil))
400
- } catch let error as HSLiveActivityError {
401
- reply(.failure(code: error.code, message: error.message))
402
- } catch {
403
- reply(.failure(code: "LIVE_ACTIVITY_FAILED", message: error.localizedDescription))
404
- }
405
- }
406
-
407
- // MARK: Eşleme
408
-
409
- static func logLevel(_ name: String?) -> HSLog.Level {
410
- switch name {
411
- case "none": return HSLog.Level.none
412
- case "error": return .error
413
- case "info": return .info
414
- case "debug": return .debug
415
- default: return .warn
416
- }
417
- }
418
-
419
- static func granted(_ status: UNAuthorizationStatus) -> Bool { status == .authorized || status == .provisional }
420
-
421
- static func orNull(_ value: Any?) -> Any { value ?? NSNull() }
422
-
423
- private static func millis(_ date: Date?) -> Any { date.map { Int64($0.timeIntervalSince1970 * 1000) } ?? NSNull() }
424
-
425
- static func map(_ n: HSNotification) -> [String: Any] {
426
- ["title": orNull(n.title), "body": orNull(n.body), "url": orNull(n.url), "imageUrl": orNull(n.imageUrl),
427
- "deliveryId": orNull(n.deliveryId), "messageId": orNull(n.messageId), "data": n.data, "androidNotificationId": NSNull()]
428
- }
429
-
430
- static func map(_ s: HSPushSubscriptionState) -> [String: Any] {
431
- ["id": orNull(s.id), "token": orNull(s.token), "optedIn": s.optedIn, "permission": granted(s.permission)]
432
- }
433
-
434
- static func map(_ item: HSInboxItem) -> [String: Any] {
435
- ["id": item.id, "messageId": orNull(item.messageId), "title": orNull(item.title), "body": orNull(item.body),
436
- "url": orNull(item.url), "imageUrl": orNull(item.imageUrl), "data": item.data, "read": item.read,
437
- "readAt": millis(item.readAt), "archivedAt": millis(item.archivedAt), "expiresAt": millis(item.expiresAt), "createdAt": millis(item.createdAt)]
438
- }
439
-
440
- static func map(_ p: HSPreference) -> [String: Any] {
441
- ["category": p.category, "channel": orNull(p.channel), "optedIn": p.optedIn, "explicit": p.explicit,
442
- "source": orNull(p.source), "updatedAt": millis(p.updatedAt)]
443
- }
444
-
445
- static func map(_ c: HSMessageCategory) -> [String: Any] {
446
- ["key": c.key, "name": c.name, "description": c.description, "channels": orNull(c.channels), "defaultOptedIn": c.defaultOptedIn]
447
- }
448
-
449
- static func map(_ r: HSPreferencesResult) -> [String: Any] {
450
- ["preferences": r.preferences.map { map($0) }, "categories": r.categories.map { map($0) }]
451
- }
452
-
453
- static func map(_ page: HSInboxPage) -> [String: Any] {
454
- ["items": page.items.map { map($0) }, "unreadCount": page.unreadCount, "nextCursor": orNull(page.nextCursor), "hasMore": page.hasMore]
455
- }
456
- }
457
-
458
- /// In-app yaşam döngüsünü etkin çekirdeğe yönlendirir (SDK dinleyiciyi zayıf değil güçlü tutar; tek örnek yeterli).
459
- final class PushizoBridgeLifecycleForwarder: HSInAppLifecycleListener {
460
- static let shared = PushizoBridgeLifecycleForwarder()
461
- func onWillDisplay(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("willDisplay", message) }
462
- func onDidDisplay(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("didDisplay", message) }
463
- func onWillDismiss(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("willDismiss", message) }
464
- func onDidDismiss(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("didDismiss", message) }
465
- }
1
+ import Foundation
2
+ import Pushizo
3
+ // SPM: ayrı modül; CocoaPods alt spec'leri tek "Pushizo" modülünde derlenir.
4
+ #if canImport(PushizoCore)
5
+ import PushizoCore
6
+ #endif
7
+ import UIKit
8
+ import UserNotifications
9
+
10
+ /// Köprü metot sonucu: başarıda isteğe bağlı sözlük, hatada kod ve mesaj.
11
+ enum PushizoBridgeResult {
12
+ case success([String: Any]?)
13
+ case failure(code: String, message: String)
14
+ }
15
+
16
+ /// JS `initialize` ayarlarının kalıcı kopyası (yalnızca herkese açık değerler; gizli bilgi tutulmaz).
17
+ struct PushizoBridgeConfig {
18
+ static let defaultsKey = "pushizo_bridge_config"
19
+ let appId: String
20
+ let apiUrl: String?
21
+ let requiresPrivacyConsent: Bool
22
+ let logLevel: String
23
+
24
+ func save() {
25
+ var dict: [String: Any] = ["appId": appId, "requiresPrivacyConsent": requiresPrivacyConsent, "logLevel": logLevel]
26
+ if let apiUrl { dict["apiUrl"] = apiUrl }
27
+ UserDefaults.standard.set(dict, forKey: Self.defaultsKey)
28
+ }
29
+
30
+ static func load() -> PushizoBridgeConfig? {
31
+ guard let dict = UserDefaults.standard.dictionary(forKey: defaultsKey),
32
+ let appId = dict["appId"] as? String, !appId.isEmpty else { return nil }
33
+ return PushizoBridgeConfig(appId: appId, apiUrl: dict["apiUrl"] as? String,
34
+ requiresPrivacyConsent: dict["requiresPrivacyConsent"] as? Bool ?? false,
35
+ logLevel: dict["logLevel"] as? String ?? "warn")
36
+ }
37
+
38
+ /// SDK'yı bu ayarlarla başlatır.
39
+ func initializeSdk() {
40
+ Pushizo.initialize(appId) { options in
41
+ if let apiUrl { options.apiUrl = apiUrl }
42
+ options.requiresPrivacyConsent = requiresPrivacyConsent
43
+ options.logLevel = PushizoBridgeCore.logLevel(logLevel)
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ Köprüden bağımsız iOS çekirdeği: JS metot adlarını Pushizo iOS SDK çağrılarına çevirir ve SDK olaylarını
50
+ `emit(tür, veri)` ile köprüye iletir. SDK dinleyicileri kaldırılamadığından süreç başına bir kez eklenir ve
51
+ o anki etkin çekirdeğe yönlendirilir.
52
+ */
53
+ final class PushizoBridgeCore: NSObject {
54
+ /// Olayların iletileceği etkin çekirdek (köprü yeniden yüklenirse güncellenir).
55
+ fileprivate static weak var active: PushizoBridgeCore?
56
+ private static var listenersRegistered = false
57
+ private static let maxPendingForeground = 32
58
+ private static let maxPlacementCache = 50
59
+ private static let notInitialized = "Önce Pushizo.initialize çağrılmalı"
60
+
61
+ private let emit: (String, [String: Any]) -> Void
62
+ /// JS tarafında ön plan dinleyicisi varsa gösterim JS kararına bırakılır.
63
+ var foregroundHandlerEnabled = false
64
+ private var foregroundSeq = 0
65
+ private var pendingForeground: [String: HSForegroundEvent] = [:]
66
+ private var pendingOrder: [String] = []
67
+ /// Son `placementsList` yanıtlarındaki mesajlar (kimliğe göre); raporlar bu nesnelerle yapılır, en eski kayıtlar düşürülür.
68
+ private var placementMessages: [String: HSInAppMessage] = [:]
69
+ private var placementOrder: [String] = []
70
+ private let lock = NSLock()
71
+
72
+ init(emit: @escaping (String, [String: Any]) -> Void) {
73
+ self.emit = emit
74
+ super.init()
75
+ Self.active = self
76
+ }
77
+
78
+ // MARK: Olaylar
79
+
80
+ /// SDK başlatılmışsa (kayıtlı ayarlarla) dinleyicileri bağlar.
81
+ func attachIfInitialized() {
82
+ if Pushizo.isInitialized { registerListeners() }
83
+ }
84
+
85
+ private func registerListeners() {
86
+ Self.active = self
87
+ guard !Self.listenersRegistered else { return }
88
+ Self.listenersRegistered = true
89
+ Pushizo.Notifications.addClickListener { e in
90
+ Self.active?.emit("click", ["notification": Self.map(e.notification),
91
+ "result": ["actionId": Self.orNull(e.actionId), "url": Self.orNull(e.url)]])
92
+ }
93
+ Pushizo.Notifications.addForegroundLifecycleListener { e in
94
+ guard let core = Self.active else { return }
95
+ core.onForeground(e)
96
+ }
97
+ Pushizo.User.pushSubscription.addObserver { s in
98
+ guard let core = Self.active else { return }
99
+ core.emit("pushSubscriptionChange", Self.map(s))
100
+ }
101
+ // Yerel SDK izin gözlemcisi: izin isteği sonucu ve uygulama yeniden etkinleştiğinde (izin Ayarlar'dan
102
+ // değişmiş olabilir) etkin izin değiştiyse çağrılır.
103
+ Pushizo.Notifications.addPermissionObserver { granted in
104
+ Self.active?.emit("permissionChange", ["permission": granted])
105
+ }
106
+ Pushizo.InAppMessages.addClickListener { e in
107
+ Self.active?.emit("inAppClick", ["message": ["id": e.messageId], "result": ["actionId": e.actionId, "url": Self.orNull(e.url)]])
108
+ }
109
+ Pushizo.InAppMessages.addLifecycleListener(PushizoBridgeLifecycleForwarder.shared)
110
+ // Canlı sohbet olayları → JS `chatEvent`; sohbet bildirimi tıklaması → `chatOpen` (cephe bekletir).
111
+ Pushizo.Chat.addListener { event in
112
+ var body = event.payload
113
+ body["type"] = event.type
114
+ Self.active?.emit("chatEvent", body)
115
+ }
116
+ Pushizo.Chat.addOpenListener { info in
117
+ Self.active?.emit("chatOpen", info.dictionary)
118
+ }
119
+ }
120
+
121
+ private func onForeground(_ event: HSForegroundEvent) {
122
+ lock.lock()
123
+ foregroundSeq += 1
124
+ let id = "fg-\(foregroundSeq)"
125
+ let pending = foregroundHandlerEnabled
126
+ if pending {
127
+ // Yerel gösterim ertelenir; JS `display()` çağırırsa veya hiçbir dinleyici engellemezse gösterilir
128
+ // (yanıt gelmezse SDK 25 sn sonra bildirimi göstermeden kapatır).
129
+ event.preventDefault()
130
+ pendingForeground[id] = event
131
+ pendingOrder.append(id)
132
+ while pendingOrder.count > Self.maxPendingForeground {
133
+ pendingForeground.removeValue(forKey: pendingOrder.removeFirst())
134
+ }
135
+ }
136
+ lock.unlock()
137
+ emit("foregroundWillDisplay", ["notificationId": id, "pending": pending, "notification": Self.map(event.notification)])
138
+ }
139
+
140
+ private func takePending(_ id: String) -> HSForegroundEvent? {
141
+ lock.lock()
142
+ defer { lock.unlock() }
143
+ pendingOrder.removeAll { $0 == id }
144
+ return pendingForeground.removeValue(forKey: id)
145
+ }
146
+
147
+ private func rememberPlacements(_ messages: [HSInAppMessage]) {
148
+ lock.lock()
149
+ defer { lock.unlock() }
150
+ for message in messages {
151
+ placementOrder.removeAll { $0 == message.id }
152
+ placementMessages[message.id] = message
153
+ placementOrder.append(message.id)
154
+ }
155
+ while placementOrder.count > Self.maxPlacementCache {
156
+ placementMessages.removeValue(forKey: placementOrder.removeFirst())
157
+ }
158
+ }
159
+
160
+ /// Rapor için mesajı son `placementsList` yanıtlarından bulur; bulunamazsa yok sayılır (yalnızca debug log).
161
+ private func placementMessage(_ id: String) -> HSInAppMessage? {
162
+ lock.lock()
163
+ defer { lock.unlock() }
164
+ guard let message = placementMessages[id] else {
165
+ if HSLog.level.rawValue >= HSLog.Level.debug.rawValue { print("[Pushizo] yerleşim mesajı bulunamadı: \(id)") }
166
+ return nil
167
+ }
168
+ return message
169
+ }
170
+
171
+ fileprivate func emitLifecycle(_ event: String, _ message: HSInAppMessage) {
172
+ emit("inAppLifecycle", ["event": event, "message": ["id": message.id]])
173
+ }
174
+
175
+ // MARK: Metotlar
176
+
177
+ /// Metodu çalıştırır; bilinmeyen metotta false döner.
178
+ func handle(_ method: String, _ args: [String: Any], reply: @escaping (PushizoBridgeResult) -> Void) -> Bool {
179
+ func ok(_ data: [String: Any]? = nil) { reply(.success(data)) }
180
+ func invalid(_ message: String) { reply(.failure(code: "INVALID_ARGUMENT", message: message)) }
181
+ func string(_ key: String) -> String? {
182
+ guard let value = args[key] as? String, !value.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
183
+ return value
184
+ }
185
+ func stringMap(_ key: String) -> [String: String] {
186
+ (args[key] as? [String: Any] ?? [:]).compactMapValues { value in
187
+ if value is NSNull { return nil }
188
+ return (value as? String) ?? "\(value)"
189
+ }
190
+ }
191
+ func stringList(_ key: String) -> [String] { (args[key] as? [Any] ?? []).compactMap { $0 as? String } }
192
+
193
+ switch method {
194
+ case "initialize":
195
+ guard let appId = string("appId") else { invalid("appId gerekli"); return true }
196
+ let config = PushizoBridgeConfig(appId: appId, apiUrl: string("apiUrl"),
197
+ requiresPrivacyConsent: args["requiresPrivacyConsent"] as? Bool ?? false,
198
+ logLevel: string("logLevel") ?? "warn")
199
+ // Soğuk başlatmada (bildirim tıklaması) SDK köprü yüklenir yüklenmez başlatılabilsin diye saklanır.
200
+ config.save()
201
+ config.initializeSdk()
202
+ registerListeners()
203
+ ok()
204
+ case "setConsentGiven": Pushizo.setConsentGiven(args["given"] as? Bool ?? false); ok()
205
+ case "login":
206
+ guard let externalId = string("externalId") else { invalid("externalId gerekli"); return true }
207
+ let identityHash = string("identityHash"), jwt = string("jwt")
208
+ // Kanıt app kipine uymuyorsa Android köprüsündeki gibi reddedilir (yerel SDK yalnızca loglar).
209
+ if let message = Pushizo.loginProofError(identityHash: identityHash, jwt: jwt) {
210
+ reply(.failure(code: "NOT_READY", message: message)); return true
211
+ }
212
+ Pushizo.login(externalId, identityHash: identityHash, jwt: jwt); ok()
213
+ case "updateUserJwt":
214
+ guard let jwt = string("jwt") else { invalid("jwt gerekli"); return true }
215
+ do {
216
+ try Pushizo.updateUserJwt(jwt); ok()
217
+ } catch {
218
+ reply(.failure(code: "NOT_READY", message: "Önce login ile kullanıcı kimliklendirilmeli"))
219
+ }
220
+ case "logout": Pushizo.logout(); ok()
221
+
222
+ case "addTags": Pushizo.User.addTags(stringMap("tags")); ok()
223
+ case "removeTags": Pushizo.User.removeTags(stringList("keys")); ok()
224
+ case "getTags": ok(["tags": Pushizo.User.getTags()])
225
+ case "addAliases": Pushizo.User.addAliases(stringMap("aliases")); ok()
226
+ case "removeAlias":
227
+ guard let label = string("label") else { invalid("label gerekli"); return true }
228
+ Pushizo.User.removeAlias(label); ok()
229
+ case "setLanguage":
230
+ guard let code = string("code") else { invalid("code gerekli"); return true }
231
+ Pushizo.User.setLanguage(code); ok()
232
+ case "addEmail", "removeEmail":
233
+ let email = args["email"] as? String ?? ""
234
+ guard HSContacts.normalizeEmail(email) != nil else { invalid("Geçersiz e-posta adresi."); return true }
235
+ if method == "addEmail" { Pushizo.User.addEmail(email) } else { Pushizo.User.removeEmail(email) }
236
+ ok()
237
+ case "addSms", "removeSms":
238
+ let phone = args["phoneNumber"] as? String ?? ""
239
+ guard HSContacts.normalizePhone(phone) != nil else { invalid("Geçersiz telefon numarası (E.164 bekleniyor)."); return true }
240
+ if method == "addSms" { Pushizo.User.addSms(phone) } else { Pushizo.User.removeSms(phone) }
241
+ ok()
242
+ case "getUser": ok(["id": Self.orNull(Pushizo.User.id), "externalId": Self.orNull(Pushizo.User.externalId)])
243
+ case "getContacts": ok(["emails": Pushizo.User.emails, "smsNumbers": Pushizo.User.smsNumbers])
244
+ // Tercihler (ADR-0019 §4): sahiplik kanıtı yerel SDK'da eklenir; doğrulama hatası INVALID_ARGUMENT, abonelik yoksa NOT_READY.
245
+ case "getPreferences":
246
+ inbox(reply) { Self.map(try await Pushizo.User.getPreferences()) }
247
+ case "setPreferences":
248
+ guard let raw = args["preferences"] as? [Any] else { invalid("preferences gerekli"); return true }
249
+ let items = raw.compactMap { $0 as? [String: Any] }
250
+ guard items.count == raw.count else { invalid("preferences öğeleri nesne olmalı"); return true }
251
+ let inputs = items.map {
252
+ HSPreferenceInput(category: $0["category"] as? String ?? "", channel: $0["channel"] as? String, optedIn: $0["optedIn"] as? Bool ?? false)
253
+ }
254
+ inbox(reply) { Self.map(try await Pushizo.User.setPreferences(inputs)) }
255
+
256
+ case "getPushSubscription":
257
+ Task {
258
+ let state = await Pushizo.User.pushSubscription.state()
259
+ DispatchQueue.main.async { ok(Self.map(state)) }
260
+ }
261
+ case "optIn": Pushizo.User.pushSubscription.optIn(); ok()
262
+ case "optOut": Pushizo.User.pushSubscription.optOut(); ok()
263
+
264
+ case "getPermission":
265
+ Task {
266
+ let status = await Pushizo.Notifications.permission()
267
+ DispatchQueue.main.async { ok(["permission": Self.granted(status)]) }
268
+ }
269
+ case "requestPermission":
270
+ // İzin değiştiyse `permissionChange` olayını yerel SDK izin gözlemcisi gönderir.
271
+ Pushizo.Notifications.requestPermission { granted in
272
+ DispatchQueue.main.async { ok(["permission": granted]) }
273
+ }
274
+ case "clearAll": Pushizo.Notifications.clearAll(); ok()
275
+ // iOS kimliği `UNNotificationRequest.identifier` metnidir; tamsayı verilirse metne çevrilerek aranır.
276
+ case "removeNotification":
277
+ let requested = string("identifier") ?? (args["id"] as? NSNumber).map { "\($0.intValue)" }
278
+ guard let identifier = requested else { invalid("identifier gerekli"); return true }
279
+ Pushizo.Notifications.removeNotification(identifier: identifier); ok()
280
+ case "removeGroupedNotifications":
281
+ guard let group = string("group") else { invalid("group gerekli"); return true }
282
+ Pushizo.Notifications.removeGroupedNotifications(group); ok()
283
+ case "setForegroundHandlerEnabled": foregroundHandlerEnabled = args["enabled"] as? Bool ?? false; ok()
284
+ case "displayNotification":
285
+ guard let id = string("notificationId") else { invalid("notificationId gerekli"); return true }
286
+ guard let event = takePending(id) else {
287
+ reply(.failure(code: "NOT_FOUND", message: "Bildirim bulunamadı veya zaten gösterildi."))
288
+ return true
289
+ }
290
+ event.display()
291
+ ok()
292
+
293
+ case "sendEvent":
294
+ guard let name = string("name") else { invalid("name gerekli"); return true }
295
+ Pushizo.Session.sendEvent(name, properties: args["properties"] as? [String: Any] ?? [:], value: (args["value"] as? NSNumber)?.doubleValue)
296
+ ok()
297
+ case "setLogLevel": Pushizo.Debug.setLogLevel(Self.logLevel(args["level"] as? String)); ok()
298
+
299
+ case "addTriggers": Pushizo.InAppMessages.addTriggers(stringMap("triggers")); ok()
300
+ case "removeTriggers": Pushizo.InAppMessages.removeTriggers(stringList("keys")); ok()
301
+ case "clearTriggers": Pushizo.InAppMessages.clearTriggers(); ok()
302
+ case "getTriggers": ok(["triggers": Pushizo.InAppMessages.getTriggers()])
303
+ case "setScreen": Pushizo.InAppMessages.setScreen(args["name"] as? String); ok()
304
+ case "setInAppPaused": Pushizo.InAppMessages.paused = args["paused"] as? Bool ?? false; ok()
305
+ case "getInAppPaused": ok(["paused": Pushizo.InAppMessages.paused])
306
+
307
+ case "inboxList":
308
+ let limit = (args["limit"] as? NSNumber)?.intValue ?? 50
309
+ let cursor = string("cursor")
310
+ inbox(reply) { Self.map(try await Pushizo.Inbox.list(limit: limit, cursor: cursor)) }
311
+ case "inboxMarkRead":
312
+ guard let id = string("id") else { invalid("id gerekli"); return true }
313
+ inbox(reply) { Self.map(try await Pushizo.Inbox.markRead(id)) }
314
+ case "inboxMarkAllRead":
315
+ inbox(reply) { ["unreadCount": try await Pushizo.Inbox.markAllRead()] }
316
+ case "inboxArchive":
317
+ guard let id = string("id") else { invalid("id gerekli"); return true }
318
+ inbox(reply) { try await Pushizo.Inbox.archive(id); return nil }
319
+ case "inboxUnreadCount":
320
+ inbox(reply) { ["unreadCount": try await Pushizo.Inbox.unreadCount()] }
321
+
322
+ // Konum (v2 Faz 17b; yalnızca ön plan): yerel SDK başlatılmadan çağrılırsa sessizce yok sayılmaz, NOT_READY döner.
323
+ case "setLocationShared":
324
+ guard Pushizo.isInitialized else { reply(.failure(code: "NOT_READY", message: Self.notInitialized)); return true }
325
+ Pushizo.Location.setShared(args["shared"] as? Bool ?? false); ok()
326
+ case "isLocationShared": ok(["shared": Pushizo.Location.isShared])
327
+ case "requestLocationPermission":
328
+ guard Pushizo.isInitialized else { reply(.failure(code: "NOT_READY", message: Self.notInitialized)); return true }
329
+ // Açıklama uyarısı + `requestWhenInUseAuthorization`; sonuç ana iş parçacığında döner.
330
+ Pushizo.Location.requestPermission(rationale: string("rationale")) { granted in ok(["permission": granted]) }
331
+ // Arka plan bölge izleme (ADR-0065): varsayılan kapalı; köprü izin istemez, Info.plist'e izin eklemez.
332
+ case "setGeofencingEnabled":
333
+ guard Pushizo.isInitialized else { reply(.failure(code: "NOT_READY", message: Self.notInitialized)); return true }
334
+ Pushizo.Location.setGeofencingEnabled(args["enabled"] as? Bool ?? false); ok()
335
+ case "isGeofencingEnabled": ok(["enabled": Pushizo.Location.isGeofencingEnabled])
336
+
337
+ // Özellik bayrakları (ADR-0066): değerler yerel SDK önbelleğinden okunur.
338
+ case "featureFlagsRefresh":
339
+ Task {
340
+ let success = await Pushizo.FeatureFlags.refresh()
341
+ DispatchQueue.main.async { ok(["success": success]) }
342
+ }
343
+ case "featureFlagsIsEnabled":
344
+ guard let key = string("key") else { invalid("key gerekli"); return true }
345
+ ok(["enabled": Pushizo.FeatureFlags.isEnabled(key, default: args["defaultValue"] as? Bool ?? false)])
346
+ case "featureFlagsGetValue":
347
+ guard let key = string("key") else { invalid("key gerekli"); return true }
348
+ ok(["value": Self.orNull(Pushizo.FeatureFlags.value(key))])
349
+
350
+ // Gömülü yerleşimler (ADR-0068): anahtar ve limit denetimi yerel SDK'dadır (HSError.invalidArgument → INVALID_ARGUMENT).
351
+ case "placementsList":
352
+ guard let key = string("key") else { invalid("key gerekli"); return true }
353
+ let limit = (args["limit"] as? NSNumber)?.intValue ?? 1
354
+ inbox(reply) {
355
+ let messages = try await Pushizo.Placements.list(key, limit: limit)
356
+ self.rememberPlacements(messages)
357
+ return ["messages": messages.map { Self.map($0) }]
358
+ }
359
+ case "placementsReportImpression":
360
+ guard let id = string("id") else { invalid("id gerekli"); return true }
361
+ if let message = placementMessage(id) { Pushizo.Placements.reportImpression(message) }
362
+ ok()
363
+ case "placementsReportClick":
364
+ guard let id = string("id"), let buttonId = string("buttonId") else { invalid("id ve buttonId gerekli"); return true }
365
+ if let message = placementMessage(id) { Pushizo.Placements.reportClick(message, buttonId: buttonId) }
366
+ ok()
367
+ case "placementsReportDismiss":
368
+ guard let id = string("id") else { invalid("id gerekli"); return true }
369
+ if let message = placementMessage(id) { Pushizo.Placements.reportDismiss(message) }
370
+ ok()
371
+
372
+ // Canlı sohbet (ADR-0040): kimlik, kuyruk, akış ve push yerel SDK'dadır.
373
+ case "chatStart":
374
+ let name = string("name"), email = string("email"), language = string("language")
375
+ inbox(reply) { try await Pushizo.Chat.start(name: name, email: email, language: language).dictionary }
376
+ case "chatGetConfig":
377
+ let language = string("language")
378
+ inbox(reply) { try await Pushizo.Chat.getConfig(language: language).dictionary }
379
+ case "chatGetConversation":
380
+ inbox(reply) { try await Pushizo.Chat.getConversation().dictionary }
381
+ case "chatGetMessages":
382
+ let after = (args["afterSeq"] as? NSNumber)?.intValue
383
+ let before = (args["beforeSeq"] as? NSNumber)?.intValue
384
+ let limit = (args["limit"] as? NSNumber)?.intValue ?? 50
385
+ inbox(reply) { try await Pushizo.Chat.getMessages(afterSeq: after, beforeSeq: before, limit: limit).dictionary }
386
+ case "chatSendMessage":
387
+ guard let text = string("text") else { invalid("text gerekli"); return true }
388
+ let optionId = string("optionId")
389
+ inbox(reply) { try await Pushizo.Chat.sendMessage(text, optionId: optionId).dictionary }
390
+ case "chatSendAttachment":
391
+ guard let fileName = string("fileName"), let mimeType = string("mimeType") else { invalid("fileName ve mimeType gerekli"); return true }
392
+ let text = string("text")
393
+ let data: Data
394
+ if let base64 = string("base64") {
395
+ guard let decoded = Data(base64Encoded: base64, options: .ignoreUnknownCharacters) else { invalid("base64 içerik çözülemedi"); return true }
396
+ data = decoded
397
+ } else if let uri = string("uri"), let url = URL(string: uri), url.isFileURL, let contents = try? Data(contentsOf: url) {
398
+ data = contents
399
+ } else {
400
+ invalid("base64 veya okunabilir bir file:// uri gerekli"); return true
401
+ }
402
+ inbox(reply) { try await Pushizo.Chat.sendAttachment(data, fileName: fileName, mimeType: mimeType, text: text).dictionary }
403
+ case "chatMarkRead":
404
+ let seq = (args["seq"] as? NSNumber)?.intValue ?? 0
405
+ inbox(reply) { ["unreadCount": try await Pushizo.Chat.markRead(seq)] }
406
+ case "chatRefreshUnreadCount":
407
+ inbox(reply) { ["unreadCount": try await Pushizo.Chat.refreshUnreadCount()] }
408
+ case "chatGetUnreadCount": ok(["unreadCount": Pushizo.Chat.unreadCount])
409
+ case "chatLeaveOfflineMessage":
410
+ guard let email = string("email"), let text = string("text") else { invalid("email ve text gerekli"); return true }
411
+ let name = string("name")
412
+ inbox(reply) { try await Pushizo.Chat.leaveOfflineMessage(email: email, text: text, name: name).dictionary }
413
+ case "chatSetTyping": Pushizo.Chat.setTyping(args["typing"] as? Bool ?? false); ok()
414
+ case "chatStartListening": Pushizo.Chat.startListening(); ok()
415
+ case "chatStopListening": Pushizo.Chat.stopListening(); ok()
416
+ case "chatAttachmentUrl":
417
+ guard let attachmentId = string("attachmentId") else { invalid("attachmentId gerekli"); return true }
418
+ let download = args["download"] as? Bool ?? false
419
+ inbox(reply) { ["url": try Pushizo.Chat.attachmentUrl(attachmentId, download: download).absoluteString] }
420
+ case "chatGetVisitorId": ok(["visitorId": Self.orNull(Pushizo.Chat.visitorId)])
421
+
422
+ // Live Activities (ADR-0024): genel `PushizoDefaultLiveActivityAttributes` türü; değer doğrulaması yerel SDK'dadır.
423
+ case "setupDefaultLiveActivity":
424
+ liveActivity(reply) { try Pushizo.LiveActivities.setupDefaultLiveActivity() }
425
+ case "startDefaultLiveActivity":
426
+ guard let activityId = string("activityId") else { invalid("activityId gerekli"); return true }
427
+ guard let attributes = args["attributes"] as? [String: Any], let contentState = args["contentState"] as? [String: Any] else {
428
+ invalid("attributes ve contentState nesne olmalı"); return true
429
+ }
430
+ liveActivity(reply) {
431
+ try Pushizo.LiveActivities.startDefaultLiveActivity(activityId: activityId, attributes: attributes, contentState: contentState)
432
+ }
433
+ default:
434
+ return false
435
+ }
436
+ return true
437
+ }
438
+
439
+ /// Bildirim kutusu çağrısı: sonuç ana iş parçacığında döner; hata kodu `HSApiError.code` veya SDK durumu.
440
+ private func inbox(_ reply: @escaping (PushizoBridgeResult) -> Void, _ body: @escaping () async throws -> [String: Any]?) {
441
+ Task {
442
+ do {
443
+ let value = try await body()
444
+ DispatchQueue.main.async { reply(.success(value)) }
445
+ } catch let error as HSApiError {
446
+ DispatchQueue.main.async { reply(.failure(code: error.code, message: error.message)) }
447
+ } catch HSChatError.invalidArgument(let message) {
448
+ DispatchQueue.main.async { reply(.failure(code: "INVALID_ARGUMENT", message: message)) }
449
+ } catch let error as HSError {
450
+ let code: String
451
+ switch error {
452
+ case .invalidArgument: code = "INVALID_ARGUMENT"
453
+ case .invalidResponse: code = "HS_ERROR"
454
+ default: code = "NOT_READY"
455
+ }
456
+ DispatchQueue.main.async { reply(.failure(code: code, message: "\(error)")) }
457
+ } catch {
458
+ DispatchQueue.main.async { reply(.failure(code: "HS_ERROR", message: error.localizedDescription)) }
459
+ }
460
+ }
461
+ }
462
+
463
+ /// Live Activity çağrısı: `HSLiveActivityError` kodu ve mesajı aynen iletilir; beklenmeyen hata `LIVE_ACTIVITY_FAILED`.
464
+ private func liveActivity(_ reply: (PushizoBridgeResult) -> Void, _ body: () throws -> Void) {
465
+ do {
466
+ try body()
467
+ reply(.success(nil))
468
+ } catch let error as HSLiveActivityError {
469
+ reply(.failure(code: error.code, message: error.message))
470
+ } catch {
471
+ reply(.failure(code: "LIVE_ACTIVITY_FAILED", message: error.localizedDescription))
472
+ }
473
+ }
474
+
475
+ // MARK: Eşleme
476
+
477
+ static func logLevel(_ name: String?) -> HSLog.Level {
478
+ switch name {
479
+ case "none": return HSLog.Level.none
480
+ case "error": return .error
481
+ case "info": return .info
482
+ case "debug": return .debug
483
+ default: return .warn
484
+ }
485
+ }
486
+
487
+ static func granted(_ status: UNAuthorizationStatus) -> Bool { status == .authorized || status == .provisional }
488
+
489
+ static func orNull(_ value: Any?) -> Any { value ?? NSNull() }
490
+
491
+ private static func millis(_ date: Date?) -> Any { date.map { Int64($0.timeIntervalSince1970 * 1000) } ?? NSNull() }
492
+
493
+ static func map(_ n: HSNotification) -> [String: Any] {
494
+ ["title": orNull(n.title), "body": orNull(n.body), "url": orNull(n.url), "imageUrl": orNull(n.imageUrl),
495
+ "deliveryId": orNull(n.deliveryId), "messageId": orNull(n.messageId), "data": n.data, "androidNotificationId": NSNull()]
496
+ }
497
+
498
+ static func map(_ s: HSPushSubscriptionState) -> [String: Any] {
499
+ ["id": orNull(s.id), "token": orNull(s.token), "optedIn": s.optedIn, "permission": granted(s.permission)]
500
+ }
501
+
502
+ static func map(_ item: HSInboxItem) -> [String: Any] {
503
+ ["id": item.id, "messageId": orNull(item.messageId), "title": orNull(item.title), "body": orNull(item.body),
504
+ "url": orNull(item.url), "imageUrl": orNull(item.imageUrl), "data": item.data, "read": item.read,
505
+ "readAt": millis(item.readAt), "archivedAt": millis(item.archivedAt), "expiresAt": millis(item.expiresAt), "createdAt": millis(item.createdAt)]
506
+ }
507
+
508
+ static func map(_ p: HSPreference) -> [String: Any] {
509
+ ["category": p.category, "channel": orNull(p.channel), "optedIn": p.optedIn, "explicit": p.explicit,
510
+ "source": orNull(p.source), "updatedAt": millis(p.updatedAt)]
511
+ }
512
+
513
+ static func map(_ c: HSMessageCategory) -> [String: Any] {
514
+ ["key": c.key, "name": c.name, "description": c.description, "channels": orNull(c.channels), "defaultOptedIn": c.defaultOptedIn]
515
+ }
516
+
517
+ static func map(_ r: HSPreferencesResult) -> [String: Any] {
518
+ ["preferences": r.preferences.map { map($0) }, "categories": r.categories.map { map($0) }]
519
+ }
520
+
521
+ static func map(_ page: HSInboxPage) -> [String: Any] {
522
+ ["items": page.items.map { map($0) }, "unreadCount": page.unreadCount, "nextCursor": orNull(page.nextCursor), "hasMore": page.hasMore]
523
+ }
524
+
525
+ // In-app mesaj modeli → JS `InAppMessage` (alanlar yerel modelle aynı; zamanlar epoch milisaniye).
526
+ static func map(_ m: HSInAppMessage) -> [String: Any] {
527
+ ["id": m.id, "priority": m.priority,
528
+ "triggers": m.triggers.map { map($0) }, "triggerGroups": m.triggerGroups.map { group in group.map { map($0) } },
529
+ "variantId": orNull(m.variantId), "display": map(m.display),
530
+ "remainingImpressions": m.remainingImpressions, "minIntervalSeconds": m.minIntervalSeconds,
531
+ "stopAfterInteraction": m.stopAfterInteraction, "lastImpressionAt": millis(m.lastImpressionAt), "endAt": millis(m.endAt),
532
+ "language": orNull(m.language)]
533
+ }
534
+
535
+ static func map(_ d: HSInAppDisplay) -> [String: Any] {
536
+ ["layout": d.layout.rawValue, "backgroundColor": orNull(d.backgroundColor), "textColor": orNull(d.textColor),
537
+ "dismissible": d.dismissible, "autoDismissSeconds": orNull(d.autoDismissSeconds), "contentType": d.contentType.rawValue,
538
+ "blocks": d.blocks.map { map($0) }, "html": orNull(d.html), "htmlHeight": orNull(d.htmlHeight)]
539
+ }
540
+
541
+ static func map(_ t: HSInAppTrigger) -> [String: Any] {
542
+ switch t {
543
+ case .sessionStart: return ["kind": "session_start"]
544
+ case let .event(name): return ["kind": "event", "name": name]
545
+ case let .screen(name): return ["kind": "screen", "name": name]
546
+ case let .condition(key, op, value):
547
+ let raw: Any
548
+ switch value {
549
+ case .string(let s)?: raw = s
550
+ case .number(let n)?: raw = n
551
+ case nil: raw = NSNull()
552
+ }
553
+ return ["kind": "trigger", "key": key, "op": op, "value": raw]
554
+ case let .sessionDuration(seconds): return ["kind": "session_duration", "seconds": seconds]
555
+ case let .unsupported(kind): return ["kind": "unsupported", "name": kind]
556
+ }
557
+ }
558
+
559
+ static func map(_ a: HSInAppAction) -> [String: Any] {
560
+ switch a {
561
+ case .dismiss: return ["type": "dismiss"]
562
+ case let .url(url): return ["type": "url", "url": url]
563
+ case let .deeplink(url): return ["type": "deeplink", "url": url]
564
+ case let .tags(tags): return ["type": "tags", "tags": tags]
565
+ case .pushPrompt: return ["type": "push_prompt"]
566
+ case let .outcome(name, value): return ["type": "outcome", "name": name, "value": orNull(value)]
567
+ }
568
+ }
569
+
570
+ static func map(_ b: HSInAppButton) -> [String: Any] {
571
+ ["id": b.id, "text": b.text, "action": map(b.action), "backgroundColor": orNull(b.backgroundColor), "textColor": orNull(b.textColor)]
572
+ }
573
+
574
+ static func map(_ c: HSInAppCarouselCard) -> [String: Any] {
575
+ ["id": c.id, "title": c.title, "body": orNull(c.body), "imageUrl": orNull(c.imageUrl), "imageAlt": orNull(c.imageAlt),
576
+ "button": c.button.map { map($0) } ?? NSNull()]
577
+ }
578
+
579
+ static func map(_ block: HSInAppBlock) -> [String: Any] {
580
+ switch block {
581
+ case let .image(url, alt): return ["type": "image", "url": url, "alt": orNull(alt)]
582
+ case let .title(text): return ["type": "title", "text": text]
583
+ case let .body(text): return ["type": "body", "text": text]
584
+ case let .button(button):
585
+ var json = map(button)
586
+ json["type"] = "button"
587
+ return json
588
+ case let .carousel(carousel): return ["type": "carousel", "id": carousel.id, "cards": carousel.cards.map { map($0) }]
589
+ }
590
+ }
591
+ }
592
+
593
+ /// In-app yaşam döngüsünü etkin çekirdeğe yönlendirir (SDK dinleyiciyi zayıf değil güçlü tutar; tek örnek yeterli).
594
+ final class PushizoBridgeLifecycleForwarder: HSInAppLifecycleListener {
595
+ static let shared = PushizoBridgeLifecycleForwarder()
596
+ func onWillDisplay(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("willDisplay", message) }
597
+ func onDidDisplay(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("didDisplay", message) }
598
+ func onWillDismiss(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("willDismiss", message) }
599
+ func onDidDismiss(_ message: HSInAppMessage) { PushizoBridgeCore.active?.emitLifecycle("didDismiss", message) }
600
+ }