bibleit

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 13 Imported by: 0

README

Bibleit Go client

A dependency-free Go client for reading and searching Bible translations, managing Lives, and inspecting your Bibleit account. It connects to the project-managed service at https://bibleit.app.

The client is released independently from the Bibleit CLI. Use the Go toolchain specified in go.mod. The CLI imports this library; the library does not depend on CLI configuration or credential storage.

Installation

Install the public module using ordinary Go module proxy and checksum verification:

go get github.com/bibleit-labs/bibleit-go

A sibling CLI checkout or Go workspace is not required. See contributing for standalone development.

Quickstart

Supply an API token to bibleit.NewClient(apiToken). The application chooses where to obtain the token; the library does not read environment variables.

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    bibleit "github.com/bibleit-labs/bibleit-go"
)

func main() {
    client, err := bibleit.NewClient(os.Getenv("BIBLEIT_TOKEN"))
    if err != nil {
        log.Fatal(err)
    }

    reading, err := client.ReadVerses(context.Background(), bibleit.Reference{
        Translation: "web",
        Book:        "John",
        Chapter:     3,
        Verse:       16,
    })
    if err != nil {
        log.Fatal(err)
    }
    for _, verse := range reading.Verses {
        fmt.Println(verse.Text)
    }
}

Use a translation enabled for your account; web is an example. The translation catalogue supplies book identifiers and names, which may be localized. Omit Verse to read a chapter, or both Chapter and Verse to read a book.

The constructor returns (*Client, error) and validates the API token before network access. Constructor errors do not include its value.

API overview

Methods Purpose
Ping, GetServerInfo, Help Inspect service availability and capabilities
GetIdentity, GetAccountInfo, ListQuotas Inspect identity, account details, and limits
ListTokens Inspect active personal token metadata
ListTranslations, GetTranslationInfo, GetTranslationCatalog Discover translations and their references
ReadVerses, SearchVerses Return typed readings and search results
CreateLive, ListLives, GetLive, SetLive Create, discover, and configure Lives
GetLiveStats, GetLiveStack, PushLive, PopLive, ControlLive Inspect and control Lives and their stacks

Read, Search, and Identity return protocol responses for callers that need records directly. Execute accepts validated command builders for additional operations such as translation add/remove and Live secret management. There is no arbitrary protocol-string constructor. Command.String() is intended for transport adapters and may contain a Live secret; avoid logging it.

Typed results preserve Raw records and unknown fields. Parsers reject malformed numbers/booleans, conflicting duplicates, inconsistent counts, and invalid stack positions instead of silently accepting them. Unknown status, role, permission, and error-code strings remain available.

Translation metadata and catalogue

GetTranslationInfo(ctx, slug) returns names, edition, update label, rights, attribution, and trademark details when supplied. GetTranslationCatalog(ctx, slug) returns ordered books and chapters. Book IDs are server identifiers, not array positions; IDs and chapter numbers may be sparse. Metadata availability does not guarantee installation or account enablement.

A catalogue chapter's Verses is the highest source verse identifier, not a dense count. Editions may omit verse numbers: an omitted individual verse returns verse_not_found, while a chapter read contains the available rows. Source numbering is preserved.

Readings and Lives

Reading.Book, Chapter, and Verse reflect coordinates supplied by the response header. Chapter/book reads and search results contain verse text without invented per-verse coordinates. Search coordinates are normally nil. Empty searches and stacks return empty slices.

Optional Live management fields use pointers so absence differs from false, zero, or an empty string. Public list/create replies may omit owner-only metadata. ControlLive accepts START, STOP, PAUSE, RESUME, CLEAR, and DELETE and returns the acknowledgement without a follow-up request. Push/pop retain all verse entries, including repeated translation names.

Token metadata

ListTokens(ctx) returns active personal credential metadata: IDs, sources, issuers, labels, scopes, timestamps, and retirement status when supplied. It returns no bearer values and is not a credential history; revoked and expired tokens are excluded. Missing scopes remain nil; an explicitly empty list means the credential inherits the actor's current permissions. Scopes restrict access and do not guarantee effective permissions.

Behavior and current limits

  • The service endpoint is fixed. Constructors and environment variables cannot override it. HTTPS certificate verification stays enabled and redirects are blocked.
  • All requests accept a context. The default HTTP timeout is 15 seconds. Operations are never retried automatically; a decoding failure after a mutation does not imply rollback.
  • Use NewClientWithHTTPClient(apiToken, httpClient) or NewAuthClientWithHTTPClient(httpClient) to customize transport and timeout. The supplied http.Client value is copied; its Transport and Jar remain shared. A custom client controls its own timeout, but redirects remain blocked.
  • Commands are limited to 8192 bytes, JSON request bodies to 16384 bytes, and finite responses to 2 MiB. Oversized or incomplete responses fail explicitly.
  • Request arguments support quoted whitespace, but embedded double quotes, CR, LF, and NUL are rejected. Backslashes are literal in requests. Escaped response strings do not define a request escape syntax.
  • Live secrets are generated by the server through CREATE/ROTATE. Custom SECRET SET is unsupported and rejected by the client.
  • HTTP subscriptions return streaming_requires_ssh. OpenSSH execution and subscriptions are provided by the CLI, not this HTTP library.
  • Browser authorization and credential storage belong to the application. The library provides code exchange and credential revocation.

Use errors.As with *bibleit.ServerError for protocol errors and RetryAfter() for rate-limit metadata. *bibleit.HTTPError represents HTTP failures without a usable protocol error and preserves available JSON error codes/metadata.

See the protocol contract and feature coverage for compatibility details.

Browser authorization

Use NewAuthClient() before an API token exists. Your application owns PKCE verifier generation, browser authorization, callback-state validation, and storage. Exchange an approved code, then construct an authenticated client:

auth, err := bibleit.NewAuthClient()
if err != nil {
    return err
}
credential, err := auth.ExchangeCode(ctx, bibleit.CodeExchange{
    Code: code, Verifier: verifier, DeviceName: "My application",
})
if err != nil {
    return err
}
client, err := bibleit.NewClient(credential.AccessToken)
if err != nil {
    return err
}

AuthorizationResult and its Fields contain the bearer value; avoid logging them. An authorization code is single-use, including when an invalid verifier consumes it. Omitting DeviceName uses the server's default label.

Call client.RevokeCredential(ctx) to revoke the credential. Only HTTP 204 is accepted as success. Revocation does not erase local storage or modify the client; subsequent authenticated requests with that credential are expected to fail.

Development

From this repository, using the toolchain in go.mod:

GOWORK=off go test -race ./...
GOWORK=off go vet ./...

Unit tests use in-memory transports. Shared protocol fixtures live in contract/fixtures/responses-v1.json. Native CI covers Linux, macOS, and Windows.

See the changelog and contributing guide. Contributions use Conventional Commits. Licensed under MIT.

The MIT software license does not grant rights to Bible translations returned by the service, account access or quotas. Report vulnerabilities privately through SECURITY.md.

Organization verification reads use ListOrganizations(ctx, cursor) and GetOrganizationApplicationStatus(ctx, id). Discover organization_status with GetServerInfo before using them against older servers. Applications grant no operating rights until Bibleit admin approval; membership is invitation-only.

Documentation

Overview

Package bibleit provides a client for Bibleit Server protocol v1. It does not read CLI configuration, open browsers, or manage credentials.

Index

Constants

View Source
const MaxCommandBytes = 8192
View Source
const MaxRequestBytes = 16384
View Source
const ServerEndpoint = "https://bibleit.app"

ServerEndpoint is the project-managed Bibleit service address. Applications cannot override it through configuration or environment variables. HTTPS certificate verification is enabled by the default transport.

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountInfo

type AccountInfo struct {
	Actor, DisplayName, Handle, AvatarURL, Locale, Theme string
	Plan, PlanName, PlanSource                           string
	PlanActivatedAt                                      int64
	Lives, Translations, Tokens, Keys                    int64
	Raw                                                  Response
}

type AuthClient

type AuthClient struct {
	// contains filtered or unexported fields
}

AuthClient exchanges an approved browser code. It does not run a browser, validate callback state, persist credentials, or retry a consumed code.

func NewAuthClient

func NewAuthClient() (*AuthClient, error)

NewAuthClient creates an unauthenticated client for browser-code exchange.

func NewAuthClientWithHTTPClient

func NewAuthClientWithHTTPClient(httpClient *http.Client) (*AuthClient, error)

NewAuthClientWithHTTPClient configures transport/timeouts for code exchange at the same fixed service endpoint. It copies the supplied HTTP client.

func (*AuthClient) ExchangeCode

func (c *AuthClient) ExchangeCode(ctx context.Context, exchange CodeExchange) (AuthorizationResult, error)

ExchangeCode redeems an approved one-use code with its PKCE verifier. Even a rejected verifier can consume the code on the current server.

type AuthorizationResult

type AuthorizationResult struct {
	Actor, IdentityName, DisplayName, AuthProvider, TokenID, AccessToken string
	Fields                                                               map[string]json.RawMessage
}

AuthorizationResult contains a secret AccessToken; Fields also contains the original JSON response, including that secret. Callers own secure storage.

type CatalogBook

type CatalogBook struct {
	ID       int64 // Server source book identifier; not the book's position in Books.
	Name     string
	Chapters []CatalogChapter
	Fields   map[string]string
}

type CatalogChapter

type CatalogChapter struct {
	Number int64
	// Verses is the highest source verse identifier, not the number of present
	// rows. Editions may omit identifiers; reading an omitted verse fails.
	Verses int64
	Fields map[string]string
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiToken string) (*Client, error)

NewClient creates a client using an API token and the project-managed service. The default HTTP timeout is 15 seconds. Operations are never retried automatically.

func NewClientWithHTTPClient

func NewClientWithHTTPClient(apiToken string, httpClient *http.Client) (*Client, error)

NewClientWithHTTPClient configures HTTP transport/timeouts while retaining the fixed service endpoint. The supplied HTTP client is copied and redirects blocked.

func (*Client) ControlLive

func (c *Client) ControlLive(ctx context.Context, id string, action LiveAction) (LiveActionResult, error)

func (*Client) CreateLive

func (c *Client) CreateLive(ctx context.Context, name string) (LiveResult, error)

func (*Client) Execute

func (c *Client) Execute(ctx context.Context, command Command) (Response, error)

func (*Client) GetAccountInfo

func (c *Client) GetAccountInfo(ctx context.Context) (AccountInfo, error)

func (*Client) GetIdentity

func (c *Client) GetIdentity(ctx context.Context) (IdentityInfo, error)

func (*Client) GetLive

func (c *Client) GetLive(ctx context.Context, id string) (LiveResult, error)

func (*Client) GetLiveStack

func (c *Client) GetLiveStack(ctx context.Context, id string) (LiveStack, error)

func (*Client) GetLiveStats

func (c *Client) GetLiveStats(ctx context.Context, id string) (LiveStatistics, error)

func (*Client) GetOrganizationApplicationStatus added in v0.0.2

func (c *Client) GetOrganizationApplicationStatus(ctx context.Context, id string) (OrganizationApplicationResult, error)

func (*Client) GetServerInfo

func (c *Client) GetServerInfo(ctx context.Context) (ServerInfo, error)

func (*Client) GetTranslationCatalog

func (c *Client) GetTranslationCatalog(ctx context.Context, slug string) (TranslationCatalog, error)

func (*Client) GetTranslationInfo

func (c *Client) GetTranslationInfo(ctx context.Context, slug string) (TranslationInfo, error)

func (*Client) Help

func (c *Client) Help(ctx context.Context, topic string) (HelpResult, error)

func (*Client) Identity

func (c *Client) Identity(ctx context.Context) (Response, error)

func (*Client) ListLives

func (c *Client) ListLives(ctx context.Context) (LiveList, error)

func (*Client) ListOrganizations added in v0.0.2

func (c *Client) ListOrganizations(ctx context.Context, cursor string) (OrganizationDirectory, error)

func (*Client) ListQuotas

func (c *Client) ListQuotas(ctx context.Context) (QuotaResult, error)

func (*Client) ListTokens

func (c *Client) ListTokens(ctx context.Context) (TokenList, error)

ListTokens lists active personal token metadata. The server filters expired, revoked and expired rotation-grace credentials; it does not return a history.

func (*Client) ListTranslations

func (c *Client) ListTranslations(ctx context.Context) (Response, error)

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) (Response, error)

func (*Client) PopLive

func (c *Client) PopLive(ctx context.Context, id string, count int) (LiveVerseResult, error)

func (*Client) PushLive

func (c *Client) PushLive(ctx context.Context, id string, ref Reference) (LiveVerseResult, error)

func (*Client) Read

func (c *Client) Read(ctx context.Context, ref Reference) (Response, error)

func (*Client) ReadVerses

func (c *Client) ReadVerses(ctx context.Context, ref Reference) (Reading, error)

func (*Client) RevokeCredential

func (c *Client) RevokeCredential(ctx context.Context) error

RevokeCredential revokes this client's bearer credential via CLI logout. Only HTTP 204 is a successful acknowledgement; errors never mutate the client.

func (*Client) Search

func (c *Client) Search(ctx context.Context, translation, query string) (Response, error)

func (*Client) SearchVerses

func (c *Client) SearchVerses(ctx context.Context, translation, query string) (Reading, error)

func (*Client) SetLive

func (c *Client) SetLive(ctx context.Context, id string, field LiveField, values ...string) (LiveResult, error)

type CodeExchange

type CodeExchange struct {
	Code, Verifier, DeviceName string
}

type Command

type Command struct {
	// contains filtered or unexported fields
}

Command is a validated customer operation. Its zero value is invalid. String exposes the wire representation for transport adapters; it may contain secrets.

func AccountInfoCommand

func AccountInfoCommand() Command

func AccountQuotasCommand

func AccountQuotasCommand() Command

func AccountTokensCommand

func AccountTokensCommand() Command

func AddTranslationCommand

func AddTranslationCommand(slug string) (Command, error)

func CreateLiveCommand

func CreateLiveCommand(name string) (Command, error)

func DeleteAllLivesCommand

func DeleteAllLivesCommand() Command

func HelpCommand

func HelpCommand(topic string) (Command, error)

HelpCommand asks the server for commands visible to the current principal. An empty topic selects the root. The server decides permission visibility.

func IdentityCommand

func IdentityCommand() Command

func LiveCommand

func LiveCommand(id string, action LiveAction) (Command, error)

func LiveListCommand

func LiveListCommand() Command

func LiveSecretCommand

func LiveSecretCommand(id string, action SecretAction, value string) (Command, error)

func LiveStackCommand

func LiveStackCommand(id string, action StackAction) (Command, error)

func OrganizationApplicationStatusCommand added in v0.0.2

func OrganizationApplicationStatusCommand(id string) (Command, error)

func OrganizationListCommand added in v0.0.2

func OrganizationListCommand(cursor string) (Command, error)

OrganizationListCommand returns one page; pass the previous Next cursor unchanged.

func PingCommand

func PingCommand() Command

func PopLiveCommand

func PopLiveCommand(id string, count int) (Command, error)

func PushLiveCommand

func PushLiveCommand(id string, ref Reference) (Command, error)

func ReadCommand

func ReadCommand(ref Reference) (Command, error)

func RemoveTranslationCommand

func RemoveTranslationCommand(slug string) (Command, error)

func SearchCommand

func SearchCommand(translation, query string) (Command, error)

func ServerInfoCommand

func ServerInfoCommand() Command

func SetLiveCommand

func SetLiveCommand(id string, field LiveField, values ...string) (Command, error)

func TranslationCatalogCommand

func TranslationCatalogCommand(slug string) (Command, error)

func TranslationInfoCommand

func TranslationInfoCommand(slug string) (Command, error)

func TranslationListCommand

func TranslationListCommand() Command

func (Command) Streaming

func (c Command) Streaming() bool

func (Command) String

func (c Command) String() string

type HTTPError

type HTTPError struct {
	StatusCode int
	Code       string
	Fields     map[string]any
}

HTTPError represents a failure without a usable protocol error envelope.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HelpEntry

type HelpEntry struct {
	Usage, Summary string
	// Auth is "none" when the server omits the auth field.
	Auth   string
	Fields map[string]string
}

type HelpResult

type HelpResult struct {
	Authenticated bool
	Commands      []HelpEntry
	Raw           Response
}

type IdentityInfo

type IdentityInfo struct {
	Actor, DisplayName, IdentityName, AuthProvider, KeyFingerprint string
	Authenticated                                                  bool
	Roles, Permissions                                             []string
	Raw                                                            Response
}

type LiveAction

type LiveAction string
const (
	LiveInfo      LiveAction = "INFO"
	LiveStats     LiveAction = "STATS"
	LiveStart     LiveAction = "START"
	LiveStop      LiveAction = "STOP"
	LivePause     LiveAction = "PAUSE"
	LiveResume    LiveAction = "RESUME"
	LiveClear     LiveAction = "CLEAR"
	LiveDelete    LiveAction = "DELETE"
	LiveSubscribe LiveAction = "SUBSCRIBE"
)

type LiveActionResult

type LiveActionResult struct {
	State  *LiveState
	Paused *bool
	Event  string
	Raw    Response
}

LiveActionResult reflects the server acknowledgement without fetching state.

type LiveConnection

type LiveConnection struct {
	Actor, Access                    string
	ConnectedAt, ConnectedForSeconds int64
	Fields                           map[string]string
}

type LiveField

type LiveField string
const (
	LiveName         LiveField = "NAME"
	LiveReference    LiveField = "REFERENCE"
	LiveTranslations LiveField = "TRANSLATIONS"
)

type LiveList

type LiveList struct {
	Lives []LiveState
	Raw   Response
}

type LiveResult

type LiveResult struct {
	Live LiveState
	Raw  Response
}

type LiveStack

type LiveStack struct {
	ID      string
	Entries []StackEntry
	Raw     Response
}

type LiveState

type LiveState struct {
	ID, Name, Status                            string
	Paused                                      bool
	Reference, Owner, CreatedBy, OrganizationID *string
	Owned, Protected                            *bool
	CreatedAt                                   *int64
	Translations                                []string
	Fields                                      map[string]string
}

type LiveStatistics

type LiveStatistics struct {
	ID                                                                                string
	RunningForSeconds, Revision, StackEntries, ActorConnections, AnonymousConnections int64
	Connections                                                                       []LiveConnection
	Raw                                                                               Response
}

type LiveVerse

type LiveVerse struct {
	Translation, Reference, Text string
	Fields                       map[string]string
}

type LiveVerseResult

type LiveVerseResult struct {
	Event  string
	Verses []LiveVerse
	Raw    Response
}

type OrganizationApplicationResult added in v0.0.2

type OrganizationApplicationResult struct {
	Application OrganizationDirectoryEntry
	Raw         Response
}

type OrganizationDirectory added in v0.0.2

type OrganizationDirectory struct {
	Entries []OrganizationDirectoryEntry
	Next    *string
	Raw     Response
}

type OrganizationDirectoryEntry added in v0.0.2

type OrganizationDirectoryEntry struct {
	Kind, ID, ApplicationID, Handle, Name, Domain, Role      string
	Verification, Status, State, NextAction, VerificationURL string
	OrganizationID                                           *string
	Fields                                                   map[string]string
}

OrganizationDirectoryEntry represents either a membership or a private application. State and verification strings remain open to future server values.

type Quota

type Quota struct {
	Permission string
	Limit      QuotaLimit
	Used       int64
	Fields     map[string]string
}

type QuotaLimit

type QuotaLimit struct {
	Unlimited bool
	Value     int64 // Meaningful only when Unlimited is false.
}

type QuotaResult

type QuotaResult struct {
	Quotas []Quota
	Raw    Response
}

type Reading

type Reading struct {
	Translation string
	// Multi-verse/search replies do not supply per-verse coordinates.
	Book, Chapter, Verse *int64
	Verses               []VerseText
	Raw                  Response
}

type Record

type Record struct {
	Type   string
	Fields map[string]string
	Order  []string
}

Record preserves unknown v1 fields and their wire order.

func ParseRecord

func ParseRecord(line string) (Record, error)

ParseRecord decodes response quoting and escaping, rejecting truncated strings.

type Reference

type Reference struct {
	Translation string
	Book        string
	Chapter     int
	Verse       int
}

Reference identifies a book, chapter, or verse. Zero chapter/verse means omitted.

type RequestSizeError

type RequestSizeError struct {
	Part  string
	Bytes int
	Limit int
}

RequestSizeError reports a request rejected locally before any network call.

func (*RequestSizeError) Error

func (e *RequestSizeError) Error() string

type Response

type Response struct {
	Lines   []string
	Records []Record
}

Response retains original lines for CLI raw output. END is excluded. Protocol v1 fields remain strings; future typed models can build on Records.

func DecodeCommandResponse

func DecodeCommandResponse(command Command, reader io.Reader) (Response, error)

DecodeCommandResponse uses the command's framing contract for a finite reply. Account translation replies contain count but are single records without END.

func DecodeResponse

func DecodeResponse(reader io.Reader) (Response, error)

DecodeResponse decodes one finite HTTP or SSH-exec reply, requiring END for multi-record replies. It is not a decoder for a persistent SSH subscription.

type SecretAction

type SecretAction string
const (
	SecretAuthenticate SecretAction = ""
	SecretCreate       SecretAction = "CREATE"
	SecretRotate       SecretAction = "ROTATE"
	SecretDelete       SecretAction = "DELETE"
)

type ServerError

type ServerError struct {
	Code   string
	Fields map[string]string
}

ServerError preserves the server code and metadata, including unknown codes.

func (*ServerError) Error

func (e *ServerError) Error() string

func (*ServerError) RetryAfter

func (e *ServerError) RetryAfter() time.Duration

type ServerInfo

type ServerInfo struct {
	ProtocolVersion int64
	Version         string
	Capabilities    []string
	Raw             Response
}

Typed results retain Raw for unknown fields and original wire records.

type StackAction

type StackAction string
const (
	StackInfo  StackAction = "INFO"
	StackClear StackAction = "CLEAR"
)

type StackEntry

type StackEntry struct {
	Position int64
	LiveVerse
}

type TokenList

type TokenList struct {
	Actor  string
	Tokens []TokenMetadata
	Raw    Response
}

type TokenMetadata

type TokenMetadata struct {
	ID, Source      string
	IssuedAt        int64
	IssuedBy, Label *string
	// Empty scopes inherit the actor's permissions. Nil means the field was absent;
	// it must not be interpreted as unrestricted authority.
	Scopes                []string
	LastUsedAt, ExpiresAt *int64
	Retiring              *bool
	Fields                map[string]string
}

TokenMetadata describes a currently active personal credential, never its value. Timestamp fields are Unix seconds. Optional fields remain nil when absent.

type TranslationCatalog

type TranslationCatalog struct {
	Translation string
	Books       []CatalogBook
	Raw         Response
}

type TranslationInfo

type TranslationInfo struct {
	ShortName, FullName                             string
	Edition, Updated                                string
	RightsStatus, RightsLabel, RightsURL, SourceURL string
	Attribution, TrademarkNotice                    string
	Raw                                             Response
}

type VerseText

type VerseText struct {
	Text   string
	Fields map[string]string
}

Directories

Path Synopsis
examples
read command
Read a verse using explicit server credentials supplied by the application.
Read a verse using explicit server credentials supplied by the application.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL