Skip to content

API at a glance

Every public type of CrmSdk 0.2.0, one line each. Types marked main actor are used from the main actor. The package’s sources hold each one’s full comment.

Crm (main actor): make one at launch and keep it.

MemberWhat it is
init(config:auth:host:)Makes the facade for the app config names.
config, authWhat it was made with.
hostYour hooks (CrmHost); may be changed at any time.
start() asyncReads the public face, restores events, records app_opened, follows the life cycle, looks for a deferred link. Once.
session(_:)Who is signed in: a CrmSession, or nil.
setReady(_:)Whether the app may show PurrCRM‘s places and in-app messages now.
currentSessionThe session now.
features, has(_:)The parts the user signed in has.
mayOpen(_:)Whether a destination may be opened now.
productName, isTestMode, languagesThe product’s name, test mode, the app’s languages.
unreadCrmValue<Int>: the messenger’s unread count.
readyCrmValue<Bool>: what setReady said.
publicAppCrmValue<CrmPublicApp?>: the app’s public face.
appFeaturesCrmValue<Set<CrmFeature>>: the parts the app has on.
sessionValueCrmValue<CrmSession?>: the session, with its features.
testPhoneCrmValue<Bool>: the user is a test phone.
messengerMessengerController.
ticketsCrmTickets.
helpCrmHelp.
inAppCrmInApp.
noticesCrmValue<CrmNotices>: the inbox.
track(_:_:)Records your own event.
screen(_:)Records the screen shown.
permissionChanged(_:allowed:) asyncThe user’s answer about "push" or "location".
flushEvents() asyncSends the queued events now.
appPaused() async, appResumed()The life cycle, when you follow it yourself.
dispose() asyncStops everything.
conversation(_:parts:)A ConversationSession for a conversation.
newConversation()A ConversationSession for a new one.
ticketConversation(_:parts:)A ConversationSession for a ticket.
isOnScreen(_:)Whether a conversation or ticket is on screen.
uploadPicture(_:type:name:progress:) async throwsUploads a picture; answers its attachment id.
registerPushToken(_: String, platform:) asyncRegisters the push token (Firebase’s).
forgetPushToken() asyncLets go of the token for the user signed in.
handlePushArrival(_:)A push arrived; answers a CrmPushResult.
handlePushTap(_:)A push was tapped; answers whether it was PurrCRM‘s.
refreshNotices() async, moreNotices() asyncReads the inbox again, or its next page.
markNoticesRead(_:all:) asyncMarks notices read.
offersByPush() async, setOffersByPush(_:) asyncThe consent to offers by push.
preferences(wording:)A CrmPreferencesKeeper for one screen, keeping each choice with your screen’s wording id (crmPreferencesWording when left out).
handleLink(_: URL) async, handleLink(_: String) asyncA link the phone handed you; answers whether it was PurrCRM‘s.
createLink(_:data:channel:) asyncA link the user shares (CrmSharedLink?).
referralLink() asyncThe user’s referral link (CrmReferralLink?).
open(_:) asyncOpens a destination through navigate.
showMessage(_:) asyncShows the in-app message with that id.
openLink(_:)Follows a link from content.
targetOf(_:)Where a link from content goes (LinkTarget?).
checkNow() asyncChecks in at once; answers how many tests came.
showSetupCheck()Shows the setup check.
runSetupChecks() asyncThe setup check’s rows.
setupFacts() asyncWhat the checks look at (SetupFacts).
setupReportText() asyncThe report, as text.
sendTestEvent() async, checkInForSetup() async, testPush() asyncThe setup check’s test actions; each answers what it did.
testLinks() async, tryLink(_:)Test links ([CrmTestLink]), and where one would go (CrmLinkTry).
TypeWhat it is
CrmConfigapiBase, appKey, appVersion, productName, storagePrefix, initialFeatures, customEvents, followLifecycle, languageTag, flushEvery, store, httpClient, clock, debug, releaseBuild, logger, clipboard; phoneLanguage().
CrmHostnavigate, followable, openInApp, openExternal, timeZone, askPermission, onUnreadChanged, links, linkOpened, installReferrer, deferredLinksFromClipboard.
CrmAuth.tokens(_:tokenFailure:), .unverified(_:); tokens, tokenFailure, userId.
CrmTokensProtocol: current() async throws -> String?, expired(_:) async.
CrmFetchedTokensActor over your backend: init(earlier:now:fetch:), earlier, current(), expired(_:), forget().
CrmFetchedTokeninit(_:expiresAt:), token, expiresAt, expiry.
CrmNoTokensNo token, for unverified sign-in.
CrmSessioninit(guestId:displayName:productEventsOff:features:), has(_:), withFeatures(_:).
crmFeaturesFor(_:_:)The features a session has of the app’s.
CrmFeature.messenger, .helpCenter, .inAppMessages.
TypeWhat it is
CrmValue<T> (main actor)value, observe(_:) (answers a CrmCancellable), stream, observerCount.
CrmCancellablecancel(); watching also stops when it is let go.
TypeWhat it is
CrmPlace.messenger, .newConversation, .conversation, .tickets, .ticket, .helpCenter, .collection, .article, .message, .preferences.
CrmDestinationplace, id, feature, gated, link; .conversation(_:), .ticket(_:), .collection(_:), .article(_:), .message(_:), .messenger, .newConversation, .tickets, .helpCenter, .preferences.
CrmLinksPurrCRM‘s paths (messages, newConversation, tickets, helpCenter, helpCollections, messageShow, preferences) and parse(_:), a path to a CrmDestination?.
CrmLinkA place you declare: name, path, webUrl, screen.
CrmLinkContextA link followed: path, from, saved, data, campaign, channel.
CrmLinkSpaceThe link space’s words and readers: prefix, clickParam, slugParam, shortRoot, claimReferrerParam, claimClipboardPrefix, shortSlug(_:), claimFromReferrer(_:), claimFromClipboard(_:), inAppPath(_:base:apiBase:).
LinkTarget.inApp(location) or .web(URL).
linkTarget(_:_:)Where a content link goes, by its rules.
CrmSharedLink, CrmReferralLinkslug, shortUrl, url.
SavedLinkOpenA saved link’s answer: path, saved, data, campaign, channel.
crmLinksDigest(_:)The digest of the places you declare.
CrmClipboardProtocol (main actor methods): hasStrings(), string(), clear(ifStill:). CrmPasteboard (UIPasteboard, a main-actor class) and CrmNoClipboard implement it.
TypeWhat it is
CrmPushResultisCrm, replyOnScreen, noticeId, silent.
CrmPushDatainit(_ userInfo:), type, noticeId, link, silent, isCrm.
CrmPushType.supportReply, .crmMessage.
CrmPushPlatform.ios, .android, .web.
CrmNoticesnotices, unread, loaded, loading, failure, nextBefore, hasMore.
CrmNoticeid, type, title, body, link, createdAt, readAt, unread, readOn(_:).
CrmNoticePage, CrmConsentA page of notices; the consent (offersByPush).
LimitscrmMaxPushTokenBytes, crmDefaultNoticePage, crmMaxNoticePage, crmMaxNoticesRead.
TypeWhat it is
MessengerController (main actor)state, load(), refresh(), loadMore().
MessengerStatehome, earlier, nextBefore, hasMore, unread, loading, loadingMore, message, opening.
MessengerHomeopen, unread, reply, articles, tickets, opening, layout, picturesAllowed.
MessengerLayoutgreeting, intro, faces, team, names, replyText, awayText, cards, newConversation, attachments, helpCenter.
HomeCard, HomeCardKindid, kind (.send, .searchHelp, .articles, .conversations, .tickets, .link, .status), title, text, link, articles.
MessengerOpeningThe help bot’s opening: workflow, version, parts, awaiting, question.
NewConversations, TeamFaces.always, .whenNoneOpen, .never; .auto, .chosen, .none.
ConversationSession (main actor)state, onScreen(_:), retry(), markReadNow(), addPicture(_:name:type:), removePicture(_:), send(_:), resend(_:), answerBot(_:button:value:), clearBotNote(), rate(_:remark:), close().
ChatStateid, ticketId, parts, thread, status, closed, lastSeq, reply, assignee, loading, loaded, gone, message, troubled, sending, sendMessage, sentSerial, pictures, uploading, note, rating, ratingMessage, ratingRequest, shown, awaiting, bot, botNote, botMessage, outgoing, opening, openingKnown, isNew.
PendingPicture, PictureStatuskey, bytes, contentType, name, status, progress, attachmentId; .uploading, .ready, .failed.
OutgoingMessage, OutgoingStatuskey, text, pictures, at, status, message, failed; .sending, .failed.
ComposerNote.tooLong, .tooManyPictures, .pictureTooLarge, .pictureWrongType, .waitForPictures.
RatingPhase, BotPhase, BotNote.open, .sending, .sent, .closed; .idle, .sending; .notEmail, .notOrderRef, .notText, .refused.
Conversation, ConversationSummary, ConversationPage, ConversationUpdateA conversation, a row of the list, a page of rows, what a wait brought.
ConversationState.open, .snoozed, .closed; isClosed.
Partid, seq, kind, author, text, blocks, attachments, state, rating, bot, createdAt.
PartKind.message, .reply, .note, .bot, .assignment, .state, .ratingRequest; guestSees.
Author, AuthorKindkind, name, isGuest; .guest, .teammate, .bot, .system.
Attachmentid, contentType, bytes, url, expiresAt.
BotPart, BotKind, BotButton, CollectFieldkind, buttons, collect, articles, reply, orderRef; .says, .asks, .collects, .suggests, .handsOff, .resolves; id, label; .text, .email, .orderRef.
CrmOrderRefAn order number’s shape: label, pattern, example, prop, upper, hint, check(_:).
ReplyExpectation, ReplyTime, ReplyLinewithin, open, opensAt; .minutes, .hours, .day; .within(_), .backAt(_:today:).
replyLine(_:_:calendar:)What to say about a reply.
isBubble(_:), placeParts(_:gap:calendar:), PartPlaceBubbles, and where each part sits (firstOfRun, newDay, timed).
shownToGuest(_:), fromStaff(_:), mergeParts(_:_:), unreadAfter(_:_:), newestStaffSeq(_:), openRatingRequest(_:), teammatesOf(_:most:)Rules about parts.
checkMessage(_:_:), MessageProblemA message’s check: .empty, .tooLong, .tooManyPictures.
checkPicture(_:_:), PictureProblem, pictureTypeOf(_:), pictureTypeOf(bytes:)A picture’s check (.wrongType, .tooLarge) and its type.
remarkFits(_:), checkCollected(_:_:_:), validEmail(_:)A rating’s remark; what the bot collects.
CrmPictureRefuseduploadPicture refused it: problem.
BackoffThe wait between failed tries: first, most, failures, next(), reset(), delayAfter(_:).
LimitsmaxMessageRunes (4000), maxAttachments (4), maxAttachmentBytes (5 MB), maxRemarkRunes (500), maxRating (5), maxCollectRunes, messengerWait, attachmentTypes.
TypeWhat it is
CrmTickets (main actor)list(), get(_:), write(_:text:attachmentIds:idempotencyKey:).
SupportTicketPage, SupportTicketSummaryitems; id, ref, title, type, state, updatedAt.
SupportTicketid, ref, title, type, state, description, fields, conversationId, parts, createdAt, updatedAt, resolvedAt.
TicketField, FieldTypekey, label, type, text, number, boolean, date, hasValue; .text, .list, .number, .boolean, .date.
TicketState.submitted, .inProgress, .waitingOnGuest, .resolved.
TypeWhat it is
CrmHelp (main actor)collections(), collection(_:), featured(), search(_:), article(_:), rate(_:helpful:).
Collection, Collectionsid, slug, title, description, articles; items.
CollectionArticlescollection, articles.
ArticleSummary, Articlesid, slug, title, summary, collection, updatedAt; items.
Articleid, slug, title, summary, blocks, collection, related, updatedAt, language, languages.
TypeWhat it is
CrmInApp (main actor)state (the queue, ready or not), next and banner (nil until setReady(true)), shown(_:path:), clicked(_:link:screen:button:path:), answered(_:screen:answers:path:), dismissed(_:screen:path:), completed(_:screen:path:), closed(_:), openLink(_:_:screen:path:), survey(_:), carousel(_:).
InAppStatebanner, waiting, showing, testPhone, next.
InAppMessageid, variant, kind, banner, post, carousel, survey, test, screens, large, drawable.
MessageKind.banner, .post, .carousel, .survey (and .chat, .push, .email, which are not drawn in the app).
InAppBanner, BannerStylestyle, blocks, dismissible, link; .inline, .floating.
InAppPostblocks, sender.
ReceiptAction.seen, .clicked, .dismissed, .completed, .answered.
SurveySession (main actor)message, survey, state, shown(), answer(_:), fits(_:_:), next(), back(), dismiss(), finish(), openLink(_:).
SurveyStatestep, answers, missing, sending, failed, done, over, path, canGoBack.
SurveyMove.moved, .missing(ids), .submitted, .failed, .closed, .stayed.
SubmitOutcome.sent, .closed, .failed.
Survey, SurveyFormatformat, intro, steps; .small, .large.
SurveyStep, SurveyStepKindid, kind, questions, blocks, branches; .questions, .thankYou.
SurveyQuestionid, type, title, description, required, options, other, min, max, minLabel, maxLabel, placeholder, range.
QuestionType.nps, .numeric, .stars, .emoji, .dropdown, .shortText, .longText, .singleChoice, .multiChoice; scaled, choice.
SurveyOption, SurveyBranchid, label; questionId, values, min, max, next.
SurveyAnswerinit(questionId:number:choices:other:text:), answered.
branchMatches, nextStep, surveyPath, unansweredRequired, answersOnPath, answerFits, checkSubmit, surveyPathIdsA survey’s rules, as PurrCRM keeps them.
LimitsotherOption ("other"), maxShortAnswerRunes (200), maxLongAnswerRunes (2000), maxOtherRunes (200), maxReceiptPath, checkinEvery.
CarouselSession (main actor)message, flow, state, screen, buttons, progress, seen(), tap(_:), choose(_:), swipeForward(), back(), close(), openLink(_:), done().
CarouselStateat, picked, frozen, busy, over, progress, dot, canGoBack, endedOnLink.
Carouselscreens, start, progress, skip, presentation, locked, style.
CarouselScreenid, layout, image, blocks, align, valign, background, buttons, choice, next, style.
CarouselImage, CarouselBackgroundurl, alt, size, aspect, fit, shape; kind, color, color2, angle, imageUrl, scrim.
CarouselButton, CarouselButtonActionid, label, style, action, screen, link, permission; .next, .screen, .back, .end, .link, .permission.
CarouselChoice, CarouselOptionmultiple, options; id, label, emoji, next.
CarouselStyleaccent, corner, buttonShape, textScale.
CarouselLayout, BackgroundKind, CarouselScrim, CarouselProgress, CarouselPresentation, CarouselCorner, CarouselButtonShape, CarouselTextScale, CarouselPermission.centred, .imageTop, .imageFull, .text; .plain, .color, .gradient, .image; .none, .light, .dark; .dots, .bar, .none; .sheet, .card, .full; .soft, .round, .square; .pill, .rounded; .compact, .regular, .large; .notifications, .location.
CarouselFlow, CarouselWalk, CarouselLead, carouselEndIndex, carouselEnd, maxCarouselScreensA carousel’s rules: where each screen and button leads, the way taken, and the screens’ order.
TypeWhat it is
ContentBlocktype, level, spans, items, imageUrl, alt, label, link, size, color, align, weight, tone, emoji, aspect, fit, shape, style, textSize, imageSize, spacerSize.
BlockType.paragraph, .heading, .bullets, .numbers, .image, .button, .divider, .eyebrow, .callout, .checklist, .spacer, .emoji.
Span, ListItemtext, bold, italic, link, underline, strike, highlight, color; spans.
ColorToken.accent, .ink, .muted, .surface, .wash, .good, .warn, .bad.
TextSize, TextWeight, ContentAlign, ContentVAlign, CalloutTone, SpacerSize, ImageSize, ImageAspect, ImageFit, ImageShape, ContentButtonStyleHow a block is drawn.
drawnBlocks(_:), plainText(_:), maxBlockLinkBytesThe blocks to draw, their text, the longest link.
TypeWhat it is
CrmPreferencesKeeper (main actor)state, wording, load(), choose(_:_:_:), turnAllOff().
PreferencesStatepreferences, loading, message, saving, saveMessage, kept.
CrmPreferences, CrmPreferenceTopic, CrmPreferenceStatetopics, allOff; id, name, description, channels; channel, subscribed.
CrmPreferenceChannel.email, .push, .inApp, .chat.
CrmPreferenceChoice, CrmPreferencesBody, CrmPublicPreferencesA choice sent, the body it goes in, the web page’s preferences.
withChoice(_:_:_:_:), allTurnedOff(_:)Preferences with a choice made, or all off.
crmPreferencesWording, crmMaxPreferenceChoices, crmMaxPreferenceWordingThe wording version kept with each choice, and limits.
TypeWhat it is
CrmEvent.appOpened, .sessionEnded, .screenViewed, .appUpdated, .pushPermissionChanged, .locationPermissionChanged, .pushOpened, .linkOpened.
CrmFlushResultHow a batch went: .nothing, .accepted(_), .refused(_), .failed(_).
EventBody, EventsBody, EventsAccepted, EventRejectedAn event, a batch, and PurrCRM‘s answer.
LimitsmaxEventBatch (50), maxEventProps (10), maxEventPropRunes (120), maxEventAge (7 days).
TypeWhat it is
CrmFailureWhy a request did not succeed; one of the four below.
CrmProblemPurrCRM said no: problem, status, code, error, detail, requestId, retryAfter; init(status:code:title:detail:scope:retryAfterSeconds:requestId:) for a fake.
CrmAppUnavailableThe app is archived or deleted: final.
CrmOfflineNo answer: cause, timedOut.
CrmContractErrorAn answer the SDK cannot read: message.
CrmTimedOutAn attempt past its deadline.
Problem, CrmErrorCode, CrmLimitScopeThe refusal (status, code, title, detail, scope, retryAfterSeconds, requestId, error, isTokenExpired, isAppUnavailable), its code, and whose limit.
CrmSentence.offline, .unavailable, .rateLimited, .rateLimitedGuest, .signInAgain, .badRequest, .notFound, .conversationGone, .ticketGone, .articleGone, .ratingClosed, .surveyClosed, .botMovedOn, .answerInvalid, .attachmentInvalid, .refused, .somethingWentWrong.
CrmAttempt.messenger, .ticket, .help, .other: what the user was doing.
CrmFailureMessagesentence, detail, retry, fromService.
CrmRetryHintat, after, soon, leftAt(_:), passedAt(_:).
tellCrmFailure(_:attempt:now:), tellCrmProblem(_:attempt:now:), crmSentenceFor(_:attempt:), shownCrmDetail(_:), crmRetryHint(_:now:)What to tell the user.
TypeWhat it is
CrmPublicAppkey, mode, brand, features, currency, orderRef, minSdkVersion, linkBase, languages, isTest.
CrmPublicBrandname, accent, logoUrl, supportEmail.
CrmPublicLinkApp, CrmPublicRatingBodyThe link page’s app, and a web page’s article rating.
isTestAppKey(_:)Whether a key is a test app’s.
testKeyInReleaseWarning, debugInReleaseWarningThe warnings a release build logs.
crmSdkVersion, crmSdkKind, CrmSdkKind"0.2.0", "ios"; .flutter, .android, .ios, .web.
CrmPlatform.ios, .android, .web.
TypeWhat it is
CrmSetupCheckA row: id, section, title, status, summary, detail, fix.
CrmCheckStatus.ok, .warning, .failure, .skipped.
SetupFactsEverything the checks look at.
setupChecks(_:)The rows for some facts.
setupReport(_:facts:at:)The report, as text.
CrmProbeHow a request went: status, milliseconds, requestId, failure, detail, ok.
CrmPushPermission.authorized, .provisional, .ephemeral, .denied, .notDetermined, .unknown.
CrmTestLink, CrmLinkTryname, url; ours, goes.
aasaCovers(_:bundleId:path:), associatedDomains(inProvision:)Reads the apple-app-site-association file, and a provision’s Associated Domains.

For tests, and for an app that hands the SDK its own storage or HTTP.

TypeWhat it is
CrmStoreProtocol: prefix, read(_:), write(_:_:), remove(_:).
DefaultsCrmStore, MemoryCrmStoreUserDefaults; memory (values, set(_:_:)).
crmStoreKey(_:_:), CrmStoreNameA key’s name, and the names the SDK keeps.
EventQueueStore, UsageStoreThe stores the event queue and the usage events keep.
CrmHttpClientProtocol: send(_:timeout:progress:), and send(_:timeout:).
CrmHttpRequest, CrmHttpResponsemethod, url, headers, body; status, headers, body.
URLSessionHttpClientThe SDK’s own, over URLSession.
CrmClock, SystemClocknow(), sleep(_:).
CrmTransport, HttpCrmTransport, CrmBody, CrmResponse, CrmRequestLogThe requests to PurrCRM, their bodies, answers and log lines.
MessengerApi, HelpApi, DeliveryApi, PreferencesApiThe guest routes over a CrmTransport, one call each, as the facade’s parts use them.
newIdempotencyKey()A fresh key for a send.
JsonValue, JsonError, Fields, FormatError, CrmTime, formatTime(_:)Reading and writing PurrCRM‘s JSON and times.
CrmWordThe vocabularies’ protocol: init(word:), word, unknown.
crmAppKeyHeader, crmUserIdHeader, crmSdkVersionHeader, crmSdkKindHeader, crmTestAppKeyPrefixThe headers and the test key’s prefix.

The request bodies (CheckinBody, ReceiptBody, MessageBody, StartBody, OpeningRef, ReadBody, RatingBody, AttachmentBody, AttachmentUpload, BotReplyBody, ArticleRatingBody, SurveyAnswerBody, SurveySubmit, OpenMessageBody, ShareLinkBody, LinkClaimBody, AppLinksReport, DeclaredLink, CrmDeviceBody, CrmForgetDeviceBody, CrmNoticesReadBody, CrmConsentBody, CrmUnreadCount, Checkin, CrmProblemBody, CrmRateLimited) and the data export’s models (ExportContact and the Export… and CrmExport… types) are public too, for tests against PurrCRM‘s contract; an app does not need them.