├── .gcloudignore ├── vendor ├── github.com │ ├── joho │ │ └── godotenv │ │ │ ├── .gitignore │ │ │ └── LICENCE │ ├── go-chi │ │ ├── chi │ │ │ ├── .gitignore │ │ │ ├── Makefile │ │ │ ├── LICENSE │ │ │ ├── CONTRIBUTING.md │ │ │ ├── chain.go │ │ │ ├── chi.go │ │ │ └── context.go │ │ └── cors │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ └── utils.go │ ├── google │ │ └── uuid │ │ │ ├── .travis.yml │ │ │ ├── CONTRIBUTORS │ │ │ ├── CONTRIBUTING.md │ │ │ ├── doc.go │ │ │ ├── node_js.go │ │ │ ├── README.md │ │ │ ├── marshal.go │ │ │ ├── node_net.go │ │ │ ├── version1.go │ │ │ ├── LICENSE │ │ │ ├── sql.go │ │ │ ├── hash.go │ │ │ ├── util.go │ │ │ ├── version4.go │ │ │ ├── dce.go │ │ │ ├── node.go │ │ │ ├── null.go │ │ │ └── time.go │ ├── tursodatabase │ │ └── libsql-client-go │ │ │ ├── libsql │ │ │ └── internal │ │ │ │ ├── hrana │ │ │ │ ├── pipeline_response.go │ │ │ │ ├── pipeline_request.go │ │ │ │ ├── batch.go │ │ │ │ ├── batch_result.go │ │ │ │ ├── stream_result.go │ │ │ │ ├── stmt.go │ │ │ │ ├── stmt_result.go │ │ │ │ ├── stream_request.go │ │ │ │ └── value.go │ │ │ │ ├── http │ │ │ │ ├── driver.go │ │ │ │ └── shared │ │ │ │ │ ├── result.go │ │ │ │ │ └── rows.go │ │ │ │ └── ws │ │ │ │ └── driver.go │ │ │ └── LICENSE │ ├── antlr │ │ └── antlr4 │ │ │ └── runtime │ │ │ └── Go │ │ │ └── antlr │ │ │ └── v4 │ │ │ ├── atn_type.go │ │ │ ├── char_stream.go │ │ │ ├── int_stream.go │ │ │ ├── token_source.go │ │ │ ├── token_stream.go │ │ │ ├── file_stream.go │ │ │ ├── trace_listener.go │ │ │ ├── atn_simulator.go │ │ │ ├── LICENSE │ │ │ ├── atn_deserialization_options.go │ │ │ ├── common_token_factory.go │ │ │ ├── input_stream.go │ │ │ ├── antlrdoc.go │ │ │ ├── rule_context.go │ │ │ ├── dfa_serializer.go │ │ │ ├── trees.go │ │ │ ├── error_listener.go │ │ │ ├── diagnostic_error_listener.go │ │ │ ├── dfa.go │ │ │ ├── utils_set.go │ │ │ ├── token.go │ │ │ ├── dfa_state.go │ │ │ └── comparators.go │ ├── klauspost │ │ └── compress │ │ │ └── flate │ │ │ ├── regmask_amd64.go │ │ │ └── regmask_other.go │ └── libsql │ │ └── sqlite-antlr4-parser │ │ └── sqliteparserutils │ │ └── utils.go ├── nhooyr.io │ └── websocket │ │ ├── .gitignore │ │ ├── internal │ │ ├── errd │ │ │ └── wrap.go │ │ ├── bpool │ │ │ └── bpool.go │ │ ├── xsync │ │ │ ├── go.go │ │ │ └── int64.go │ │ └── wsjs │ │ │ └── wsjs_js.go │ │ ├── conn.go │ │ ├── accept_js.go │ │ ├── doc.go │ │ ├── LICENSE.txt │ │ ├── wsjson │ │ └── wsjson.go │ │ ├── compress.go │ │ ├── close.go │ │ ├── stringer.go │ │ ├── compress_notjs.go │ │ ├── netconn.go │ │ ├── close_notjs.go │ │ └── README.md ├── golang.org │ └── x │ │ └── exp │ │ ├── PATENTS │ │ ├── LICENSE │ │ ├── constraints │ │ └── constraints.go │ │ └── slices │ │ └── sort.go └── modules.txt ├── .gitignore ├── scripts ├── buildprod.sh └── migrateup.sh ├── Dockerfile ├── sqlc.yaml ├── handler_ready.go ├── sql ├── schema │ ├── 001_users.sql │ └── 002_notes.sql └── queries │ ├── users.sql │ └── notes.sql ├── internal ├── database │ ├── models.go │ ├── db.go │ ├── users.sql.go │ └── notes.sql.go └── auth │ └── auth.go ├── go.mod ├── README.md ├── json.go ├── middleware_auth.go ├── models.go ├── handler_notes.go ├── handler_user.go └── main.go /.gcloudignore: -------------------------------------------------------------------------------- 1 | !notely 2 | -------------------------------------------------------------------------------- /vendor/github.com/joho/godotenv/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/.gitignore: -------------------------------------------------------------------------------- 1 | websocket.test 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | .env 3 | learn-cicd-starter 4 | notely 5 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.sw? 3 | .vscode 4 | -------------------------------------------------------------------------------- /scripts/buildprod.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o notely 4 | -------------------------------------------------------------------------------- /scripts/migrateup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ -f .env ]; then 4 | source .env 5 | fi 6 | 7 | cd sql/schema 8 | goose turso $DATABASE_URL up 9 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.4.3 5 | - 1.5.3 6 | - tip 7 | 8 | script: 9 | - go test -v ./... 10 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM --platform=linux/amd64 debian:stable-slim 2 | 3 | RUN apt-get update && apt-get install -y ca-certificates 4 | 5 | ADD notely /usr/bin/notely 6 | 7 | CMD ["notely"] 8 | -------------------------------------------------------------------------------- /sqlc.yaml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | sql: 3 | - schema: "sql/schema" 4 | queries: "sql/queries" 5 | engine: "sqlite" 6 | gen: 7 | go: 8 | out: "internal/database" 9 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Paul Borman 2 | bmatsuo 3 | shawnps 4 | theory 5 | jboverfelt 6 | dsymonds 7 | cd1 8 | wallclockbuilder 9 | dansouza 10 | -------------------------------------------------------------------------------- /handler_ready.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "net/http" 4 | 5 | func handlerReadiness(w http.ResponseWriter, r *http.Request) { 6 | respondWithJSON(w, http.StatusOK, map[string]string{"status": "ok"}) 7 | } 8 | -------------------------------------------------------------------------------- /sql/schema/001_users.sql: -------------------------------------------------------------------------------- 1 | -- +goose Up 2 | CREATE TABLE users ( 3 | id TEXT PRIMARY KEY, 4 | created_at TEXT NOT NULL, 5 | updated_at TEXT NOT NULL, 6 | name TEXT NOT NULL, 7 | api_key TEXT UNIQUE NOT NULL 8 | ); 9 | 10 | -- +goose Down 11 | DROP TABLE users; 12 | -------------------------------------------------------------------------------- /sql/queries/users.sql: -------------------------------------------------------------------------------- 1 | -- name: CreateUser :exec 2 | INSERT INTO users (id, created_at, updated_at, name, api_key) 3 | VALUES ( 4 | ?, 5 | ?, 6 | ?, 7 | ?, 8 | ? 9 | ); 10 | -- 11 | 12 | -- name: GetUser :one 13 | SELECT * FROM users WHERE api_key = ?; 14 | -- 15 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/pipeline_response.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | type PipelineResponse struct { 4 | Baton string `json:"baton,omitempty"` 5 | BaseUrl string `json:"base_url,omitempty"` 6 | Results []StreamResult `json:"results"` 7 | } 8 | -------------------------------------------------------------------------------- /sql/schema/002_notes.sql: -------------------------------------------------------------------------------- 1 | -- +goose Up 2 | CREATE TABLE notes ( 3 | id TEXT PRIMARY KEY, 4 | created_at TEXT NOT NULL, 5 | updated_at TEXT NOT NULL, 6 | note TEXT NOT NULL, 7 | user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE 8 | ); 9 | 10 | -- +goose Down 11 | DROP TABLE notes; 12 | -------------------------------------------------------------------------------- /sql/queries/notes.sql: -------------------------------------------------------------------------------- 1 | -- name: CreateNote :exec 2 | INSERT INTO notes (id, created_at, updated_at, note, user_id) 3 | VALUES (?, ?, ?, ?, ?); 4 | -- 5 | 6 | -- name: GetNote :one 7 | SELECT * FROM notes WHERE id = ?; 8 | -- 9 | 10 | -- name: GetNotesForUser :many 11 | SELECT * FROM notes WHERE user_id = ?; 12 | -- 13 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/http/driver.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | "database/sql/driver" 5 | 6 | "github.com/tursodatabase/libsql-client-go/libsql/internal/http/hranaV2" 7 | ) 8 | 9 | func Connect(url, jwt, host string) driver.Conn { 10 | return hranaV2.Connect(url, jwt, host) 11 | } 12 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/pipeline_request.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | type PipelineRequest struct { 4 | Baton string `json:"baton,omitempty"` 5 | Requests []StreamRequest `json:"requests"` 6 | } 7 | 8 | func (pr *PipelineRequest) Add(request StreamRequest) { 9 | pr.Requests = append(pr.Requests, request) 10 | } 11 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | We definitely welcome patches and contribution to this project! 4 | 5 | ### Legal requirements 6 | 7 | In order to protect both you and ourselves, you will need to sign the 8 | [Contributor License Agreement](https://cla.developers.google.com/clas). 9 | 10 | You may have already signed it for other Google projects. 11 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/atn_type.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | // Represent the type of recognizer an ATN applies to. 8 | const ( 9 | ATNTypeLexer = 0 10 | ATNTypeParser = 1 11 | ) 12 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/internal/errd/wrap.go: -------------------------------------------------------------------------------- 1 | package errd 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Wrap wraps err with fmt.Errorf if err is non nil. 8 | // Intended for use with defer and a named error return. 9 | // Inspired by https://github.com/golang/go/issues/32676. 10 | func Wrap(err *error, f string, v ...interface{}) { 11 | if *err != nil { 12 | *err = fmt.Errorf(f+": %w", append(v, *err)...) 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/conn.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | // MessageType represents the type of a WebSocket message. 4 | // See https://tools.ietf.org/html/rfc6455#section-5.6 5 | type MessageType int 6 | 7 | // MessageType constants. 8 | const ( 9 | // MessageText is for UTF-8 encoded text messages like JSON. 10 | MessageText MessageType = iota + 1 11 | // MessageBinary is for binary messages like protobufs. 12 | MessageBinary 13 | ) 14 | -------------------------------------------------------------------------------- /internal/database/models.go: -------------------------------------------------------------------------------- 1 | // Code generated by sqlc. DO NOT EDIT. 2 | // versions: 3 | // sqlc v1.25.0 4 | 5 | package database 6 | 7 | import () 8 | 9 | type Note struct { 10 | ID string 11 | CreatedAt string 12 | UpdatedAt string 13 | Note string 14 | UserID string 15 | } 16 | 17 | type User struct { 18 | ID string 19 | CreatedAt string 20 | UpdatedAt string 21 | Name string 22 | ApiKey string 23 | } 24 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | @echo "**********************************************************" 3 | @echo "** chi build tool **" 4 | @echo "**********************************************************" 5 | 6 | 7 | test: 8 | go clean -testcache && $(MAKE) test-router && $(MAKE) test-middleware 9 | 10 | test-router: 11 | go test -race -v . 12 | 13 | test-middleware: 14 | go test -race -v ./middleware 15 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/http/shared/result.go: -------------------------------------------------------------------------------- 1 | package shared 2 | 3 | type result struct { 4 | id int64 5 | changes int64 6 | } 7 | 8 | func NewResult(id, changes int64) *result { 9 | return &result{id: id, changes: changes} 10 | } 11 | 12 | func (r *result) LastInsertId() (int64, error) { 13 | return r.id, nil 14 | } 15 | 16 | func (r *result) RowsAffected() (int64, error) { 17 | return r.changes, nil 18 | } 19 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/char_stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type CharStream interface { 8 | IntStream 9 | GetText(int, int) string 10 | GetTextFromTokens(start, end Token) string 11 | GetTextFromInterval(*Interval) string 12 | } 13 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/int_stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type IntStream interface { 8 | Consume() 9 | LA(int) int 10 | Mark() int 11 | Release(marker int) 12 | Index() int 13 | Seek(index int) 14 | Size() int 15 | GetSourceName() string 16 | } 17 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package uuid generates and inspects UUIDs. 6 | // 7 | // UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security 8 | // Services. 9 | // 10 | // A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to 11 | // maps or compared directly. 12 | package uuid 13 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/internal/bpool/bpool.go: -------------------------------------------------------------------------------- 1 | package bpool 2 | 3 | import ( 4 | "bytes" 5 | "sync" 6 | ) 7 | 8 | var bpool sync.Pool 9 | 10 | // Get returns a buffer from the pool or creates a new one if 11 | // the pool is empty. 12 | func Get() *bytes.Buffer { 13 | b := bpool.Get() 14 | if b == nil { 15 | return &bytes.Buffer{} 16 | } 17 | return b.(*bytes.Buffer) 18 | } 19 | 20 | // Put returns a buffer into the pool. 21 | func Put(b *bytes.Buffer) { 22 | b.Reset() 23 | bpool.Put(b) 24 | } 25 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/internal/xsync/go.go: -------------------------------------------------------------------------------- 1 | package xsync 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // Go allows running a function in another goroutine 8 | // and waiting for its error. 9 | func Go(fn func() error) <-chan error { 10 | errs := make(chan error, 1) 11 | go func() { 12 | defer func() { 13 | r := recover() 14 | if r != nil { 15 | select { 16 | case errs <- fmt.Errorf("panic in go fn: %v", r): 17 | default: 18 | } 19 | } 20 | }() 21 | errs <- fn() 22 | }() 23 | 24 | return errs 25 | } 26 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/internal/xsync/int64.go: -------------------------------------------------------------------------------- 1 | package xsync 2 | 3 | import ( 4 | "sync/atomic" 5 | ) 6 | 7 | // Int64 represents an atomic int64. 8 | type Int64 struct { 9 | // We do not use atomic.Load/StoreInt64 since it does not 10 | // work on 32 bit computers but we need 64 bit integers. 11 | i atomic.Value 12 | } 13 | 14 | // Load loads the int64. 15 | func (v *Int64) Load() int64 { 16 | i, _ := v.i.Load().(int64) 17 | return i 18 | } 19 | 20 | // Store stores the int64. 21 | func (v *Int64) Store(i int64) { 22 | v.i.Store(i) 23 | } 24 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/accept_js.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "errors" 5 | "net/http" 6 | ) 7 | 8 | // AcceptOptions represents Accept's options. 9 | type AcceptOptions struct { 10 | Subprotocols []string 11 | InsecureSkipVerify bool 12 | OriginPatterns []string 13 | CompressionMode CompressionMode 14 | CompressionThreshold int 15 | } 16 | 17 | // Accept is stubbed out for Wasm. 18 | func Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error) { 19 | return nil, errors.New("unimplemented") 20 | } 21 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/token_source.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type TokenSource interface { 8 | NextToken() Token 9 | Skip() 10 | More() 11 | GetLine() int 12 | GetCharPositionInLine() int 13 | GetInputStream() CharStream 14 | GetSourceName() string 15 | setTokenFactory(factory TokenFactory) 16 | GetTokenFactory() TokenFactory 17 | } 18 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/node_js.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build js 6 | 7 | package uuid 8 | 9 | // getHardwareInterface returns nil values for the JS version of the code. 10 | // This remvoves the "net" dependency, because it is not used in the browser. 11 | // Using the "net" library inflates the size of the transpiled JS code by 673k bytes. 12 | func getHardwareInterface(name string) (string, []byte) { return "", nil } 13 | -------------------------------------------------------------------------------- /internal/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import ( 4 | "errors" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | var ErrNoAuthHeaderIncluded = errors.New("no authorization header included") 10 | 11 | // GetAPIKey - 12 | func GetAPIKey(headers http.Header) (string, error) { 13 | authHeader := headers.Get("Authorization") 14 | if authHeader == "" { 15 | return "", ErrNoAuthHeaderIncluded 16 | } 17 | splitAuth := strings.Split(authHeader, " ") 18 | if len(splitAuth) < 2 || splitAuth[0] != "ApiKey" { 19 | return "", errors.New("malformed authorization header") 20 | } 21 | 22 | return splitAuth[1], nil 23 | } 24 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/token_stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type TokenStream interface { 8 | IntStream 9 | 10 | LT(k int) Token 11 | 12 | Get(index int) Token 13 | GetTokenSource() TokenSource 14 | SetTokenSource(TokenSource) 15 | 16 | GetAllText() string 17 | GetTextFromInterval(*Interval) string 18 | GetTextFromRuleContext(RuleContext) string 19 | GetTextFromTokens(Token, Token) string 20 | } 21 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/bootdotdev/learn-cicd-starter 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/go-chi/chi v1.5.4 7 | github.com/go-chi/cors v1.2.1 8 | github.com/google/uuid v1.3.0 9 | github.com/joho/godotenv v1.5.1 10 | github.com/tursodatabase/libsql-client-go v0.0.0-20240220085343-4ae0eb9d0898 11 | ) 12 | 13 | require ( 14 | github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230512164433-5d1fd1a340c9 // indirect 15 | github.com/klauspost/compress v1.15.15 // indirect 16 | github.com/libsql/sqlite-antlr4-parser v0.0.0-20230802215326-5cb5bb604475 // indirect 17 | golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect 18 | nhooyr.io/websocket v1.8.7 // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # learn-cicd-starter (Notely) 2 | 3 | This repo contains the starter code for the "Notely" application for the "Learn CICD" course on [Boot.dev](https://boot.dev). 4 | 5 | ## Local Development 6 | 7 | Make sure you're on Go version 1.22+. 8 | 9 | Create a `.env` file in the root of the project with the following contents: 10 | 11 | ```bash 12 | PORT="8080" 13 | ``` 14 | 15 | Run the server: 16 | 17 | ```bash 18 | go build -o notely && ./notely 19 | ``` 20 | 21 | *This starts the server in non-database mode.* It will serve a simple webpage at `http://localhost:8080`. 22 | 23 | You do *not* need to set up a database or any interactivity on the webpage yet. Instructions for that will come later in the course! 24 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/batch.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | type Batch struct { 4 | Steps []BatchStep `json:"steps"` 5 | ReplicationIndex *uint64 `json:"replication_index,omitempty"` 6 | } 7 | 8 | type BatchStep struct { 9 | Stmt Stmt `json:"stmt"` 10 | Condition *BatchCondition `json:"condition,omitempty"` 11 | } 12 | 13 | type BatchCondition struct { 14 | Type string `json:"type"` 15 | Step *int32 `json:"step,omitempty"` 16 | Cond *BatchCondition `json:"cond,omitempty"` 17 | Conds []BatchCondition `json:"conds,omitempty"` 18 | } 19 | 20 | func (b *Batch) Add(stmt Stmt) { 21 | b.Steps = append(b.Steps, BatchStep{Stmt: stmt}) 22 | } 23 | -------------------------------------------------------------------------------- /internal/database/db.go: -------------------------------------------------------------------------------- 1 | // Code generated by sqlc. DO NOT EDIT. 2 | // versions: 3 | // sqlc v1.25.0 4 | 5 | package database 6 | 7 | import ( 8 | "context" 9 | "database/sql" 10 | ) 11 | 12 | type DBTX interface { 13 | ExecContext(context.Context, string, ...interface{}) (sql.Result, error) 14 | PrepareContext(context.Context, string) (*sql.Stmt, error) 15 | QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) 16 | QueryRowContext(context.Context, string, ...interface{}) *sql.Row 17 | } 18 | 19 | func New(db DBTX) *Queries { 20 | return &Queries{db: db} 21 | } 22 | 23 | type Queries struct { 24 | db DBTX 25 | } 26 | 27 | func (q *Queries) WithTx(tx *sql.Tx) *Queries { 28 | return &Queries{ 29 | db: tx, 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /json.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | func respondWithError(w http.ResponseWriter, code int, msg string, logErr error) { 10 | if logErr != nil { 11 | log.Println(logErr) 12 | } 13 | if code > 499 { 14 | log.Printf("Responding with 5XX error: %s", msg) 15 | } 16 | type errorResponse struct { 17 | Error string `json:"error"` 18 | } 19 | respondWithJSON(w, code, errorResponse{ 20 | Error: msg, 21 | }) 22 | } 23 | 24 | func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) { 25 | w.Header().Set("Content-Type", "application/json") 26 | dat, err := json.Marshal(payload) 27 | if err != nil { 28 | log.Printf("Error marshalling JSON: %s", err) 29 | w.WriteHeader(500) 30 | return 31 | } 32 | w.WriteHeader(code) 33 | w.Write(dat) 34 | } 35 | -------------------------------------------------------------------------------- /middleware_auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/bootdotdev/learn-cicd-starter/internal/auth" 7 | "github.com/bootdotdev/learn-cicd-starter/internal/database" 8 | ) 9 | 10 | type authedHandler func(http.ResponseWriter, *http.Request, database.User) 11 | 12 | func (cfg *apiConfig) middlewareAuth(handler authedHandler) http.HandlerFunc { 13 | return func(w http.ResponseWriter, r *http.Request) { 14 | apiKey, err := auth.GetAPIKey(r.Header) 15 | if err != nil { 16 | respondWithError(w, http.StatusUnauthorized, "Couldn't find api key", err) 17 | return 18 | } 19 | 20 | user, err := cfg.DB.GetUser(r.Context(), apiKey) 21 | if err != nil { 22 | respondWithError(w, http.StatusNotFound, "Couldn't get user", err) 23 | return 24 | } 25 | 26 | handler(w, r, user) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/README.md: -------------------------------------------------------------------------------- 1 | # uuid ![build status](https://travis-ci.org/google/uuid.svg?branch=master) 2 | The uuid package generates and inspects UUIDs based on 3 | [RFC 4122](http://tools.ietf.org/html/rfc4122) 4 | and DCE 1.1: Authentication and Security Services. 5 | 6 | This package is based on the github.com/pborman/uuid package (previously named 7 | code.google.com/p/go-uuid). It differs from these earlier packages in that 8 | a UUID is a 16 byte array rather than a byte slice. One loss due to this 9 | change is the ability to represent an invalid UUID (vs a NIL UUID). 10 | 11 | ###### Install 12 | `go get github.com/google/uuid` 13 | 14 | ###### Documentation 15 | [![GoDoc](https://godoc.org/github.com/google/uuid?status.svg)](http://godoc.org/github.com/google/uuid) 16 | 17 | Full `go doc` style documentation for the package can be viewed online without 18 | installing this package by using the GoDoc site here: 19 | http://pkg.go.dev/github.com/google/uuid 20 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/marshal.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import "fmt" 8 | 9 | // MarshalText implements encoding.TextMarshaler. 10 | func (uuid UUID) MarshalText() ([]byte, error) { 11 | var js [36]byte 12 | encodeHex(js[:], uuid) 13 | return js[:], nil 14 | } 15 | 16 | // UnmarshalText implements encoding.TextUnmarshaler. 17 | func (uuid *UUID) UnmarshalText(data []byte) error { 18 | id, err := ParseBytes(data) 19 | if err != nil { 20 | return err 21 | } 22 | *uuid = id 23 | return nil 24 | } 25 | 26 | // MarshalBinary implements encoding.BinaryMarshaler. 27 | func (uuid UUID) MarshalBinary() ([]byte, error) { 28 | return uuid[:], nil 29 | } 30 | 31 | // UnmarshalBinary implements encoding.BinaryUnmarshaler. 32 | func (uuid *UUID) UnmarshalBinary(data []byte) error { 33 | if len(data) != 16 { 34 | return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) 35 | } 36 | copy(uuid[:], data) 37 | return nil 38 | } 39 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/file_stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "bytes" 9 | "io" 10 | "os" 11 | ) 12 | 13 | // This is an InputStream that is loaded from a file all at once 14 | // when you construct the object. 15 | 16 | type FileStream struct { 17 | *InputStream 18 | 19 | filename string 20 | } 21 | 22 | func NewFileStream(fileName string) (*FileStream, error) { 23 | 24 | buf := bytes.NewBuffer(nil) 25 | 26 | f, err := os.Open(fileName) 27 | if err != nil { 28 | return nil, err 29 | } 30 | defer f.Close() 31 | _, err = io.Copy(buf, f) 32 | if err != nil { 33 | return nil, err 34 | } 35 | 36 | fs := new(FileStream) 37 | 38 | fs.filename = fileName 39 | s := string(buf.Bytes()) 40 | 41 | fs.InputStream = NewInputStream(s) 42 | 43 | return fs, nil 44 | 45 | } 46 | 47 | func (f *FileStream) GetSourceName() string { 48 | return f.filename 49 | } 50 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/node_net.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !js 6 | 7 | package uuid 8 | 9 | import "net" 10 | 11 | var interfaces []net.Interface // cached list of interfaces 12 | 13 | // getHardwareInterface returns the name and hardware address of interface name. 14 | // If name is "" then the name and hardware address of one of the system's 15 | // interfaces is returned. If no interfaces are found (name does not exist or 16 | // there are no interfaces) then "", nil is returned. 17 | // 18 | // Only addresses of at least 6 bytes are returned. 19 | func getHardwareInterface(name string) (string, []byte) { 20 | if interfaces == nil { 21 | var err error 22 | interfaces, err = net.Interfaces() 23 | if err != nil { 24 | return "", nil 25 | } 26 | } 27 | for _, ifs := range interfaces { 28 | if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { 29 | return ifs.Name, ifs.HardwareAddr 30 | } 31 | } 32 | return "", nil 33 | } 34 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/doc.go: -------------------------------------------------------------------------------- 1 | // +build !js 2 | 3 | // Package websocket implements the RFC 6455 WebSocket protocol. 4 | // 5 | // https://tools.ietf.org/html/rfc6455 6 | // 7 | // Use Dial to dial a WebSocket server. 8 | // 9 | // Use Accept to accept a WebSocket client. 10 | // 11 | // Conn represents the resulting WebSocket connection. 12 | // 13 | // The examples are the best way to understand how to correctly use the library. 14 | // 15 | // The wsjson and wspb subpackages contain helpers for JSON and protobuf messages. 16 | // 17 | // More documentation at https://nhooyr.io/websocket. 18 | // 19 | // Wasm 20 | // 21 | // The client side supports compiling to Wasm. 22 | // It wraps the WebSocket browser API. 23 | // 24 | // See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket 25 | // 26 | // Some important caveats to be aware of: 27 | // 28 | // - Accept always errors out 29 | // - Conn.Ping is no-op 30 | // - HTTPClient, HTTPHeader and CompressionMode in DialOptions are no-op 31 | // - *http.Response from Dial is &http.Response{} with a 101 status code on success 32 | package websocket // import "nhooyr.io/websocket" 33 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Anmol Sethi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/joho/godotenv/LICENCE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 John Barton 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining 6 | a copy of this software and associated documentation files (the 7 | "Software"), to deal in the Software without restriction, including 8 | without limitation the rights to use, copy, modify, merge, publish, 9 | distribute, sublicense, and/or sell copies of the Software, and to 10 | permit persons to whom the Software is furnished to do so, subject to 11 | the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be 14 | included in all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 libSQL 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/trace_listener.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import "fmt" 8 | 9 | type TraceListener struct { 10 | parser *BaseParser 11 | } 12 | 13 | func NewTraceListener(parser *BaseParser) *TraceListener { 14 | tl := new(TraceListener) 15 | tl.parser = parser 16 | return tl 17 | } 18 | 19 | func (t *TraceListener) VisitErrorNode(_ ErrorNode) { 20 | } 21 | 22 | func (t *TraceListener) EnterEveryRule(ctx ParserRuleContext) { 23 | fmt.Println("enter " + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + ", LT(1)=" + t.parser.input.LT(1).GetText()) 24 | } 25 | 26 | func (t *TraceListener) VisitTerminal(node TerminalNode) { 27 | fmt.Println("consume " + fmt.Sprint(node.GetSymbol()) + " rule " + t.parser.GetRuleNames()[t.parser.ctx.GetRuleIndex()]) 28 | } 29 | 30 | func (t *TraceListener) ExitEveryRule(ctx ParserRuleContext) { 31 | fmt.Println("exit " + t.parser.GetRuleNames()[ctx.GetRuleIndex()] + ", LT(1)=" + t.parser.input.LT(1).GetText()) 32 | } 33 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc. 2 | 3 | MIT License 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Prerequisites 4 | 5 | 1. [Install Go][go-install]. 6 | 2. Download the sources and switch the working directory: 7 | 8 | ```bash 9 | go get -u -d github.com/go-chi/chi 10 | cd $GOPATH/src/github.com/go-chi/chi 11 | ``` 12 | 13 | ## Submitting a Pull Request 14 | 15 | A typical workflow is: 16 | 17 | 1. [Fork the repository.][fork] [This tip maybe also helpful.][go-fork-tip] 18 | 2. [Create a topic branch.][branch] 19 | 3. Add tests for your change. 20 | 4. Run `go test`. If your tests pass, return to the step 3. 21 | 5. Implement the change and ensure the steps from the previous step pass. 22 | 6. Run `goimports -w .`, to ensure the new code conforms to Go formatting guideline. 23 | 7. [Add, commit and push your changes.][git-help] 24 | 8. [Submit a pull request.][pull-req] 25 | 26 | [go-install]: https://golang.org/doc/install 27 | [go-fork-tip]: http://blog.campoy.cat/2014/03/github-and-go-forking-pull-requests-and.html 28 | [fork]: https://help.github.com/articles/fork-a-repo 29 | [branch]: http://learn.github.com/p/branching.html 30 | [git-help]: https://guides.github.com 31 | [pull-req]: https://help.github.com/articles/using-pull-requests 32 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/batch_result.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strconv" 7 | ) 8 | 9 | type BatchResult struct { 10 | StepResults []*StmtResult `json:"step_results"` 11 | StepErrors []*Error `json:"step_errors"` 12 | ReplicationIndex *uint64 `json:"replication_index"` 13 | } 14 | 15 | func (b *BatchResult) UnmarshalJSON(data []byte) error { 16 | type Alias BatchResult 17 | aux := &struct { 18 | ReplicationIndex interface{} `json:"replication_index,omitempty"` 19 | *Alias 20 | }{ 21 | Alias: (*Alias)(b), 22 | } 23 | 24 | if err := json.Unmarshal(data, &aux); err != nil { 25 | return err 26 | } 27 | 28 | if aux.ReplicationIndex == nil { 29 | return nil 30 | } 31 | 32 | switch v := aux.ReplicationIndex.(type) { 33 | case float64: 34 | repIndex := uint64(v) 35 | b.ReplicationIndex = &repIndex 36 | case string: 37 | if v == "" { 38 | return nil 39 | } 40 | repIndex, err := strconv.ParseUint(v, 10, 64) 41 | if err != nil { 42 | return err 43 | } 44 | b.ReplicationIndex = &repIndex 45 | default: 46 | return fmt.Errorf("invalid type for replication index: %T", v) 47 | } 48 | return nil 49 | } 50 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/cors/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Olivier Poitrey 2 | Copyright (c) 2016-Present https://github.com/go-chi authors 3 | 4 | MIT License 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | this software and associated documentation files (the "Software"), to deal in 8 | the Software without restriction, including without limitation the rights to 9 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 10 | the Software, and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 18 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 19 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 20 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 21 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /internal/database/users.sql.go: -------------------------------------------------------------------------------- 1 | // Code generated by sqlc. DO NOT EDIT. 2 | // versions: 3 | // sqlc v1.25.0 4 | // source: users.sql 5 | 6 | package database 7 | 8 | import ( 9 | "context" 10 | ) 11 | 12 | const createUser = `-- name: CreateUser :exec 13 | INSERT INTO users (id, created_at, updated_at, name, api_key) 14 | VALUES ( 15 | ?, 16 | ?, 17 | ?, 18 | ?, 19 | ? 20 | ) 21 | ` 22 | 23 | type CreateUserParams struct { 24 | ID string 25 | CreatedAt string 26 | UpdatedAt string 27 | Name string 28 | ApiKey string 29 | } 30 | 31 | func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) error { 32 | _, err := q.db.ExecContext(ctx, createUser, 33 | arg.ID, 34 | arg.CreatedAt, 35 | arg.UpdatedAt, 36 | arg.Name, 37 | arg.ApiKey, 38 | ) 39 | return err 40 | } 41 | 42 | const getUser = `-- name: GetUser :one 43 | 44 | SELECT id, created_at, updated_at, name, api_key FROM users WHERE api_key = ? 45 | ` 46 | 47 | func (q *Queries) GetUser(ctx context.Context, apiKey string) (User, error) { 48 | row := q.db.QueryRowContext(ctx, getUser, apiKey) 49 | var i User 50 | err := row.Scan( 51 | &i.ID, 52 | &i.CreatedAt, 53 | &i.UpdatedAt, 54 | &i.Name, 55 | &i.ApiKey, 56 | ) 57 | return i, err 58 | } 59 | -------------------------------------------------------------------------------- /vendor/github.com/klauspost/compress/flate/regmask_amd64.go: -------------------------------------------------------------------------------- 1 | package flate 2 | 3 | const ( 4 | // Masks for shifts with register sizes of the shift value. 5 | // This can be used to work around the x86 design of shifting by mod register size. 6 | // It can be used when a variable shift is always smaller than the register size. 7 | 8 | // reg8SizeMaskX - shift value is 8 bits, shifted is X 9 | reg8SizeMask8 = 7 10 | reg8SizeMask16 = 15 11 | reg8SizeMask32 = 31 12 | reg8SizeMask64 = 63 13 | 14 | // reg16SizeMaskX - shift value is 16 bits, shifted is X 15 | reg16SizeMask8 = reg8SizeMask8 16 | reg16SizeMask16 = reg8SizeMask16 17 | reg16SizeMask32 = reg8SizeMask32 18 | reg16SizeMask64 = reg8SizeMask64 19 | 20 | // reg32SizeMaskX - shift value is 32 bits, shifted is X 21 | reg32SizeMask8 = reg8SizeMask8 22 | reg32SizeMask16 = reg8SizeMask16 23 | reg32SizeMask32 = reg8SizeMask32 24 | reg32SizeMask64 = reg8SizeMask64 25 | 26 | // reg64SizeMaskX - shift value is 64 bits, shifted is X 27 | reg64SizeMask8 = reg8SizeMask8 28 | reg64SizeMask16 = reg8SizeMask16 29 | reg64SizeMask32 = reg8SizeMask32 30 | reg64SizeMask64 = reg8SizeMask64 31 | 32 | // regSizeMaskUintX - shift value is uint, shifted is X 33 | regSizeMaskUint8 = reg8SizeMask8 34 | regSizeMaskUint16 = reg8SizeMask16 35 | regSizeMaskUint32 = reg8SizeMask32 36 | regSizeMaskUint64 = reg8SizeMask64 37 | ) 38 | -------------------------------------------------------------------------------- /vendor/github.com/klauspost/compress/flate/regmask_other.go: -------------------------------------------------------------------------------- 1 | //go:build !amd64 2 | // +build !amd64 3 | 4 | package flate 5 | 6 | const ( 7 | // Masks for shifts with register sizes of the shift value. 8 | // This can be used to work around the x86 design of shifting by mod register size. 9 | // It can be used when a variable shift is always smaller than the register size. 10 | 11 | // reg8SizeMaskX - shift value is 8 bits, shifted is X 12 | reg8SizeMask8 = 0xff 13 | reg8SizeMask16 = 0xff 14 | reg8SizeMask32 = 0xff 15 | reg8SizeMask64 = 0xff 16 | 17 | // reg16SizeMaskX - shift value is 16 bits, shifted is X 18 | reg16SizeMask8 = 0xffff 19 | reg16SizeMask16 = 0xffff 20 | reg16SizeMask32 = 0xffff 21 | reg16SizeMask64 = 0xffff 22 | 23 | // reg32SizeMaskX - shift value is 32 bits, shifted is X 24 | reg32SizeMask8 = 0xffffffff 25 | reg32SizeMask16 = 0xffffffff 26 | reg32SizeMask32 = 0xffffffff 27 | reg32SizeMask64 = 0xffffffff 28 | 29 | // reg64SizeMaskX - shift value is 64 bits, shifted is X 30 | reg64SizeMask8 = 0xffffffffffffffff 31 | reg64SizeMask16 = 0xffffffffffffffff 32 | reg64SizeMask32 = 0xffffffffffffffff 33 | reg64SizeMask64 = 0xffffffffffffffff 34 | 35 | // regSizeMaskUintX - shift value is uint, shifted is X 36 | regSizeMaskUint8 = ^uint(0) 37 | regSizeMaskUint16 = ^uint(0) 38 | regSizeMaskUint32 = ^uint(0) 39 | regSizeMaskUint64 = ^uint(0) 40 | ) 41 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/stream_result.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | ) 8 | 9 | type StreamResult struct { 10 | Type string `json:"type"` 11 | Response *StreamResponse `json:"response,omitempty"` 12 | Error *Error `json:"error,omitempty"` 13 | } 14 | 15 | type StreamResponse struct { 16 | Type string `json:"type"` 17 | Result json.RawMessage `json:"result,omitempty"` 18 | } 19 | 20 | func (r *StreamResponse) ExecuteResult() (*StmtResult, error) { 21 | if r.Type != "execute" { 22 | return nil, fmt.Errorf("invalid response type: %s", r.Type) 23 | } 24 | 25 | var res StmtResult 26 | if err := json.Unmarshal(r.Result, &res); err != nil { 27 | return nil, err 28 | } 29 | return &res, nil 30 | } 31 | 32 | func (r *StreamResponse) BatchResult() (*BatchResult, error) { 33 | if r.Type != "batch" { 34 | return nil, fmt.Errorf("invalid response type: %s", r.Type) 35 | } 36 | 37 | var res BatchResult 38 | if err := json.Unmarshal(r.Result, &res); err != nil { 39 | return nil, err 40 | } 41 | for _, e := range res.StepErrors { 42 | if e != nil { 43 | return nil, errors.New(e.Message) 44 | } 45 | } 46 | return &res, nil 47 | } 48 | 49 | type Error struct { 50 | Message string `json:"message"` 51 | Code *string `json:"code,omitempty"` 52 | } 53 | -------------------------------------------------------------------------------- /vendor/golang.org/x/exp/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/version1.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | ) 10 | 11 | // NewUUID returns a Version 1 UUID based on the current NodeID and clock 12 | // sequence, and the current time. If the NodeID has not been set by SetNodeID 13 | // or SetNodeInterface then it will be set automatically. If the NodeID cannot 14 | // be set NewUUID returns nil. If clock sequence has not been set by 15 | // SetClockSequence then it will be set automatically. If GetTime fails to 16 | // return the current NewUUID returns nil and an error. 17 | // 18 | // In most cases, New should be used. 19 | func NewUUID() (UUID, error) { 20 | var uuid UUID 21 | now, seq, err := GetTime() 22 | if err != nil { 23 | return uuid, err 24 | } 25 | 26 | timeLow := uint32(now & 0xffffffff) 27 | timeMid := uint16((now >> 32) & 0xffff) 28 | timeHi := uint16((now >> 48) & 0x0fff) 29 | timeHi |= 0x1000 // Version 1 30 | 31 | binary.BigEndian.PutUint32(uuid[0:], timeLow) 32 | binary.BigEndian.PutUint16(uuid[4:], timeMid) 33 | binary.BigEndian.PutUint16(uuid[6:], timeHi) 34 | binary.BigEndian.PutUint16(uuid[8:], seq) 35 | 36 | nodeMu.Lock() 37 | if nodeID == zeroID { 38 | setNodeInterface("") 39 | } 40 | copy(uuid[10:], nodeID[:]) 41 | nodeMu.Unlock() 42 | 43 | return uuid, nil 44 | } 45 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/atn_simulator.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | var ATNSimulatorError = NewDFAState(0x7FFFFFFF, NewBaseATNConfigSet(false)) 8 | 9 | type IATNSimulator interface { 10 | SharedContextCache() *PredictionContextCache 11 | ATN() *ATN 12 | DecisionToDFA() []*DFA 13 | } 14 | 15 | type BaseATNSimulator struct { 16 | atn *ATN 17 | sharedContextCache *PredictionContextCache 18 | decisionToDFA []*DFA 19 | } 20 | 21 | func NewBaseATNSimulator(atn *ATN, sharedContextCache *PredictionContextCache) *BaseATNSimulator { 22 | b := new(BaseATNSimulator) 23 | 24 | b.atn = atn 25 | b.sharedContextCache = sharedContextCache 26 | 27 | return b 28 | } 29 | 30 | func (b *BaseATNSimulator) getCachedContext(context PredictionContext) PredictionContext { 31 | if b.sharedContextCache == nil { 32 | return context 33 | } 34 | 35 | visited := make(map[PredictionContext]PredictionContext) 36 | 37 | return getCachedBasePredictionContext(context, b.sharedContextCache, visited) 38 | } 39 | 40 | func (b *BaseATNSimulator) SharedContextCache() *PredictionContextCache { 41 | return b.sharedContextCache 42 | } 43 | 44 | func (b *BaseATNSimulator) ATN() *ATN { 45 | return b.atn 46 | } 47 | 48 | func (b *BaseATNSimulator) DecisionToDFA() []*DFA { 49 | return b.decisionToDFA 50 | } 51 | -------------------------------------------------------------------------------- /vendor/golang.org/x/exp/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009,2014 Google Inc. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 The ANTLR Project 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, 7 | this list of conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | 3. Neither the name of the copyright holder nor the names of its 14 | contributors may be used to endorse or promote products derived from this 15 | software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 21 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/stmt.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "github.com/tursodatabase/libsql-client-go/libsql/internal/http/shared" 5 | ) 6 | 7 | type Stmt struct { 8 | Sql *string `json:"sql,omitempty"` 9 | SqlId *int32 `json:"sql_id,omitempty"` 10 | Args []Value `json:"args,omitempty"` 11 | NamedArgs []NamedArg `json:"named_args,omitempty"` 12 | WantRows bool `json:"want_rows"` 13 | ReplicationIndex *uint64 `json:"replication_index,omitempty"` 14 | } 15 | 16 | type NamedArg struct { 17 | Name string `json:"name"` 18 | Value Value `json:"value"` 19 | } 20 | 21 | func (s *Stmt) AddArgs(params shared.Params) error { 22 | if len(params.Named()) > 0 { 23 | return s.AddNamedArgs(params.Named()) 24 | } else { 25 | return s.AddPositionalArgs(params.Positional()) 26 | } 27 | } 28 | 29 | func (s *Stmt) AddPositionalArgs(args []any) error { 30 | argValues := make([]Value, len(args)) 31 | for idx := range args { 32 | var err error 33 | if argValues[idx], err = ToValue(args[idx]); err != nil { 34 | return err 35 | } 36 | } 37 | s.Args = argValues 38 | return nil 39 | } 40 | 41 | func (s *Stmt) AddNamedArgs(args map[string]any) error { 42 | argValues := make([]NamedArg, len(args)) 43 | idx := 0 44 | for key, value := range args { 45 | var err error 46 | var v Value 47 | if v, err = ToValue(value); err != nil { 48 | return err 49 | } 50 | argValues[idx] = NamedArg{ 51 | Name: key, 52 | Value: v, 53 | } 54 | idx++ 55 | } 56 | s.NamedArgs = argValues 57 | return nil 58 | } 59 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/stmt_result.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strconv" 7 | ) 8 | 9 | type Column struct { 10 | Name *string `json:"name"` 11 | Type *string `json:"decltype"` 12 | } 13 | 14 | type StmtResult struct { 15 | Cols []Column `json:"cols"` 16 | Rows [][]Value `json:"rows"` 17 | AffectedRowCount int32 `json:"affected_row_count"` 18 | LastInsertRowId *string `json:"last_insert_rowid"` 19 | ReplicationIndex *uint64 `json:"replication_index"` 20 | } 21 | 22 | func (r *StmtResult) GetLastInsertRowId() int64 { 23 | if r.LastInsertRowId != nil { 24 | if integer, err := strconv.ParseInt(*r.LastInsertRowId, 10, 64); err == nil { 25 | return integer 26 | } 27 | } 28 | return 0 29 | } 30 | 31 | func (r *StmtResult) UnmarshalJSON(data []byte) error { 32 | type Alias StmtResult 33 | aux := &struct { 34 | ReplicationIndex interface{} `json:"replication_index,omitempty"` 35 | *Alias 36 | }{ 37 | Alias: (*Alias)(r), 38 | } 39 | 40 | if err := json.Unmarshal(data, &aux); err != nil { 41 | return err 42 | } 43 | 44 | if aux.ReplicationIndex == nil { 45 | return nil 46 | } 47 | 48 | switch v := aux.ReplicationIndex.(type) { 49 | case float64: 50 | repIndex := uint64(v) 51 | r.ReplicationIndex = &repIndex 52 | case string: 53 | if v == "" { 54 | return nil 55 | } 56 | repIndex, err := strconv.ParseUint(v, 10, 64) 57 | if err != nil { 58 | return err 59 | } 60 | r.ReplicationIndex = &repIndex 61 | default: 62 | return fmt.Errorf("invalid type for replication index: %T", v) 63 | } 64 | return nil 65 | } 66 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/sql.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "database/sql/driver" 9 | "fmt" 10 | ) 11 | 12 | // Scan implements sql.Scanner so UUIDs can be read from databases transparently. 13 | // Currently, database types that map to string and []byte are supported. Please 14 | // consult database-specific driver documentation for matching types. 15 | func (uuid *UUID) Scan(src interface{}) error { 16 | switch src := src.(type) { 17 | case nil: 18 | return nil 19 | 20 | case string: 21 | // if an empty UUID comes from a table, we return a null UUID 22 | if src == "" { 23 | return nil 24 | } 25 | 26 | // see Parse for required string format 27 | u, err := Parse(src) 28 | if err != nil { 29 | return fmt.Errorf("Scan: %v", err) 30 | } 31 | 32 | *uuid = u 33 | 34 | case []byte: 35 | // if an empty UUID comes from a table, we return a null UUID 36 | if len(src) == 0 { 37 | return nil 38 | } 39 | 40 | // assumes a simple slice of bytes if 16 bytes 41 | // otherwise attempts to parse 42 | if len(src) != 16 { 43 | return uuid.Scan(string(src)) 44 | } 45 | copy((*uuid)[:], src) 46 | 47 | default: 48 | return fmt.Errorf("Scan: unable to scan type %T into UUID", src) 49 | } 50 | 51 | return nil 52 | } 53 | 54 | // Value implements sql.Valuer so that UUIDs can be written to databases 55 | // transparently. Currently, UUIDs map to strings. Please consult 56 | // database-specific driver documentation for matching types. 57 | func (uuid UUID) Value() (driver.Value, error) { 58 | return uuid.String(), nil 59 | } 60 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/chain.go: -------------------------------------------------------------------------------- 1 | package chi 2 | 3 | import "net/http" 4 | 5 | // Chain returns a Middlewares type from a slice of middleware handlers. 6 | func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares { 7 | return Middlewares(middlewares) 8 | } 9 | 10 | // Handler builds and returns a http.Handler from the chain of middlewares, 11 | // with `h http.Handler` as the final handler. 12 | func (mws Middlewares) Handler(h http.Handler) http.Handler { 13 | return &ChainHandler{mws, h, chain(mws, h)} 14 | } 15 | 16 | // HandlerFunc builds and returns a http.Handler from the chain of middlewares, 17 | // with `h http.Handler` as the final handler. 18 | func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler { 19 | return &ChainHandler{mws, h, chain(mws, h)} 20 | } 21 | 22 | // ChainHandler is a http.Handler with support for handler composition and 23 | // execution. 24 | type ChainHandler struct { 25 | Middlewares Middlewares 26 | Endpoint http.Handler 27 | chain http.Handler 28 | } 29 | 30 | func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 31 | c.chain.ServeHTTP(w, r) 32 | } 33 | 34 | // chain builds a http.Handler composed of an inline middleware stack and endpoint 35 | // handler in the order they are passed. 36 | func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler { 37 | // Return ahead of time if there aren't any middlewares for the chain 38 | if len(middlewares) == 0 { 39 | return endpoint 40 | } 41 | 42 | // Wrap the end handler with the middleware chain 43 | h := middlewares[len(middlewares)-1](endpoint) 44 | for i := len(middlewares) - 2; i >= 0; i-- { 45 | h = middlewares[i](h) 46 | } 47 | 48 | return h 49 | } 50 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230512164433-5d1fd1a340c9 2 | ## explicit; go 1.18 3 | github.com/antlr/antlr4/runtime/Go/antlr/v4 4 | # github.com/go-chi/chi v1.5.4 5 | ## explicit; go 1.16 6 | github.com/go-chi/chi 7 | # github.com/go-chi/cors v1.2.1 8 | ## explicit; go 1.14 9 | github.com/go-chi/cors 10 | # github.com/google/uuid v1.3.0 11 | ## explicit 12 | github.com/google/uuid 13 | # github.com/joho/godotenv v1.5.1 14 | ## explicit; go 1.12 15 | github.com/joho/godotenv 16 | # github.com/klauspost/compress v1.15.15 17 | ## explicit; go 1.17 18 | github.com/klauspost/compress/flate 19 | # github.com/libsql/sqlite-antlr4-parser v0.0.0-20230802215326-5cb5bb604475 20 | ## explicit; go 1.19 21 | github.com/libsql/sqlite-antlr4-parser/sqliteparser 22 | github.com/libsql/sqlite-antlr4-parser/sqliteparserutils 23 | # github.com/tursodatabase/libsql-client-go v0.0.0-20240220085343-4ae0eb9d0898 24 | ## explicit; go 1.20 25 | github.com/tursodatabase/libsql-client-go/libsql 26 | github.com/tursodatabase/libsql-client-go/libsql/internal/hrana 27 | github.com/tursodatabase/libsql-client-go/libsql/internal/http 28 | github.com/tursodatabase/libsql-client-go/libsql/internal/http/hranaV2 29 | github.com/tursodatabase/libsql-client-go/libsql/internal/http/shared 30 | github.com/tursodatabase/libsql-client-go/libsql/internal/ws 31 | # golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e 32 | ## explicit; go 1.18 33 | golang.org/x/exp/constraints 34 | golang.org/x/exp/slices 35 | # nhooyr.io/websocket v1.8.7 36 | ## explicit; go 1.13 37 | nhooyr.io/websocket 38 | nhooyr.io/websocket/internal/bpool 39 | nhooyr.io/websocket/internal/errd 40 | nhooyr.io/websocket/internal/wsjs 41 | nhooyr.io/websocket/internal/xsync 42 | nhooyr.io/websocket/wsjson 43 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/cors/README.md: -------------------------------------------------------------------------------- 1 | # CORS net/http middleware 2 | 3 | [go-chi/cors](https://github.com/go-chi/cors) is a fork of [github.com/rs/cors](https://github.com/rs/cors) that 4 | provides a `net/http` compatible middleware for performing preflight CORS checks on the server side. These headers 5 | are required for using the browser native [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). 6 | 7 | This middleware is designed to be used as a top-level middleware on the [chi](https://github.com/go-chi/chi) router. 8 | Applying with within a `r.Group()` or using `With()` will not work without routes matching `OPTIONS` added. 9 | 10 | ## Usage 11 | 12 | ```go 13 | func main() { 14 | r := chi.NewRouter() 15 | 16 | // Basic CORS 17 | // for more ideas, see: https://developer.github.com/v3/#cross-origin-resource-sharing 18 | r.Use(cors.Handler(cors.Options{ 19 | // AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts 20 | AllowedOrigins: []string{"https://*", "http://*"}, 21 | // AllowOriginFunc: func(r *http.Request, origin string) bool { return true }, 22 | AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, 23 | AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, 24 | ExposedHeaders: []string{"Link"}, 25 | AllowCredentials: false, 26 | MaxAge: 300, // Maximum value not ignored by any of major browsers 27 | })) 28 | 29 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { 30 | w.Write([]byte("welcome")) 31 | }) 32 | 33 | http.ListenAndServe(":3000", r) 34 | } 35 | ``` 36 | 37 | ## Credits 38 | 39 | All credit for the original work of this middleware goes out to [github.com/rs](github.com/rs). 40 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/cors/utils.go: -------------------------------------------------------------------------------- 1 | package cors 2 | 3 | import "strings" 4 | 5 | const toLower = 'a' - 'A' 6 | 7 | type converter func(string) string 8 | 9 | type wildcard struct { 10 | prefix string 11 | suffix string 12 | } 13 | 14 | func (w wildcard) match(s string) bool { 15 | return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix) 16 | } 17 | 18 | // convert converts a list of string using the passed converter function 19 | func convert(s []string, c converter) []string { 20 | out := []string{} 21 | for _, i := range s { 22 | out = append(out, c(i)) 23 | } 24 | return out 25 | } 26 | 27 | // parseHeaderList tokenize + normalize a string containing a list of headers 28 | func parseHeaderList(headerList string) []string { 29 | l := len(headerList) 30 | h := make([]byte, 0, l) 31 | upper := true 32 | // Estimate the number headers in order to allocate the right splice size 33 | t := 0 34 | for i := 0; i < l; i++ { 35 | if headerList[i] == ',' { 36 | t++ 37 | } 38 | } 39 | headers := make([]string, 0, t) 40 | for i := 0; i < l; i++ { 41 | b := headerList[i] 42 | if b >= 'a' && b <= 'z' { 43 | if upper { 44 | h = append(h, b-toLower) 45 | } else { 46 | h = append(h, b) 47 | } 48 | } else if b >= 'A' && b <= 'Z' { 49 | if !upper { 50 | h = append(h, b+toLower) 51 | } else { 52 | h = append(h, b) 53 | } 54 | } else if b == '-' || b == '_' || b == '.' || (b >= '0' && b <= '9') { 55 | h = append(h, b) 56 | } 57 | 58 | if b == ' ' || b == ',' || i == l-1 { 59 | if len(h) > 0 { 60 | // Flush the found header 61 | headers = append(headers, string(h)) 62 | h = h[:0] 63 | upper = true 64 | } 65 | } else { 66 | upper = b == '-' 67 | } 68 | } 69 | return headers 70 | } 71 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/http/shared/rows.go: -------------------------------------------------------------------------------- 1 | package shared 2 | 3 | import ( 4 | "database/sql/driver" 5 | "fmt" 6 | "io" 7 | ) 8 | 9 | type rowsProvider interface { 10 | SetsCount() int 11 | RowsCount(setIdx int) int 12 | Columns(setIdx int) []string 13 | FieldValue(setIdx, rowIdx int, columnIdx int) driver.Value 14 | Error(setIdx int) string 15 | HasResult(setIdx int) bool 16 | } 17 | 18 | func NewRows(result rowsProvider) driver.Rows { 19 | return &rows{result: result} 20 | } 21 | 22 | type rows struct { 23 | result rowsProvider 24 | currentResultSetIndex int 25 | currentRowIdx int 26 | } 27 | 28 | func (r *rows) Columns() []string { 29 | return r.result.Columns(r.currentResultSetIndex) 30 | } 31 | 32 | func (r *rows) Close() error { 33 | return nil 34 | } 35 | 36 | func (r *rows) Next(dest []driver.Value) error { 37 | if r.currentRowIdx == r.result.RowsCount(r.currentResultSetIndex) { 38 | return io.EOF 39 | } 40 | count := len(r.result.Columns(r.currentResultSetIndex)) 41 | for idx := 0; idx < count; idx++ { 42 | dest[idx] = r.result.FieldValue(r.currentResultSetIndex, r.currentRowIdx, idx) 43 | } 44 | r.currentRowIdx++ 45 | return nil 46 | } 47 | 48 | func (r *rows) HasNextResultSet() bool { 49 | return r.currentResultSetIndex < r.result.SetsCount()-1 50 | } 51 | 52 | func (r *rows) NextResultSet() error { 53 | if !r.HasNextResultSet() { 54 | return io.EOF 55 | } 56 | 57 | r.currentResultSetIndex++ 58 | r.currentRowIdx = 0 59 | 60 | errStr := r.result.Error(r.currentResultSetIndex) 61 | if errStr != "" { 62 | return fmt.Errorf("failed to execute statement\n%s", errStr) 63 | } 64 | if !r.result.HasResult(r.currentResultSetIndex) { 65 | return fmt.Errorf("no results for statement") 66 | } 67 | 68 | return nil 69 | } 70 | -------------------------------------------------------------------------------- /models.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/bootdotdev/learn-cicd-starter/internal/database" 7 | ) 8 | 9 | type User struct { 10 | ID string `json:"id"` 11 | CreatedAt time.Time `json:"created_at"` 12 | UpdatedAt time.Time `json:"updated_at"` 13 | Name string `json:"name"` 14 | ApiKey string `json:"api_key"` 15 | } 16 | 17 | func databaseUserToUser(user database.User) (User, error) { 18 | createdAt, err := time.Parse(time.RFC3339, user.CreatedAt) 19 | if err != nil { 20 | return User{}, err 21 | } 22 | 23 | updatedAt, err := time.Parse(time.RFC3339, user.UpdatedAt) 24 | if err != nil { 25 | return User{}, err 26 | } 27 | return User{ 28 | ID: user.ID, 29 | CreatedAt: createdAt, 30 | UpdatedAt: updatedAt, 31 | Name: user.Name, 32 | ApiKey: user.ApiKey, 33 | }, nil 34 | } 35 | 36 | type Note struct { 37 | ID string `json:"id"` 38 | CreatedAt time.Time `json:"created_at"` 39 | UpdatedAt time.Time `json:"updated_at"` 40 | Note string `json:"note"` 41 | UserID string `json:"user_id"` 42 | } 43 | 44 | func databaseNoteToNote(post database.Note) (Note, error) { 45 | createdAt, err := time.Parse(time.RFC3339, post.CreatedAt) 46 | if err != nil { 47 | return Note{}, err 48 | } 49 | 50 | updatedAt, err := time.Parse(time.RFC3339, post.UpdatedAt) 51 | if err != nil { 52 | return Note{}, err 53 | } 54 | return Note{ 55 | ID: post.ID, 56 | CreatedAt: createdAt, 57 | UpdatedAt: updatedAt, 58 | Note: post.Note, 59 | UserID: post.UserID, 60 | }, nil 61 | } 62 | 63 | func databasePostsToPosts(notes []database.Note) ([]Note, error) { 64 | result := make([]Note, len(notes)) 65 | for i, note := range notes { 66 | var err error 67 | result[i], err = databaseNoteToNote(note) 68 | if err != nil { 69 | return nil, err 70 | } 71 | 72 | } 73 | return result, nil 74 | } 75 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/stream_request.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "github.com/tursodatabase/libsql-client-go/libsql/internal/http/shared" 5 | ) 6 | 7 | type StreamRequest struct { 8 | Type string `json:"type"` 9 | Stmt *Stmt `json:"stmt,omitempty"` 10 | Batch *Batch `json:"batch,omitempty"` 11 | Sql *string `json:"sql,omitempty"` 12 | SqlId *int32 `json:"sql_id,omitempty"` 13 | } 14 | 15 | func CloseStream() StreamRequest { 16 | return StreamRequest{Type: "close"} 17 | } 18 | 19 | func ExecuteStream(sql string, params shared.Params, wantRows bool) (*StreamRequest, error) { 20 | stmt := &Stmt{ 21 | Sql: &sql, 22 | WantRows: wantRows, 23 | } 24 | if err := stmt.AddArgs(params); err != nil { 25 | return nil, err 26 | } 27 | return &StreamRequest{Type: "execute", Stmt: stmt}, nil 28 | } 29 | 30 | func ExecuteStoredStream(sqlId int32, params shared.Params, wantRows bool) (*StreamRequest, error) { 31 | stmt := &Stmt{ 32 | SqlId: &sqlId, 33 | WantRows: wantRows, 34 | } 35 | if err := stmt.AddArgs(params); err != nil { 36 | return nil, err 37 | } 38 | return &StreamRequest{Type: "execute", Stmt: stmt}, nil 39 | } 40 | 41 | func BatchStream(sqls []string, params []shared.Params, wantRows bool) (*StreamRequest, error) { 42 | batch := &Batch{} 43 | for idx, sql := range sqls { 44 | s := sql 45 | stmt := &Stmt{ 46 | Sql: &s, 47 | WantRows: wantRows, 48 | } 49 | if err := stmt.AddArgs(params[idx]); err != nil { 50 | return nil, err 51 | } 52 | batch.Add(*stmt) 53 | } 54 | return &StreamRequest{Type: "batch", Batch: batch}, nil 55 | } 56 | 57 | func StoreSqlStream(sql string, sqlId int32) StreamRequest { 58 | return StreamRequest{Type: "store_sql", Sql: &sql, SqlId: &sqlId} 59 | } 60 | 61 | func CloseStoredSqlStream(sqlId int32) StreamRequest { 62 | return StreamRequest{Type: "close_sql", SqlId: &sqlId} 63 | } 64 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/hash.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "crypto/md5" 9 | "crypto/sha1" 10 | "hash" 11 | ) 12 | 13 | // Well known namespace IDs and UUIDs 14 | var ( 15 | NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) 16 | NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) 17 | NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) 18 | NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) 19 | Nil UUID // empty UUID, all zeros 20 | ) 21 | 22 | // NewHash returns a new UUID derived from the hash of space concatenated with 23 | // data generated by h. The hash should be at least 16 byte in length. The 24 | // first 16 bytes of the hash are used to form the UUID. The version of the 25 | // UUID will be the lower 4 bits of version. NewHash is used to implement 26 | // NewMD5 and NewSHA1. 27 | func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { 28 | h.Reset() 29 | h.Write(space[:]) //nolint:errcheck 30 | h.Write(data) //nolint:errcheck 31 | s := h.Sum(nil) 32 | var uuid UUID 33 | copy(uuid[:], s) 34 | uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) 35 | uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant 36 | return uuid 37 | } 38 | 39 | // NewMD5 returns a new MD5 (Version 3) UUID based on the 40 | // supplied name space and data. It is the same as calling: 41 | // 42 | // NewHash(md5.New(), space, data, 3) 43 | func NewMD5(space UUID, data []byte) UUID { 44 | return NewHash(md5.New(), space, data, 3) 45 | } 46 | 47 | // NewSHA1 returns a new SHA1 (Version 5) UUID based on the 48 | // supplied name space and data. It is the same as calling: 49 | // 50 | // NewHash(sha1.New(), space, data, 5) 51 | func NewSHA1(space UUID, data []byte) UUID { 52 | return NewHash(sha1.New(), space, data, 5) 53 | } 54 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/wsjson/wsjson.go: -------------------------------------------------------------------------------- 1 | // Package wsjson provides helpers for reading and writing JSON messages. 2 | package wsjson // import "nhooyr.io/websocket/wsjson" 3 | 4 | import ( 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | 9 | "nhooyr.io/websocket" 10 | "nhooyr.io/websocket/internal/bpool" 11 | "nhooyr.io/websocket/internal/errd" 12 | ) 13 | 14 | // Read reads a JSON message from c into v. 15 | // It will reuse buffers in between calls to avoid allocations. 16 | func Read(ctx context.Context, c *websocket.Conn, v interface{}) error { 17 | return read(ctx, c, v) 18 | } 19 | 20 | func read(ctx context.Context, c *websocket.Conn, v interface{}) (err error) { 21 | defer errd.Wrap(&err, "failed to read JSON message") 22 | 23 | _, r, err := c.Reader(ctx) 24 | if err != nil { 25 | return err 26 | } 27 | 28 | b := bpool.Get() 29 | defer bpool.Put(b) 30 | 31 | _, err = b.ReadFrom(r) 32 | if err != nil { 33 | return err 34 | } 35 | 36 | err = json.Unmarshal(b.Bytes(), v) 37 | if err != nil { 38 | c.Close(websocket.StatusInvalidFramePayloadData, "failed to unmarshal JSON") 39 | return fmt.Errorf("failed to unmarshal JSON: %w", err) 40 | } 41 | 42 | return nil 43 | } 44 | 45 | // Write writes the JSON message v to c. 46 | // It will reuse buffers in between calls to avoid allocations. 47 | func Write(ctx context.Context, c *websocket.Conn, v interface{}) error { 48 | return write(ctx, c, v) 49 | } 50 | 51 | func write(ctx context.Context, c *websocket.Conn, v interface{}) (err error) { 52 | defer errd.Wrap(&err, "failed to write JSON message") 53 | 54 | w, err := c.Writer(ctx, websocket.MessageText) 55 | if err != nil { 56 | return err 57 | } 58 | 59 | // json.Marshal cannot reuse buffers between calls as it has to return 60 | // a copy of the byte slice but Encoder does as it directly writes to w. 61 | err = json.NewEncoder(w).Encode(v) 62 | if err != nil { 63 | return fmt.Errorf("failed to marshal JSON: %w", err) 64 | } 65 | 66 | return w.Close() 67 | } 68 | -------------------------------------------------------------------------------- /vendor/golang.org/x/exp/constraints/constraints.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package constraints defines a set of useful constraints to be used 6 | // with type parameters. 7 | package constraints 8 | 9 | // Signed is a constraint that permits any signed integer type. 10 | // If future releases of Go add new predeclared signed integer types, 11 | // this constraint will be modified to include them. 12 | type Signed interface { 13 | ~int | ~int8 | ~int16 | ~int32 | ~int64 14 | } 15 | 16 | // Unsigned is a constraint that permits any unsigned integer type. 17 | // If future releases of Go add new predeclared unsigned integer types, 18 | // this constraint will be modified to include them. 19 | type Unsigned interface { 20 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr 21 | } 22 | 23 | // Integer is a constraint that permits any integer type. 24 | // If future releases of Go add new predeclared integer types, 25 | // this constraint will be modified to include them. 26 | type Integer interface { 27 | Signed | Unsigned 28 | } 29 | 30 | // Float is a constraint that permits any floating-point type. 31 | // If future releases of Go add new predeclared floating-point types, 32 | // this constraint will be modified to include them. 33 | type Float interface { 34 | ~float32 | ~float64 35 | } 36 | 37 | // Complex is a constraint that permits any complex numeric type. 38 | // If future releases of Go add new predeclared complex numeric types, 39 | // this constraint will be modified to include them. 40 | type Complex interface { 41 | ~complex64 | ~complex128 42 | } 43 | 44 | // Ordered is a constraint that permits any ordered type: any type 45 | // that supports the operators < <= >= >. 46 | // If future releases of Go add new ordered types, 47 | // this constraint will be modified to include them. 48 | type Ordered interface { 49 | Integer | Float | ~string 50 | } 51 | -------------------------------------------------------------------------------- /handler_notes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | "time" 7 | 8 | "github.com/bootdotdev/learn-cicd-starter/internal/database" 9 | "github.com/google/uuid" 10 | ) 11 | 12 | func (cfg *apiConfig) handlerNotesGet(w http.ResponseWriter, r *http.Request, user database.User) { 13 | posts, err := cfg.DB.GetNotesForUser(r.Context(), user.ID) 14 | if err != nil { 15 | respondWithError(w, http.StatusInternalServerError, "Couldn't get posts for user", err) 16 | return 17 | } 18 | 19 | postsResp, err := databasePostsToPosts(posts) 20 | if err != nil { 21 | respondWithError(w, http.StatusInternalServerError, "Couldn't convert posts", err) 22 | return 23 | } 24 | 25 | respondWithJSON(w, http.StatusOK, postsResp) 26 | } 27 | 28 | func (cfg *apiConfig) handlerNotesCreate(w http.ResponseWriter, r *http.Request, user database.User) { 29 | type parameters struct { 30 | Note string `json:"note"` 31 | } 32 | decoder := json.NewDecoder(r.Body) 33 | params := parameters{} 34 | err := decoder.Decode(¶ms) 35 | if err != nil { 36 | respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err) 37 | return 38 | } 39 | 40 | id := uuid.New().String() 41 | err = cfg.DB.CreateNote(r.Context(), database.CreateNoteParams{ 42 | ID: id, 43 | CreatedAt: time.Now().UTC().Format(time.RFC3339), 44 | UpdatedAt: time.Now().UTC().Format(time.RFC3339), 45 | Note: params.Note, 46 | UserID: user.ID, 47 | }) 48 | if err != nil { 49 | respondWithError(w, http.StatusInternalServerError, "Couldn't create note", err) 50 | return 51 | } 52 | 53 | note, err := cfg.DB.GetNote(r.Context(), id) 54 | if err != nil { 55 | respondWithError(w, http.StatusNotFound, "Couldn't get note", err) 56 | return 57 | } 58 | 59 | noteResp, err := databaseNoteToNote(note) 60 | if err != nil { 61 | respondWithError(w, http.StatusInternalServerError, "Couldn't convert note", err) 62 | return 63 | } 64 | 65 | respondWithJSON(w, http.StatusCreated, noteResp) 66 | } 67 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/compress.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | // CompressionMode represents the modes available to the deflate extension. 4 | // See https://tools.ietf.org/html/rfc7692 5 | // 6 | // A compatibility layer is implemented for the older deflate-frame extension used 7 | // by safari. See https://tools.ietf.org/html/draft-tyoshino-hybi-websocket-perframe-deflate-06 8 | // It will work the same in every way except that we cannot signal to the peer we 9 | // want to use no context takeover on our side, we can only signal that they should. 10 | // It is however currently disabled due to Safari bugs. See https://github.com/nhooyr/websocket/issues/218 11 | type CompressionMode int 12 | 13 | const ( 14 | // CompressionNoContextTakeover grabs a new flate.Reader and flate.Writer as needed 15 | // for every message. This applies to both server and client side. 16 | // 17 | // This means less efficient compression as the sliding window from previous messages 18 | // will not be used but the memory overhead will be lower if the connections 19 | // are long lived and seldom used. 20 | // 21 | // The message will only be compressed if greater than 512 bytes. 22 | CompressionNoContextTakeover CompressionMode = iota 23 | 24 | // CompressionContextTakeover uses a flate.Reader and flate.Writer per connection. 25 | // This enables reusing the sliding window from previous messages. 26 | // As most WebSocket protocols are repetitive, this can be very efficient. 27 | // It carries an overhead of 8 kB for every connection compared to CompressionNoContextTakeover. 28 | // 29 | // If the peer negotiates NoContextTakeover on the client or server side, it will be 30 | // used instead as this is required by the RFC. 31 | CompressionContextTakeover 32 | 33 | // CompressionDisabled disables the deflate extension. 34 | // 35 | // Use this if you are using a predominantly binary protocol with very 36 | // little duplication in between messages or CPU and memory are more 37 | // important than bandwidth. 38 | CompressionDisabled 39 | ) 40 | -------------------------------------------------------------------------------- /internal/database/notes.sql.go: -------------------------------------------------------------------------------- 1 | // Code generated by sqlc. DO NOT EDIT. 2 | // versions: 3 | // sqlc v1.25.0 4 | // source: notes.sql 5 | 6 | package database 7 | 8 | import ( 9 | "context" 10 | ) 11 | 12 | const createNote = `-- name: CreateNote :exec 13 | INSERT INTO notes (id, created_at, updated_at, note, user_id) 14 | VALUES (?, ?, ?, ?, ?) 15 | ` 16 | 17 | type CreateNoteParams struct { 18 | ID string 19 | CreatedAt string 20 | UpdatedAt string 21 | Note string 22 | UserID string 23 | } 24 | 25 | func (q *Queries) CreateNote(ctx context.Context, arg CreateNoteParams) error { 26 | _, err := q.db.ExecContext(ctx, createNote, 27 | arg.ID, 28 | arg.CreatedAt, 29 | arg.UpdatedAt, 30 | arg.Note, 31 | arg.UserID, 32 | ) 33 | return err 34 | } 35 | 36 | const getNote = `-- name: GetNote :one 37 | 38 | SELECT id, created_at, updated_at, note, user_id FROM notes WHERE id = ? 39 | ` 40 | 41 | func (q *Queries) GetNote(ctx context.Context, id string) (Note, error) { 42 | row := q.db.QueryRowContext(ctx, getNote, id) 43 | var i Note 44 | err := row.Scan( 45 | &i.ID, 46 | &i.CreatedAt, 47 | &i.UpdatedAt, 48 | &i.Note, 49 | &i.UserID, 50 | ) 51 | return i, err 52 | } 53 | 54 | const getNotesForUser = `-- name: GetNotesForUser :many 55 | 56 | SELECT id, created_at, updated_at, note, user_id FROM notes WHERE user_id = ? 57 | ` 58 | 59 | func (q *Queries) GetNotesForUser(ctx context.Context, userID string) ([]Note, error) { 60 | rows, err := q.db.QueryContext(ctx, getNotesForUser, userID) 61 | if err != nil { 62 | return nil, err 63 | } 64 | defer rows.Close() 65 | var items []Note 66 | for rows.Next() { 67 | var i Note 68 | if err := rows.Scan( 69 | &i.ID, 70 | &i.CreatedAt, 71 | &i.UpdatedAt, 72 | &i.Note, 73 | &i.UserID, 74 | ); err != nil { 75 | return nil, err 76 | } 77 | items = append(items, i) 78 | } 79 | if err := rows.Close(); err != nil { 80 | return nil, err 81 | } 82 | if err := rows.Err(); err != nil { 83 | return nil, err 84 | } 85 | return items, nil 86 | } 87 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/atn_deserialization_options.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import "errors" 8 | 9 | var defaultATNDeserializationOptions = ATNDeserializationOptions{true, true, false} 10 | 11 | type ATNDeserializationOptions struct { 12 | readOnly bool 13 | verifyATN bool 14 | generateRuleBypassTransitions bool 15 | } 16 | 17 | func (opts *ATNDeserializationOptions) ReadOnly() bool { 18 | return opts.readOnly 19 | } 20 | 21 | func (opts *ATNDeserializationOptions) SetReadOnly(readOnly bool) { 22 | if opts.readOnly { 23 | panic(errors.New("Cannot mutate read only ATNDeserializationOptions")) 24 | } 25 | opts.readOnly = readOnly 26 | } 27 | 28 | func (opts *ATNDeserializationOptions) VerifyATN() bool { 29 | return opts.verifyATN 30 | } 31 | 32 | func (opts *ATNDeserializationOptions) SetVerifyATN(verifyATN bool) { 33 | if opts.readOnly { 34 | panic(errors.New("Cannot mutate read only ATNDeserializationOptions")) 35 | } 36 | opts.verifyATN = verifyATN 37 | } 38 | 39 | func (opts *ATNDeserializationOptions) GenerateRuleBypassTransitions() bool { 40 | return opts.generateRuleBypassTransitions 41 | } 42 | 43 | func (opts *ATNDeserializationOptions) SetGenerateRuleBypassTransitions(generateRuleBypassTransitions bool) { 44 | if opts.readOnly { 45 | panic(errors.New("Cannot mutate read only ATNDeserializationOptions")) 46 | } 47 | opts.generateRuleBypassTransitions = generateRuleBypassTransitions 48 | } 49 | 50 | func DefaultATNDeserializationOptions() *ATNDeserializationOptions { 51 | return NewATNDeserializationOptions(&defaultATNDeserializationOptions) 52 | } 53 | 54 | func NewATNDeserializationOptions(other *ATNDeserializationOptions) *ATNDeserializationOptions { 55 | o := new(ATNDeserializationOptions) 56 | if other != nil { 57 | *o = *other 58 | o.readOnly = false 59 | } 60 | return o 61 | } 62 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // randomBits completely fills slice b with random data. 12 | func randomBits(b []byte) { 13 | if _, err := io.ReadFull(rander, b); err != nil { 14 | panic(err.Error()) // rand should never fail 15 | } 16 | } 17 | 18 | // xvalues returns the value of a byte as a hexadecimal digit or 255. 19 | var xvalues = [256]byte{ 20 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 21 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 22 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 23 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 24 | 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 25 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 26 | 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 27 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 28 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 29 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 30 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 32 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 33 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 34 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 35 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 36 | } 37 | 38 | // xtob converts hex characters x1 and x2 into a byte. 39 | func xtob(x1, x2 byte) (byte, bool) { 40 | b1 := xvalues[x1] 41 | b2 := xvalues[x2] 42 | return (b1 << 4) | b2, b1 != 255 && b2 != 255 43 | } 44 | -------------------------------------------------------------------------------- /handler_user.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "encoding/json" 8 | "net/http" 9 | "time" 10 | 11 | "github.com/bootdotdev/learn-cicd-starter/internal/database" 12 | "github.com/google/uuid" 13 | ) 14 | 15 | func (cfg *apiConfig) handlerUsersCreate(w http.ResponseWriter, r *http.Request) { 16 | type parameters struct { 17 | Name string `json:"name"` 18 | } 19 | decoder := json.NewDecoder(r.Body) 20 | params := parameters{} 21 | err := decoder.Decode(¶ms) 22 | if err != nil { 23 | respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err) 24 | return 25 | } 26 | 27 | apiKey, err := generateRandomSHA256Hash() 28 | if err != nil { 29 | respondWithError(w, http.StatusInternalServerError, "Couldn't gen apikey", err) 30 | return 31 | } 32 | 33 | err = cfg.DB.CreateUser(r.Context(), database.CreateUserParams{ 34 | ID: uuid.New().String(), 35 | CreatedAt: time.Now().UTC().Format(time.RFC3339), 36 | UpdatedAt: time.Now().UTC().Format(time.RFC3339), 37 | Name: params.Name, 38 | ApiKey: apiKey, 39 | }) 40 | if err != nil { 41 | respondWithError(w, http.StatusInternalServerError, "Couldn't create user", err) 42 | return 43 | } 44 | 45 | user, err := cfg.DB.GetUser(r.Context(), apiKey) 46 | if err != nil { 47 | respondWithError(w, http.StatusInternalServerError, "Couldn't get user", err) 48 | return 49 | } 50 | 51 | userResp, err := databaseUserToUser(user) 52 | if err != nil { 53 | respondWithError(w, http.StatusInternalServerError, "Couldn't convert user", err) 54 | return 55 | } 56 | respondWithJSON(w, http.StatusCreated, userResp) 57 | } 58 | 59 | func generateRandomSHA256Hash() (string, error) { 60 | randomBytes := make([]byte, 32) 61 | _, err := rand.Read(randomBytes) 62 | if err != nil { 63 | return "", err 64 | } 65 | hash := sha256.Sum256(randomBytes) 66 | hashString := hex.EncodeToString(hash[:]) 67 | return hashString, nil 68 | } 69 | 70 | func (cfg *apiConfig) handlerUsersGet(w http.ResponseWriter, r *http.Request, user database.User) { 71 | 72 | userResp, err := databaseUserToUser(user) 73 | if err != nil { 74 | respondWithError(w, http.StatusInternalServerError, "Couldn't convert user", err) 75 | return 76 | } 77 | 78 | respondWithJSON(w, http.StatusOK, userResp) 79 | } 80 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/common_token_factory.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | // TokenFactory creates CommonToken objects. 8 | type TokenFactory interface { 9 | Create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token 10 | } 11 | 12 | // CommonTokenFactory is the default TokenFactory implementation. 13 | type CommonTokenFactory struct { 14 | // copyText indicates whether CommonToken.setText should be called after 15 | // constructing tokens to explicitly set the text. This is useful for cases 16 | // where the input stream might not be able to provide arbitrary substrings of 17 | // text from the input after the lexer creates a token (e.g. the 18 | // implementation of CharStream.GetText in UnbufferedCharStream panics an 19 | // UnsupportedOperationException). Explicitly setting the token text allows 20 | // Token.GetText to be called at any time regardless of the input stream 21 | // implementation. 22 | // 23 | // The default value is false to avoid the performance and memory overhead of 24 | // copying text for every token unless explicitly requested. 25 | copyText bool 26 | } 27 | 28 | func NewCommonTokenFactory(copyText bool) *CommonTokenFactory { 29 | return &CommonTokenFactory{copyText: copyText} 30 | } 31 | 32 | // CommonTokenFactoryDEFAULT is the default CommonTokenFactory. It does not 33 | // explicitly copy token text when constructing tokens. 34 | var CommonTokenFactoryDEFAULT = NewCommonTokenFactory(false) 35 | 36 | func (c *CommonTokenFactory) Create(source *TokenSourceCharStreamPair, ttype int, text string, channel, start, stop, line, column int) Token { 37 | t := NewCommonToken(source, ttype, channel, start, stop) 38 | 39 | t.line = line 40 | t.column = column 41 | 42 | if text != "" { 43 | t.SetText(text) 44 | } else if c.copyText && source.charStream != nil { 45 | t.SetText(source.charStream.GetTextFromInterval(NewInterval(start, stop))) 46 | } 47 | 48 | return t 49 | } 50 | 51 | func (c *CommonTokenFactory) createThin(ttype int, text string) Token { 52 | t := NewCommonToken(nil, ttype, TokenDefaultChannel, -1, -1) 53 | t.SetText(text) 54 | 55 | return t 56 | } 57 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/version4.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import "io" 8 | 9 | // New creates a new random UUID or panics. New is equivalent to 10 | // the expression 11 | // 12 | // uuid.Must(uuid.NewRandom()) 13 | func New() UUID { 14 | return Must(NewRandom()) 15 | } 16 | 17 | // NewString creates a new random UUID and returns it as a string or panics. 18 | // NewString is equivalent to the expression 19 | // 20 | // uuid.New().String() 21 | func NewString() string { 22 | return Must(NewRandom()).String() 23 | } 24 | 25 | // NewRandom returns a Random (Version 4) UUID. 26 | // 27 | // The strength of the UUIDs is based on the strength of the crypto/rand 28 | // package. 29 | // 30 | // Uses the randomness pool if it was enabled with EnableRandPool. 31 | // 32 | // A note about uniqueness derived from the UUID Wikipedia entry: 33 | // 34 | // Randomly generated UUIDs have 122 random bits. One's annual risk of being 35 | // hit by a meteorite is estimated to be one chance in 17 billion, that 36 | // means the probability is about 0.00000000006 (6 × 10−11), 37 | // equivalent to the odds of creating a few tens of trillions of UUIDs in a 38 | // year and having one duplicate. 39 | func NewRandom() (UUID, error) { 40 | if !poolEnabled { 41 | return NewRandomFromReader(rander) 42 | } 43 | return newRandomFromPool() 44 | } 45 | 46 | // NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. 47 | func NewRandomFromReader(r io.Reader) (UUID, error) { 48 | var uuid UUID 49 | _, err := io.ReadFull(r, uuid[:]) 50 | if err != nil { 51 | return Nil, err 52 | } 53 | uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 54 | uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 55 | return uuid, nil 56 | } 57 | 58 | func newRandomFromPool() (UUID, error) { 59 | var uuid UUID 60 | poolMu.Lock() 61 | if poolPos == randPoolSize { 62 | _, err := io.ReadFull(rander, pool[:]) 63 | if err != nil { 64 | poolMu.Unlock() 65 | return Nil, err 66 | } 67 | poolPos = 0 68 | } 69 | copy(uuid[:], pool[poolPos:(poolPos+16)]) 70 | poolPos += 16 71 | poolMu.Unlock() 72 | 73 | uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 74 | uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 75 | return uuid, nil 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/dce.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | "fmt" 10 | "os" 11 | ) 12 | 13 | // A Domain represents a Version 2 domain 14 | type Domain byte 15 | 16 | // Domain constants for DCE Security (Version 2) UUIDs. 17 | const ( 18 | Person = Domain(0) 19 | Group = Domain(1) 20 | Org = Domain(2) 21 | ) 22 | 23 | // NewDCESecurity returns a DCE Security (Version 2) UUID. 24 | // 25 | // The domain should be one of Person, Group or Org. 26 | // On a POSIX system the id should be the users UID for the Person 27 | // domain and the users GID for the Group. The meaning of id for 28 | // the domain Org or on non-POSIX systems is site defined. 29 | // 30 | // For a given domain/id pair the same token may be returned for up to 31 | // 7 minutes and 10 seconds. 32 | func NewDCESecurity(domain Domain, id uint32) (UUID, error) { 33 | uuid, err := NewUUID() 34 | if err == nil { 35 | uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 36 | uuid[9] = byte(domain) 37 | binary.BigEndian.PutUint32(uuid[0:], id) 38 | } 39 | return uuid, err 40 | } 41 | 42 | // NewDCEPerson returns a DCE Security (Version 2) UUID in the person 43 | // domain with the id returned by os.Getuid. 44 | // 45 | // NewDCESecurity(Person, uint32(os.Getuid())) 46 | func NewDCEPerson() (UUID, error) { 47 | return NewDCESecurity(Person, uint32(os.Getuid())) 48 | } 49 | 50 | // NewDCEGroup returns a DCE Security (Version 2) UUID in the group 51 | // domain with the id returned by os.Getgid. 52 | // 53 | // NewDCESecurity(Group, uint32(os.Getgid())) 54 | func NewDCEGroup() (UUID, error) { 55 | return NewDCESecurity(Group, uint32(os.Getgid())) 56 | } 57 | 58 | // Domain returns the domain for a Version 2 UUID. Domains are only defined 59 | // for Version 2 UUIDs. 60 | func (uuid UUID) Domain() Domain { 61 | return Domain(uuid[9]) 62 | } 63 | 64 | // ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 65 | // UUIDs. 66 | func (uuid UUID) ID() uint32 { 67 | return binary.BigEndian.Uint32(uuid[0:4]) 68 | } 69 | 70 | func (d Domain) String() string { 71 | switch d { 72 | case Person: 73 | return "Person" 74 | case Group: 75 | return "Group" 76 | case Org: 77 | return "Org" 78 | } 79 | return fmt.Sprintf("Domain%d", int(d)) 80 | } 81 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/hrana/value.go: -------------------------------------------------------------------------------- 1 | package hrana 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | "strconv" 7 | "strings" 8 | "time" 9 | ) 10 | 11 | type Value struct { 12 | Type string `json:"type"` 13 | Value any `json:"value,omitempty"` 14 | Base64 string `json:"base64,omitempty"` 15 | } 16 | 17 | func (v Value) ToValue(columnType *string) any { 18 | if v.Type == "blob" { 19 | bytes, err := base64.StdEncoding.WithPadding(base64.NoPadding).DecodeString(v.Base64) 20 | if err != nil { 21 | return nil 22 | } 23 | return bytes 24 | } else if v.Type == "integer" { 25 | integer, err := strconv.ParseInt(v.Value.(string), 10, 64) 26 | if err != nil { 27 | return nil 28 | } 29 | return integer 30 | } else if columnType != nil { 31 | if (strings.ToLower(*columnType) == "timestamp" || strings.ToLower(*columnType) == "datetime") && v.Type == "text" { 32 | for _, format := range []string{ 33 | "2006-01-02 15:04:05.999999999-07:00", 34 | "2006-01-02T15:04:05.999999999-07:00", 35 | "2006-01-02 15:04:05.999999999", 36 | "2006-01-02T15:04:05.999999999", 37 | "2006-01-02 15:04:05", 38 | "2006-01-02T15:04:05", 39 | "2006-01-02 15:04", 40 | "2006-01-02T15:04", 41 | "2006-01-02", 42 | } { 43 | if t, err := time.ParseInLocation(format, v.Value.(string), time.UTC); err == nil { 44 | return t 45 | } 46 | } 47 | } 48 | } 49 | 50 | return v.Value 51 | } 52 | 53 | func ToValue(v any) (Value, error) { 54 | var res Value 55 | if v == nil { 56 | res.Type = "null" 57 | } else if integer, ok := v.(int64); ok { 58 | res.Type = "integer" 59 | res.Value = strconv.FormatInt(integer, 10) 60 | } else if integer, ok := v.(int); ok { 61 | res.Type = "integer" 62 | res.Value = strconv.FormatInt(int64(integer), 10) 63 | } else if text, ok := v.(string); ok { 64 | res.Type = "text" 65 | res.Value = text 66 | } else if blob, ok := v.([]byte); ok { 67 | res.Type = "blob" 68 | res.Base64 = base64.StdEncoding.WithPadding(base64.NoPadding).EncodeToString(blob) 69 | } else if float, ok := v.(float64); ok { 70 | res.Type = "float" 71 | res.Value = float 72 | } else if t, ok := v.(time.Time); ok { 73 | res.Type = "text" 74 | res.Value = t.Format("2006-01-02 15:04:05.999999999-07:00") 75 | } else if t, ok := v.(bool); ok { 76 | res.Type = "integer" 77 | res.Value = "0" 78 | if t { 79 | res.Value = "1" 80 | } 81 | } else { 82 | return res, fmt.Errorf("unsupported value type: %s", v) 83 | } 84 | return res, nil 85 | } 86 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/close.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | // StatusCode represents a WebSocket status code. 9 | // https://tools.ietf.org/html/rfc6455#section-7.4 10 | type StatusCode int 11 | 12 | // https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number 13 | // 14 | // These are only the status codes defined by the protocol. 15 | // 16 | // You can define custom codes in the 3000-4999 range. 17 | // The 3000-3999 range is reserved for use by libraries, frameworks and applications. 18 | // The 4000-4999 range is reserved for private use. 19 | const ( 20 | StatusNormalClosure StatusCode = 1000 21 | StatusGoingAway StatusCode = 1001 22 | StatusProtocolError StatusCode = 1002 23 | StatusUnsupportedData StatusCode = 1003 24 | 25 | // 1004 is reserved and so unexported. 26 | statusReserved StatusCode = 1004 27 | 28 | // StatusNoStatusRcvd cannot be sent in a close message. 29 | // It is reserved for when a close message is received without 30 | // a status code. 31 | StatusNoStatusRcvd StatusCode = 1005 32 | 33 | // StatusAbnormalClosure is exported for use only with Wasm. 34 | // In non Wasm Go, the returned error will indicate whether the 35 | // connection was closed abnormally. 36 | StatusAbnormalClosure StatusCode = 1006 37 | 38 | StatusInvalidFramePayloadData StatusCode = 1007 39 | StatusPolicyViolation StatusCode = 1008 40 | StatusMessageTooBig StatusCode = 1009 41 | StatusMandatoryExtension StatusCode = 1010 42 | StatusInternalError StatusCode = 1011 43 | StatusServiceRestart StatusCode = 1012 44 | StatusTryAgainLater StatusCode = 1013 45 | StatusBadGateway StatusCode = 1014 46 | 47 | // StatusTLSHandshake is only exported for use with Wasm. 48 | // In non Wasm Go, the returned error will indicate whether there was 49 | // a TLS handshake failure. 50 | StatusTLSHandshake StatusCode = 1015 51 | ) 52 | 53 | // CloseError is returned when the connection is closed with a status and reason. 54 | // 55 | // Use Go 1.13's errors.As to check for this error. 56 | // Also see the CloseStatus helper. 57 | type CloseError struct { 58 | Code StatusCode 59 | Reason string 60 | } 61 | 62 | func (ce CloseError) Error() string { 63 | return fmt.Sprintf("status = %v and reason = %q", ce.Code, ce.Reason) 64 | } 65 | 66 | // CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab 67 | // the status code from a CloseError. 68 | // 69 | // -1 will be returned if the passed error is nil or not a CloseError. 70 | func CloseStatus(err error) StatusCode { 71 | var ce CloseError 72 | if errors.As(err, &ce) { 73 | return ce.Code 74 | } 75 | return -1 76 | } 77 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/node.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "sync" 9 | ) 10 | 11 | var ( 12 | nodeMu sync.Mutex 13 | ifname string // name of interface being used 14 | nodeID [6]byte // hardware for version 1 UUIDs 15 | zeroID [6]byte // nodeID with only 0's 16 | ) 17 | 18 | // NodeInterface returns the name of the interface from which the NodeID was 19 | // derived. The interface "user" is returned if the NodeID was set by 20 | // SetNodeID. 21 | func NodeInterface() string { 22 | defer nodeMu.Unlock() 23 | nodeMu.Lock() 24 | return ifname 25 | } 26 | 27 | // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. 28 | // If name is "" then the first usable interface found will be used or a random 29 | // Node ID will be generated. If a named interface cannot be found then false 30 | // is returned. 31 | // 32 | // SetNodeInterface never fails when name is "". 33 | func SetNodeInterface(name string) bool { 34 | defer nodeMu.Unlock() 35 | nodeMu.Lock() 36 | return setNodeInterface(name) 37 | } 38 | 39 | func setNodeInterface(name string) bool { 40 | iname, addr := getHardwareInterface(name) // null implementation for js 41 | if iname != "" && addr != nil { 42 | ifname = iname 43 | copy(nodeID[:], addr) 44 | return true 45 | } 46 | 47 | // We found no interfaces with a valid hardware address. If name 48 | // does not specify a specific interface generate a random Node ID 49 | // (section 4.1.6) 50 | if name == "" { 51 | ifname = "random" 52 | randomBits(nodeID[:]) 53 | return true 54 | } 55 | return false 56 | } 57 | 58 | // NodeID returns a slice of a copy of the current Node ID, setting the Node ID 59 | // if not already set. 60 | func NodeID() []byte { 61 | defer nodeMu.Unlock() 62 | nodeMu.Lock() 63 | if nodeID == zeroID { 64 | setNodeInterface("") 65 | } 66 | nid := nodeID 67 | return nid[:] 68 | } 69 | 70 | // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes 71 | // of id are used. If id is less than 6 bytes then false is returned and the 72 | // Node ID is not set. 73 | func SetNodeID(id []byte) bool { 74 | if len(id) < 6 { 75 | return false 76 | } 77 | defer nodeMu.Unlock() 78 | nodeMu.Lock() 79 | copy(nodeID[:], id) 80 | ifname = "user" 81 | return true 82 | } 83 | 84 | // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is 85 | // not valid. The NodeID is only well defined for version 1 and 2 UUIDs. 86 | func (uuid UUID) NodeID() []byte { 87 | var node [6]byte 88 | copy(node[:], uuid[10:]) 89 | return node[:] 90 | } 91 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "embed" 6 | "io" 7 | "log" 8 | "net/http" 9 | "os" 10 | 11 | "github.com/go-chi/chi" 12 | "github.com/go-chi/cors" 13 | "github.com/joho/godotenv" 14 | 15 | "github.com/bootdotdev/learn-cicd-starter/internal/database" 16 | 17 | _ "github.com/tursodatabase/libsql-client-go/libsql" 18 | ) 19 | 20 | type apiConfig struct { 21 | DB *database.Queries 22 | } 23 | 24 | //go:embed static/* 25 | var staticFiles embed.FS 26 | 27 | func main() { 28 | err := godotenv.Load(".env") 29 | if err != nil { 30 | log.Printf("warning: assuming default configuration. .env unreadable: %v", err) 31 | } 32 | 33 | port := os.Getenv("PORT") 34 | if port == "" { 35 | log.Fatal("PORT environment variable is not set") 36 | } 37 | 38 | apiCfg := apiConfig{} 39 | 40 | // https://github.com/libsql/libsql-client-go/#open-a-connection-to-sqld 41 | // libsql://[your-database].turso.io?authToken=[your-auth-token] 42 | dbURL := os.Getenv("DATABASE_URL") 43 | if dbURL == "" { 44 | log.Println("DATABASE_URL environment variable is not set") 45 | log.Println("Running without CRUD endpoints") 46 | } else { 47 | db, err := sql.Open("libsql", dbURL) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | dbQueries := database.New(db) 52 | apiCfg.DB = dbQueries 53 | log.Println("Connected to database!") 54 | } 55 | 56 | router := chi.NewRouter() 57 | 58 | router.Use(cors.Handler(cors.Options{ 59 | AllowedOrigins: []string{"https://*", "http://*"}, 60 | AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, 61 | AllowedHeaders: []string{"*"}, 62 | ExposedHeaders: []string{"Link"}, 63 | AllowCredentials: false, 64 | MaxAge: 300, 65 | })) 66 | 67 | router.Get("/", func(w http.ResponseWriter, r *http.Request) { 68 | f, err := staticFiles.Open("static/index.html") 69 | if err != nil { 70 | http.Error(w, err.Error(), http.StatusInternalServerError) 71 | return 72 | } 73 | defer f.Close() 74 | if _, err := io.Copy(w, f); err != nil { 75 | http.Error(w, err.Error(), http.StatusInternalServerError) 76 | } 77 | }) 78 | 79 | v1Router := chi.NewRouter() 80 | 81 | if apiCfg.DB != nil { 82 | v1Router.Post("/users", apiCfg.handlerUsersCreate) 83 | v1Router.Get("/users", apiCfg.middlewareAuth(apiCfg.handlerUsersGet)) 84 | v1Router.Get("/notes", apiCfg.middlewareAuth(apiCfg.handlerNotesGet)) 85 | v1Router.Post("/notes", apiCfg.middlewareAuth(apiCfg.handlerNotesCreate)) 86 | } 87 | 88 | v1Router.Get("/healthz", handlerReadiness) 89 | 90 | router.Mount("/v1", v1Router) 91 | srv := &http.Server{ 92 | Addr: ":" + port, 93 | Handler: router, 94 | } 95 | 96 | log.Printf("Serving on port: %s\n", port) 97 | log.Fatal(srv.ListenAndServe()) 98 | } 99 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/input_stream.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type InputStream struct { 8 | name string 9 | index int 10 | data []rune 11 | size int 12 | } 13 | 14 | func NewInputStream(data string) *InputStream { 15 | 16 | is := new(InputStream) 17 | 18 | is.name = "" 19 | is.index = 0 20 | is.data = []rune(data) 21 | is.size = len(is.data) // number of runes 22 | 23 | return is 24 | } 25 | 26 | func (is *InputStream) reset() { 27 | is.index = 0 28 | } 29 | 30 | func (is *InputStream) Consume() { 31 | if is.index >= is.size { 32 | // assert is.LA(1) == TokenEOF 33 | panic("cannot consume EOF") 34 | } 35 | is.index++ 36 | } 37 | 38 | func (is *InputStream) LA(offset int) int { 39 | 40 | if offset == 0 { 41 | return 0 // nil 42 | } 43 | if offset < 0 { 44 | offset++ // e.g., translate LA(-1) to use offset=0 45 | } 46 | pos := is.index + offset - 1 47 | 48 | if pos < 0 || pos >= is.size { // invalid 49 | return TokenEOF 50 | } 51 | 52 | return int(is.data[pos]) 53 | } 54 | 55 | func (is *InputStream) LT(offset int) int { 56 | return is.LA(offset) 57 | } 58 | 59 | func (is *InputStream) Index() int { 60 | return is.index 61 | } 62 | 63 | func (is *InputStream) Size() int { 64 | return is.size 65 | } 66 | 67 | // mark/release do nothing we have entire buffer 68 | func (is *InputStream) Mark() int { 69 | return -1 70 | } 71 | 72 | func (is *InputStream) Release(marker int) { 73 | } 74 | 75 | func (is *InputStream) Seek(index int) { 76 | if index <= is.index { 77 | is.index = index // just jump don't update stream state (line,...) 78 | return 79 | } 80 | // seek forward 81 | is.index = intMin(index, is.size) 82 | } 83 | 84 | func (is *InputStream) GetText(start int, stop int) string { 85 | if stop >= is.size { 86 | stop = is.size - 1 87 | } 88 | if start >= is.size { 89 | return "" 90 | } 91 | 92 | return string(is.data[start : stop+1]) 93 | } 94 | 95 | func (is *InputStream) GetTextFromTokens(start, stop Token) string { 96 | if start != nil && stop != nil { 97 | return is.GetTextFromInterval(NewInterval(start.GetTokenIndex(), stop.GetTokenIndex())) 98 | } 99 | 100 | return "" 101 | } 102 | 103 | func (is *InputStream) GetTextFromInterval(i *Interval) string { 104 | return is.GetText(i.Start, i.Stop) 105 | } 106 | 107 | func (*InputStream) GetSourceName() string { 108 | return "Obtained from string" 109 | } 110 | 111 | func (is *InputStream) String() string { 112 | return string(is.data) 113 | } 114 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/antlrdoc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package antlr implements the Go version of the ANTLR 4 runtime. 3 | 4 | # The ANTLR Tool 5 | 6 | ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, 7 | or translating structured text or binary files. It's widely used to build languages, tools, and frameworks. 8 | From a grammar, ANTLR generates a parser that can build parse trees and also generates a listener interface 9 | (or visitor) that makes it easy to respond to the recognition of phrases of interest. 10 | 11 | # Code Generation 12 | 13 | ANTLR supports the generation of code in a number of [target languages], and the generated code is supported by a 14 | runtime library, written specifically to support the generated code in the target language. This library is the 15 | runtime for the Go target. 16 | 17 | To generate code for the go target, it is generally recommended to place the source grammar files in a package of 18 | their own, and use the `.sh` script method of generating code, using the go generate directive. In that same directory 19 | it is usual, though not required, to place the antlr tool that should be used to generate the code. That does mean 20 | that the antlr tool JAR file will be checked in to your source code control though, so you are free to use any other 21 | way of specifying the version of the ANTLR tool to use, such as aliasing in `.zshrc` or equivalent, or a profile in 22 | your IDE, or configuration in your CI system. 23 | 24 | Here is a general template for an ANTLR based recognizer in Go: 25 | 26 | . 27 | ├── myproject 28 | ├── parser 29 | │ ├── mygrammar.g4 30 | │ ├── antlr-4.12.0-complete.jar 31 | │ ├── error_listeners.go 32 | │ ├── generate.go 33 | │ ├── generate.sh 34 | ├── go.mod 35 | ├── go.sum 36 | ├── main.go 37 | └── main_test.go 38 | 39 | Make sure that the package statement in your grammar file(s) reflects the go package they exist in. 40 | The generate.go file then looks like this: 41 | 42 | package parser 43 | 44 | //go:generate ./generate.sh 45 | 46 | And the generate.sh file will look similar to this: 47 | 48 | #!/bin/sh 49 | 50 | alias antlr4='java -Xmx500M -cp "./antlr4-4.12.0-complete.jar:$CLASSPATH" org.antlr.v4.Tool' 51 | antlr4 -Dlanguage=Go -no-visitor -package parser *.g4 52 | 53 | depending on whether you want visitors or listeners or any other ANTLR options. 54 | 55 | From the command line at the root of your package “myproject” you can then simply issue the command: 56 | 57 | go generate ./... 58 | 59 | # Copyright Notice 60 | 61 | Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 62 | 63 | Use of this file is governed by the BSD 3-clause license, which can be found in the [LICENSE.txt] file in the project root. 64 | 65 | [target languages]: https://github.com/antlr/antlr4/tree/master/runtime 66 | [LICENSE.txt]: https://github.com/antlr/antlr4/blob/master/LICENSE.txt 67 | */ 68 | package antlr 69 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/null.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "bytes" 9 | "database/sql/driver" 10 | "encoding/json" 11 | "fmt" 12 | ) 13 | 14 | var jsonNull = []byte("null") 15 | 16 | // NullUUID represents a UUID that may be null. 17 | // NullUUID implements the SQL driver.Scanner interface so 18 | // it can be used as a scan destination: 19 | // 20 | // var u uuid.NullUUID 21 | // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) 22 | // ... 23 | // if u.Valid { 24 | // // use u.UUID 25 | // } else { 26 | // // NULL value 27 | // } 28 | // 29 | type NullUUID struct { 30 | UUID UUID 31 | Valid bool // Valid is true if UUID is not NULL 32 | } 33 | 34 | // Scan implements the SQL driver.Scanner interface. 35 | func (nu *NullUUID) Scan(value interface{}) error { 36 | if value == nil { 37 | nu.UUID, nu.Valid = Nil, false 38 | return nil 39 | } 40 | 41 | err := nu.UUID.Scan(value) 42 | if err != nil { 43 | nu.Valid = false 44 | return err 45 | } 46 | 47 | nu.Valid = true 48 | return nil 49 | } 50 | 51 | // Value implements the driver Valuer interface. 52 | func (nu NullUUID) Value() (driver.Value, error) { 53 | if !nu.Valid { 54 | return nil, nil 55 | } 56 | // Delegate to UUID Value function 57 | return nu.UUID.Value() 58 | } 59 | 60 | // MarshalBinary implements encoding.BinaryMarshaler. 61 | func (nu NullUUID) MarshalBinary() ([]byte, error) { 62 | if nu.Valid { 63 | return nu.UUID[:], nil 64 | } 65 | 66 | return []byte(nil), nil 67 | } 68 | 69 | // UnmarshalBinary implements encoding.BinaryUnmarshaler. 70 | func (nu *NullUUID) UnmarshalBinary(data []byte) error { 71 | if len(data) != 16 { 72 | return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) 73 | } 74 | copy(nu.UUID[:], data) 75 | nu.Valid = true 76 | return nil 77 | } 78 | 79 | // MarshalText implements encoding.TextMarshaler. 80 | func (nu NullUUID) MarshalText() ([]byte, error) { 81 | if nu.Valid { 82 | return nu.UUID.MarshalText() 83 | } 84 | 85 | return jsonNull, nil 86 | } 87 | 88 | // UnmarshalText implements encoding.TextUnmarshaler. 89 | func (nu *NullUUID) UnmarshalText(data []byte) error { 90 | id, err := ParseBytes(data) 91 | if err != nil { 92 | nu.Valid = false 93 | return err 94 | } 95 | nu.UUID = id 96 | nu.Valid = true 97 | return nil 98 | } 99 | 100 | // MarshalJSON implements json.Marshaler. 101 | func (nu NullUUID) MarshalJSON() ([]byte, error) { 102 | if nu.Valid { 103 | return json.Marshal(nu.UUID) 104 | } 105 | 106 | return jsonNull, nil 107 | } 108 | 109 | // UnmarshalJSON implements json.Unmarshaler. 110 | func (nu *NullUUID) UnmarshalJSON(data []byte) error { 111 | if bytes.Equal(data, jsonNull) { 112 | *nu = NullUUID{} 113 | return nil // valid null UUID 114 | } 115 | err := json.Unmarshal(data, &nu.UUID) 116 | nu.Valid = err == nil 117 | return err 118 | } 119 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/stringer.go: -------------------------------------------------------------------------------- 1 | // Code generated by "stringer -type=opcode,MessageType,StatusCode -output=stringer.go"; DO NOT EDIT. 2 | 3 | package websocket 4 | 5 | import "strconv" 6 | 7 | func _() { 8 | // An "invalid array index" compiler error signifies that the constant values have changed. 9 | // Re-run the stringer command to generate them again. 10 | var x [1]struct{} 11 | _ = x[opContinuation-0] 12 | _ = x[opText-1] 13 | _ = x[opBinary-2] 14 | _ = x[opClose-8] 15 | _ = x[opPing-9] 16 | _ = x[opPong-10] 17 | } 18 | 19 | const ( 20 | _opcode_name_0 = "opContinuationopTextopBinary" 21 | _opcode_name_1 = "opCloseopPingopPong" 22 | ) 23 | 24 | var ( 25 | _opcode_index_0 = [...]uint8{0, 14, 20, 28} 26 | _opcode_index_1 = [...]uint8{0, 7, 13, 19} 27 | ) 28 | 29 | func (i opcode) String() string { 30 | switch { 31 | case 0 <= i && i <= 2: 32 | return _opcode_name_0[_opcode_index_0[i]:_opcode_index_0[i+1]] 33 | case 8 <= i && i <= 10: 34 | i -= 8 35 | return _opcode_name_1[_opcode_index_1[i]:_opcode_index_1[i+1]] 36 | default: 37 | return "opcode(" + strconv.FormatInt(int64(i), 10) + ")" 38 | } 39 | } 40 | func _() { 41 | // An "invalid array index" compiler error signifies that the constant values have changed. 42 | // Re-run the stringer command to generate them again. 43 | var x [1]struct{} 44 | _ = x[MessageText-1] 45 | _ = x[MessageBinary-2] 46 | } 47 | 48 | const _MessageType_name = "MessageTextMessageBinary" 49 | 50 | var _MessageType_index = [...]uint8{0, 11, 24} 51 | 52 | func (i MessageType) String() string { 53 | i -= 1 54 | if i < 0 || i >= MessageType(len(_MessageType_index)-1) { 55 | return "MessageType(" + strconv.FormatInt(int64(i+1), 10) + ")" 56 | } 57 | return _MessageType_name[_MessageType_index[i]:_MessageType_index[i+1]] 58 | } 59 | func _() { 60 | // An "invalid array index" compiler error signifies that the constant values have changed. 61 | // Re-run the stringer command to generate them again. 62 | var x [1]struct{} 63 | _ = x[StatusNormalClosure-1000] 64 | _ = x[StatusGoingAway-1001] 65 | _ = x[StatusProtocolError-1002] 66 | _ = x[StatusUnsupportedData-1003] 67 | _ = x[statusReserved-1004] 68 | _ = x[StatusNoStatusRcvd-1005] 69 | _ = x[StatusAbnormalClosure-1006] 70 | _ = x[StatusInvalidFramePayloadData-1007] 71 | _ = x[StatusPolicyViolation-1008] 72 | _ = x[StatusMessageTooBig-1009] 73 | _ = x[StatusMandatoryExtension-1010] 74 | _ = x[StatusInternalError-1011] 75 | _ = x[StatusServiceRestart-1012] 76 | _ = x[StatusTryAgainLater-1013] 77 | _ = x[StatusBadGateway-1014] 78 | _ = x[StatusTLSHandshake-1015] 79 | } 80 | 81 | const _StatusCode_name = "StatusNormalClosureStatusGoingAwayStatusProtocolErrorStatusUnsupportedDatastatusReservedStatusNoStatusRcvdStatusAbnormalClosureStatusInvalidFramePayloadDataStatusPolicyViolationStatusMessageTooBigStatusMandatoryExtensionStatusInternalErrorStatusServiceRestartStatusTryAgainLaterStatusBadGatewayStatusTLSHandshake" 82 | 83 | var _StatusCode_index = [...]uint16{0, 19, 34, 53, 74, 88, 106, 127, 156, 177, 196, 220, 239, 259, 278, 294, 312} 84 | 85 | func (i StatusCode) String() string { 86 | i -= 1000 87 | if i < 0 || i >= StatusCode(len(_StatusCode_index)-1) { 88 | return "StatusCode(" + strconv.FormatInt(int64(i+1000), 10) + ")" 89 | } 90 | return _StatusCode_name[_StatusCode_index[i]:_StatusCode_index[i+1]] 91 | } 92 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/rule_context.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | // A rule context is a record of a single rule invocation. It knows 8 | // which context invoked it, if any. If there is no parent context, then 9 | // naturally the invoking state is not valid. The parent link 10 | // provides a chain upwards from the current rule invocation to the root 11 | // of the invocation tree, forming a stack. We actually carry no 12 | // information about the rule associated with b context (except 13 | // when parsing). We keep only the state number of the invoking state from 14 | // the ATN submachine that invoked b. Contrast b with the s 15 | // pointer inside ParserRuleContext that tracks the current state 16 | // being "executed" for the current rule. 17 | // 18 | // The parent contexts are useful for computing lookahead sets and 19 | // getting error information. 20 | // 21 | // These objects are used during parsing and prediction. 22 | // For the special case of parsers, we use the subclass 23 | // ParserRuleContext. 24 | // 25 | // @see ParserRuleContext 26 | // 27 | 28 | type RuleContext interface { 29 | RuleNode 30 | 31 | GetInvokingState() int 32 | SetInvokingState(int) 33 | 34 | GetRuleIndex() int 35 | IsEmpty() bool 36 | 37 | GetAltNumber() int 38 | SetAltNumber(altNumber int) 39 | 40 | String([]string, RuleContext) string 41 | } 42 | 43 | type BaseRuleContext struct { 44 | parentCtx RuleContext 45 | invokingState int 46 | RuleIndex int 47 | } 48 | 49 | func NewBaseRuleContext(parent RuleContext, invokingState int) *BaseRuleContext { 50 | 51 | rn := new(BaseRuleContext) 52 | 53 | // What context invoked b rule? 54 | rn.parentCtx = parent 55 | 56 | // What state invoked the rule associated with b context? 57 | // The "return address" is the followState of invokingState 58 | // If parent is nil, b should be -1. 59 | if parent == nil { 60 | rn.invokingState = -1 61 | } else { 62 | rn.invokingState = invokingState 63 | } 64 | 65 | return rn 66 | } 67 | 68 | func (b *BaseRuleContext) GetBaseRuleContext() *BaseRuleContext { 69 | return b 70 | } 71 | 72 | func (b *BaseRuleContext) SetParent(v Tree) { 73 | if v == nil { 74 | b.parentCtx = nil 75 | } else { 76 | b.parentCtx = v.(RuleContext) 77 | } 78 | } 79 | 80 | func (b *BaseRuleContext) GetInvokingState() int { 81 | return b.invokingState 82 | } 83 | 84 | func (b *BaseRuleContext) SetInvokingState(t int) { 85 | b.invokingState = t 86 | } 87 | 88 | func (b *BaseRuleContext) GetRuleIndex() int { 89 | return b.RuleIndex 90 | } 91 | 92 | func (b *BaseRuleContext) GetAltNumber() int { 93 | return ATNInvalidAltNumber 94 | } 95 | 96 | func (b *BaseRuleContext) SetAltNumber(altNumber int) {} 97 | 98 | // A context is empty if there is no invoking state meaning nobody call 99 | // current context. 100 | func (b *BaseRuleContext) IsEmpty() bool { 101 | return b.invokingState == -1 102 | } 103 | 104 | // Return the combined text of all child nodes. This method only considers 105 | // tokens which have been added to the parse tree. 106 | //

107 | // Since tokens on hidden channels (e.g. whitespace or comments) are not 108 | // added to the parse trees, they will not appear in the output of b 109 | // method. 110 | // 111 | 112 | func (b *BaseRuleContext) GetParent() Tree { 113 | return b.parentCtx 114 | } 115 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/dfa_serializer.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "fmt" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | // DFASerializer is a DFA walker that knows how to dump them to serialized 14 | // strings. 15 | type DFASerializer struct { 16 | dfa *DFA 17 | literalNames []string 18 | symbolicNames []string 19 | } 20 | 21 | func NewDFASerializer(dfa *DFA, literalNames, symbolicNames []string) *DFASerializer { 22 | if literalNames == nil { 23 | literalNames = make([]string, 0) 24 | } 25 | 26 | if symbolicNames == nil { 27 | symbolicNames = make([]string, 0) 28 | } 29 | 30 | return &DFASerializer{ 31 | dfa: dfa, 32 | literalNames: literalNames, 33 | symbolicNames: symbolicNames, 34 | } 35 | } 36 | 37 | func (d *DFASerializer) String() string { 38 | if d.dfa.getS0() == nil { 39 | return "" 40 | } 41 | 42 | buf := "" 43 | states := d.dfa.sortedStates() 44 | 45 | for _, s := range states { 46 | if s.edges != nil { 47 | n := len(s.edges) 48 | 49 | for j := 0; j < n; j++ { 50 | t := s.edges[j] 51 | 52 | if t != nil && t.stateNumber != 0x7FFFFFFF { 53 | buf += d.GetStateString(s) 54 | buf += "-" 55 | buf += d.getEdgeLabel(j) 56 | buf += "->" 57 | buf += d.GetStateString(t) 58 | buf += "\n" 59 | } 60 | } 61 | } 62 | } 63 | 64 | if len(buf) == 0 { 65 | return "" 66 | } 67 | 68 | return buf 69 | } 70 | 71 | func (d *DFASerializer) getEdgeLabel(i int) string { 72 | if i == 0 { 73 | return "EOF" 74 | } else if d.literalNames != nil && i-1 < len(d.literalNames) { 75 | return d.literalNames[i-1] 76 | } else if d.symbolicNames != nil && i-1 < len(d.symbolicNames) { 77 | return d.symbolicNames[i-1] 78 | } 79 | 80 | return strconv.Itoa(i - 1) 81 | } 82 | 83 | func (d *DFASerializer) GetStateString(s *DFAState) string { 84 | var a, b string 85 | 86 | if s.isAcceptState { 87 | a = ":" 88 | } 89 | 90 | if s.requiresFullContext { 91 | b = "^" 92 | } 93 | 94 | baseStateStr := a + "s" + strconv.Itoa(s.stateNumber) + b 95 | 96 | if s.isAcceptState { 97 | if s.predicates != nil { 98 | return baseStateStr + "=>" + fmt.Sprint(s.predicates) 99 | } 100 | 101 | return baseStateStr + "=>" + fmt.Sprint(s.prediction) 102 | } 103 | 104 | return baseStateStr 105 | } 106 | 107 | type LexerDFASerializer struct { 108 | *DFASerializer 109 | } 110 | 111 | func NewLexerDFASerializer(dfa *DFA) *LexerDFASerializer { 112 | return &LexerDFASerializer{DFASerializer: NewDFASerializer(dfa, nil, nil)} 113 | } 114 | 115 | func (l *LexerDFASerializer) getEdgeLabel(i int) string { 116 | var sb strings.Builder 117 | sb.Grow(6) 118 | sb.WriteByte('\'') 119 | sb.WriteRune(rune(i)) 120 | sb.WriteByte('\'') 121 | return sb.String() 122 | } 123 | 124 | func (l *LexerDFASerializer) String() string { 125 | if l.dfa.getS0() == nil { 126 | return "" 127 | } 128 | 129 | buf := "" 130 | states := l.dfa.sortedStates() 131 | 132 | for i := 0; i < len(states); i++ { 133 | s := states[i] 134 | 135 | if s.edges != nil { 136 | n := len(s.edges) 137 | 138 | for j := 0; j < n; j++ { 139 | t := s.edges[j] 140 | 141 | if t != nil && t.stateNumber != 0x7FFFFFFF { 142 | buf += l.GetStateString(s) 143 | buf += "-" 144 | buf += l.getEdgeLabel(j) 145 | buf += "->" 146 | buf += l.GetStateString(t) 147 | buf += "\n" 148 | } 149 | } 150 | } 151 | } 152 | 153 | if len(buf) == 0 { 154 | return "" 155 | } 156 | 157 | return buf 158 | } 159 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/trees.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import "fmt" 8 | 9 | /** A set of utility routines useful for all kinds of ANTLR trees. */ 10 | 11 | // Print out a whole tree in LISP form. {@link //getNodeText} is used on the 12 | // 13 | // node payloads to get the text for the nodes. Detect 14 | // parse trees and extract data appropriately. 15 | func TreesStringTree(tree Tree, ruleNames []string, recog Recognizer) string { 16 | 17 | if recog != nil { 18 | ruleNames = recog.GetRuleNames() 19 | } 20 | 21 | s := TreesGetNodeText(tree, ruleNames, nil) 22 | 23 | s = EscapeWhitespace(s, false) 24 | c := tree.GetChildCount() 25 | if c == 0 { 26 | return s 27 | } 28 | res := "(" + s + " " 29 | if c > 0 { 30 | s = TreesStringTree(tree.GetChild(0), ruleNames, nil) 31 | res += s 32 | } 33 | for i := 1; i < c; i++ { 34 | s = TreesStringTree(tree.GetChild(i), ruleNames, nil) 35 | res += (" " + s) 36 | } 37 | res += ")" 38 | return res 39 | } 40 | 41 | func TreesGetNodeText(t Tree, ruleNames []string, recog Parser) string { 42 | if recog != nil { 43 | ruleNames = recog.GetRuleNames() 44 | } 45 | 46 | if ruleNames != nil { 47 | switch t2 := t.(type) { 48 | case RuleNode: 49 | t3 := t2.GetRuleContext() 50 | altNumber := t3.GetAltNumber() 51 | 52 | if altNumber != ATNInvalidAltNumber { 53 | return fmt.Sprintf("%s:%d", ruleNames[t3.GetRuleIndex()], altNumber) 54 | } 55 | return ruleNames[t3.GetRuleIndex()] 56 | case ErrorNode: 57 | return fmt.Sprint(t2) 58 | case TerminalNode: 59 | if t2.GetSymbol() != nil { 60 | return t2.GetSymbol().GetText() 61 | } 62 | } 63 | } 64 | 65 | // no recog for rule names 66 | payload := t.GetPayload() 67 | if p2, ok := payload.(Token); ok { 68 | return p2.GetText() 69 | } 70 | 71 | return fmt.Sprint(t.GetPayload()) 72 | } 73 | 74 | // Return ordered list of all children of this node 75 | func TreesGetChildren(t Tree) []Tree { 76 | list := make([]Tree, 0) 77 | for i := 0; i < t.GetChildCount(); i++ { 78 | list = append(list, t.GetChild(i)) 79 | } 80 | return list 81 | } 82 | 83 | // Return a list of all ancestors of this node. The first node of 84 | // 85 | // list is the root and the last is the parent of this node. 86 | func TreesgetAncestors(t Tree) []Tree { 87 | ancestors := make([]Tree, 0) 88 | t = t.GetParent() 89 | for t != nil { 90 | f := []Tree{t} 91 | ancestors = append(f, ancestors...) 92 | t = t.GetParent() 93 | } 94 | return ancestors 95 | } 96 | 97 | func TreesFindAllTokenNodes(t ParseTree, ttype int) []ParseTree { 98 | return TreesfindAllNodes(t, ttype, true) 99 | } 100 | 101 | func TreesfindAllRuleNodes(t ParseTree, ruleIndex int) []ParseTree { 102 | return TreesfindAllNodes(t, ruleIndex, false) 103 | } 104 | 105 | func TreesfindAllNodes(t ParseTree, index int, findTokens bool) []ParseTree { 106 | nodes := make([]ParseTree, 0) 107 | treesFindAllNodes(t, index, findTokens, &nodes) 108 | return nodes 109 | } 110 | 111 | func treesFindAllNodes(t ParseTree, index int, findTokens bool, nodes *[]ParseTree) { 112 | // check this node (the root) first 113 | 114 | t2, ok := t.(TerminalNode) 115 | t3, ok2 := t.(ParserRuleContext) 116 | 117 | if findTokens && ok { 118 | if t2.GetSymbol().GetTokenType() == index { 119 | *nodes = append(*nodes, t2) 120 | } 121 | } else if !findTokens && ok2 { 122 | if t3.GetRuleIndex() == index { 123 | *nodes = append(*nodes, t3) 124 | } 125 | } 126 | // check children 127 | for i := 0; i < t.GetChildCount(); i++ { 128 | treesFindAllNodes(t.GetChild(i).(ParseTree), index, findTokens, nodes) 129 | } 130 | } 131 | 132 | func TreesDescendants(t ParseTree) []ParseTree { 133 | nodes := []ParseTree{t} 134 | for i := 0; i < t.GetChildCount(); i++ { 135 | nodes = append(nodes, TreesDescendants(t.GetChild(i).(ParseTree))...) 136 | } 137 | return nodes 138 | } 139 | -------------------------------------------------------------------------------- /vendor/github.com/google/uuid/time.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | // A Time represents a time as the number of 100's of nanoseconds since 15 Oct 14 | // 1582. 15 | type Time int64 16 | 17 | const ( 18 | lillian = 2299160 // Julian day of 15 Oct 1582 19 | unix = 2440587 // Julian day of 1 Jan 1970 20 | epoch = unix - lillian // Days between epochs 21 | g1582 = epoch * 86400 // seconds between epochs 22 | g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs 23 | ) 24 | 25 | var ( 26 | timeMu sync.Mutex 27 | lasttime uint64 // last time we returned 28 | clockSeq uint16 // clock sequence for this run 29 | 30 | timeNow = time.Now // for testing 31 | ) 32 | 33 | // UnixTime converts t the number of seconds and nanoseconds using the Unix 34 | // epoch of 1 Jan 1970. 35 | func (t Time) UnixTime() (sec, nsec int64) { 36 | sec = int64(t - g1582ns100) 37 | nsec = (sec % 10000000) * 100 38 | sec /= 10000000 39 | return sec, nsec 40 | } 41 | 42 | // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and 43 | // clock sequence as well as adjusting the clock sequence as needed. An error 44 | // is returned if the current time cannot be determined. 45 | func GetTime() (Time, uint16, error) { 46 | defer timeMu.Unlock() 47 | timeMu.Lock() 48 | return getTime() 49 | } 50 | 51 | func getTime() (Time, uint16, error) { 52 | t := timeNow() 53 | 54 | // If we don't have a clock sequence already, set one. 55 | if clockSeq == 0 { 56 | setClockSequence(-1) 57 | } 58 | now := uint64(t.UnixNano()/100) + g1582ns100 59 | 60 | // If time has gone backwards with this clock sequence then we 61 | // increment the clock sequence 62 | if now <= lasttime { 63 | clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 64 | } 65 | lasttime = now 66 | return Time(now), clockSeq, nil 67 | } 68 | 69 | // ClockSequence returns the current clock sequence, generating one if not 70 | // already set. The clock sequence is only used for Version 1 UUIDs. 71 | // 72 | // The uuid package does not use global static storage for the clock sequence or 73 | // the last time a UUID was generated. Unless SetClockSequence is used, a new 74 | // random clock sequence is generated the first time a clock sequence is 75 | // requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) 76 | func ClockSequence() int { 77 | defer timeMu.Unlock() 78 | timeMu.Lock() 79 | return clockSequence() 80 | } 81 | 82 | func clockSequence() int { 83 | if clockSeq == 0 { 84 | setClockSequence(-1) 85 | } 86 | return int(clockSeq & 0x3fff) 87 | } 88 | 89 | // SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to 90 | // -1 causes a new sequence to be generated. 91 | func SetClockSequence(seq int) { 92 | defer timeMu.Unlock() 93 | timeMu.Lock() 94 | setClockSequence(seq) 95 | } 96 | 97 | func setClockSequence(seq int) { 98 | if seq == -1 { 99 | var b [2]byte 100 | randomBits(b[:]) // clock sequence 101 | seq = int(b[0])<<8 | int(b[1]) 102 | } 103 | oldSeq := clockSeq 104 | clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant 105 | if oldSeq != clockSeq { 106 | lasttime = 0 107 | } 108 | } 109 | 110 | // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in 111 | // uuid. The time is only defined for version 1 and 2 UUIDs. 112 | func (uuid UUID) Time() Time { 113 | time := int64(binary.BigEndian.Uint32(uuid[0:4])) 114 | time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 115 | time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 116 | return Time(time) 117 | } 118 | 119 | // ClockSequence returns the clock sequence encoded in uuid. 120 | // The clock sequence is only well defined for version 1 and 2 UUIDs. 121 | func (uuid UUID) ClockSequence() int { 122 | return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff 123 | } 124 | -------------------------------------------------------------------------------- /vendor/github.com/libsql/sqlite-antlr4-parser/sqliteparserutils/utils.go: -------------------------------------------------------------------------------- 1 | package sqliteparserutils 2 | 3 | import ( 4 | "github.com/antlr/antlr4/runtime/Go/antlr/v4" 5 | "github.com/libsql/sqlite-antlr4-parser/sqliteparser" 6 | ) 7 | 8 | // TODO: Shell test begin transaction on shell 9 | 10 | type SplitStatementExtraInfo struct { 11 | IncompleteCreateTriggerStatement bool 12 | IncompleteMultilineComment bool 13 | LastTokenType int 14 | } 15 | 16 | func SplitStatement(statement string) (stmts []string, extraInfo SplitStatementExtraInfo) { 17 | tokenStream := createTokenStream(statement) 18 | 19 | stmtIntervals := make([]*antlr.Interval, 0) 20 | currentIntervalStart := -1 21 | insideCreateTriggerStmt := false 22 | insideMultilineComment := false 23 | 24 | var previousToken antlr.Token 25 | var currentToken antlr.Token 26 | for currentToken = tokenStream.LT(1); currentToken.GetTokenType() != antlr.TokenEOF; currentToken = tokenStream.LT(1) { 27 | // We break loop here because we're sure multiline comment didn't finished, otherwise lexer would have just ignored 28 | // it 29 | if atIncompleteMultilineCommentStart(tokenStream) { 30 | insideMultilineComment = true 31 | break 32 | } 33 | 34 | if currentIntervalStart == -1 { 35 | if currentToken.GetTokenType() == sqliteparser.SQLiteLexerSCOL { 36 | previousToken = currentToken 37 | tokenStream.Consume() 38 | continue 39 | } 40 | currentIntervalStart = currentToken.GetTokenIndex() 41 | 42 | if atCreateTriggerStart(tokenStream) { 43 | insideCreateTriggerStmt = true 44 | previousToken = currentToken 45 | tokenStream.Consume() 46 | continue 47 | } 48 | 49 | } 50 | 51 | if insideCreateTriggerStmt { 52 | if currentToken.GetTokenType() == sqliteparser.SQLiteLexerEND_ { 53 | insideCreateTriggerStmt = false 54 | } 55 | } else if currentToken.GetTokenType() == sqliteparser.SQLiteLexerSCOL { 56 | stmtIntervals = append(stmtIntervals, antlr.NewInterval(currentIntervalStart, previousToken.GetTokenIndex())) 57 | currentIntervalStart = -1 58 | } 59 | 60 | previousToken = currentToken 61 | tokenStream.Consume() 62 | } 63 | 64 | if currentIntervalStart != -1 && previousToken != nil { 65 | stmtIntervals = append(stmtIntervals, antlr.NewInterval(currentIntervalStart, previousToken.GetTokenIndex())) 66 | } 67 | 68 | stmts = make([]string, 0) 69 | for _, stmtInterval := range stmtIntervals { 70 | stmts = append(stmts, tokenStream.GetTextFromInterval(stmtInterval)) 71 | } 72 | 73 | lastTokenType := antlr.TokenInvalidType 74 | if previousToken != nil { 75 | lastTokenType = previousToken.GetTokenType() 76 | } 77 | return stmts, SplitStatementExtraInfo{IncompleteCreateTriggerStatement: insideCreateTriggerStmt, IncompleteMultilineComment: insideMultilineComment, LastTokenType: lastTokenType} 78 | } 79 | 80 | func atCreateTriggerStart(tokenStream antlr.TokenStream) bool { 81 | if tokenStream.LT(1).GetTokenType() != sqliteparser.SQLiteLexerCREATE_ { 82 | return false 83 | } 84 | 85 | if tokenStream.LT(2).GetTokenType() == sqliteparser.SQLiteLexerTRIGGER_ { 86 | return true 87 | } 88 | 89 | if tokenStream.LT(2).GetTokenType() == sqliteparser.SQLiteLexerTEMP_ || tokenStream.LT(2).GetTokenType() == sqliteparser.SQLiteLexerTEMPORARY_ && 90 | tokenStream.LT(3).GetTokenType() == sqliteparser.SQLiteLexerTRIGGER_ { 91 | return true 92 | } 93 | 94 | return false 95 | 96 | } 97 | 98 | // Note: Only starts for incomplete multiline comments will be detected cause lexer automatically ignores complete 99 | // multiline comments 100 | func atIncompleteMultilineCommentStart(tokenStream antlr.TokenStream) bool { 101 | if tokenStream.LT(1).GetTokenType() != sqliteparser.SQLiteLexerDIV { 102 | return false 103 | } 104 | 105 | if tokenStream.LT(2).GetTokenType() == sqliteparser.SQLiteLexerSTAR { 106 | return true 107 | } 108 | 109 | return false 110 | } 111 | 112 | func createTokenStream(statement string) *antlr.CommonTokenStream { 113 | statementStream := antlr.NewInputStream(statement) 114 | 115 | lexer := sqliteparser.NewSQLiteLexer(statementStream) 116 | return antlr.NewCommonTokenStream(lexer, 0) 117 | } 118 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/error_listener.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | "strconv" 11 | ) 12 | 13 | // Provides an empty default implementation of {@link ANTLRErrorListener}. The 14 | // default implementation of each method does nothing, but can be overridden as 15 | // necessary. 16 | 17 | type ErrorListener interface { 18 | SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) 19 | ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) 20 | ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) 21 | ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) 22 | } 23 | 24 | type DefaultErrorListener struct { 25 | } 26 | 27 | func NewDefaultErrorListener() *DefaultErrorListener { 28 | return new(DefaultErrorListener) 29 | } 30 | 31 | func (d *DefaultErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) { 32 | } 33 | 34 | func (d *DefaultErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) { 35 | } 36 | 37 | func (d *DefaultErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) { 38 | } 39 | 40 | func (d *DefaultErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) { 41 | } 42 | 43 | type ConsoleErrorListener struct { 44 | *DefaultErrorListener 45 | } 46 | 47 | func NewConsoleErrorListener() *ConsoleErrorListener { 48 | return new(ConsoleErrorListener) 49 | } 50 | 51 | // Provides a default instance of {@link ConsoleErrorListener}. 52 | var ConsoleErrorListenerINSTANCE = NewConsoleErrorListener() 53 | 54 | // {@inheritDoc} 55 | // 56 | //

57 | // This implementation prints messages to {@link System//err} containing the 58 | // values of {@code line}, {@code charPositionInLine}, and {@code msg} using 59 | // the following format.

60 | // 61 | //
 62 | // line line:charPositionInLine msg
 63 | // 
64 | func (c *ConsoleErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) { 65 | fmt.Fprintln(os.Stderr, "line "+strconv.Itoa(line)+":"+strconv.Itoa(column)+" "+msg) 66 | } 67 | 68 | type ProxyErrorListener struct { 69 | *DefaultErrorListener 70 | delegates []ErrorListener 71 | } 72 | 73 | func NewProxyErrorListener(delegates []ErrorListener) *ProxyErrorListener { 74 | if delegates == nil { 75 | panic("delegates is not provided") 76 | } 77 | l := new(ProxyErrorListener) 78 | l.delegates = delegates 79 | return l 80 | } 81 | 82 | func (p *ProxyErrorListener) SyntaxError(recognizer Recognizer, offendingSymbol interface{}, line, column int, msg string, e RecognitionException) { 83 | for _, d := range p.delegates { 84 | d.SyntaxError(recognizer, offendingSymbol, line, column, msg, e) 85 | } 86 | } 87 | 88 | func (p *ProxyErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) { 89 | for _, d := range p.delegates { 90 | d.ReportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) 91 | } 92 | } 93 | 94 | func (p *ProxyErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) { 95 | for _, d := range p.delegates { 96 | d.ReportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) 97 | } 98 | } 99 | 100 | func (p *ProxyErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) { 101 | for _, d := range p.delegates { 102 | d.ReportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/compress_notjs.go: -------------------------------------------------------------------------------- 1 | // +build !js 2 | 3 | package websocket 4 | 5 | import ( 6 | "io" 7 | "net/http" 8 | "sync" 9 | 10 | "github.com/klauspost/compress/flate" 11 | ) 12 | 13 | func (m CompressionMode) opts() *compressionOptions { 14 | return &compressionOptions{ 15 | clientNoContextTakeover: m == CompressionNoContextTakeover, 16 | serverNoContextTakeover: m == CompressionNoContextTakeover, 17 | } 18 | } 19 | 20 | type compressionOptions struct { 21 | clientNoContextTakeover bool 22 | serverNoContextTakeover bool 23 | } 24 | 25 | func (copts *compressionOptions) setHeader(h http.Header) { 26 | s := "permessage-deflate" 27 | if copts.clientNoContextTakeover { 28 | s += "; client_no_context_takeover" 29 | } 30 | if copts.serverNoContextTakeover { 31 | s += "; server_no_context_takeover" 32 | } 33 | h.Set("Sec-WebSocket-Extensions", s) 34 | } 35 | 36 | // These bytes are required to get flate.Reader to return. 37 | // They are removed when sending to avoid the overhead as 38 | // WebSocket framing tell's when the message has ended but then 39 | // we need to add them back otherwise flate.Reader keeps 40 | // trying to return more bytes. 41 | const deflateMessageTail = "\x00\x00\xff\xff" 42 | 43 | type trimLastFourBytesWriter struct { 44 | w io.Writer 45 | tail []byte 46 | } 47 | 48 | func (tw *trimLastFourBytesWriter) reset() { 49 | if tw != nil && tw.tail != nil { 50 | tw.tail = tw.tail[:0] 51 | } 52 | } 53 | 54 | func (tw *trimLastFourBytesWriter) Write(p []byte) (int, error) { 55 | if tw.tail == nil { 56 | tw.tail = make([]byte, 0, 4) 57 | } 58 | 59 | extra := len(tw.tail) + len(p) - 4 60 | 61 | if extra <= 0 { 62 | tw.tail = append(tw.tail, p...) 63 | return len(p), nil 64 | } 65 | 66 | // Now we need to write as many extra bytes as we can from the previous tail. 67 | if extra > len(tw.tail) { 68 | extra = len(tw.tail) 69 | } 70 | if extra > 0 { 71 | _, err := tw.w.Write(tw.tail[:extra]) 72 | if err != nil { 73 | return 0, err 74 | } 75 | 76 | // Shift remaining bytes in tail over. 77 | n := copy(tw.tail, tw.tail[extra:]) 78 | tw.tail = tw.tail[:n] 79 | } 80 | 81 | // If p is less than or equal to 4 bytes, 82 | // all of it is is part of the tail. 83 | if len(p) <= 4 { 84 | tw.tail = append(tw.tail, p...) 85 | return len(p), nil 86 | } 87 | 88 | // Otherwise, only the last 4 bytes are. 89 | tw.tail = append(tw.tail, p[len(p)-4:]...) 90 | 91 | p = p[:len(p)-4] 92 | n, err := tw.w.Write(p) 93 | return n + 4, err 94 | } 95 | 96 | var flateReaderPool sync.Pool 97 | 98 | func getFlateReader(r io.Reader, dict []byte) io.Reader { 99 | fr, ok := flateReaderPool.Get().(io.Reader) 100 | if !ok { 101 | return flate.NewReaderDict(r, dict) 102 | } 103 | fr.(flate.Resetter).Reset(r, dict) 104 | return fr 105 | } 106 | 107 | func putFlateReader(fr io.Reader) { 108 | flateReaderPool.Put(fr) 109 | } 110 | 111 | type slidingWindow struct { 112 | buf []byte 113 | } 114 | 115 | var swPoolMu sync.RWMutex 116 | var swPool = map[int]*sync.Pool{} 117 | 118 | func slidingWindowPool(n int) *sync.Pool { 119 | swPoolMu.RLock() 120 | p, ok := swPool[n] 121 | swPoolMu.RUnlock() 122 | if ok { 123 | return p 124 | } 125 | 126 | p = &sync.Pool{} 127 | 128 | swPoolMu.Lock() 129 | swPool[n] = p 130 | swPoolMu.Unlock() 131 | 132 | return p 133 | } 134 | 135 | func (sw *slidingWindow) init(n int) { 136 | if sw.buf != nil { 137 | return 138 | } 139 | 140 | if n == 0 { 141 | n = 32768 142 | } 143 | 144 | p := slidingWindowPool(n) 145 | buf, ok := p.Get().([]byte) 146 | if ok { 147 | sw.buf = buf[:0] 148 | } else { 149 | sw.buf = make([]byte, 0, n) 150 | } 151 | } 152 | 153 | func (sw *slidingWindow) close() { 154 | if sw.buf == nil { 155 | return 156 | } 157 | 158 | swPoolMu.Lock() 159 | swPool[cap(sw.buf)].Put(sw.buf) 160 | swPoolMu.Unlock() 161 | sw.buf = nil 162 | } 163 | 164 | func (sw *slidingWindow) write(p []byte) { 165 | if len(p) >= cap(sw.buf) { 166 | sw.buf = sw.buf[:cap(sw.buf)] 167 | p = p[len(p)-cap(sw.buf):] 168 | copy(sw.buf, p) 169 | return 170 | } 171 | 172 | left := cap(sw.buf) - len(sw.buf) 173 | if left < len(p) { 174 | // We need to shift spaceNeeded bytes from the end to make room for p at the end. 175 | spaceNeeded := len(p) - left 176 | copy(sw.buf, sw.buf[spaceNeeded:]) 177 | sw.buf = sw.buf[:len(sw.buf)-spaceNeeded] 178 | } 179 | 180 | sw.buf = append(sw.buf, p...) 181 | } 182 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/diagnostic_error_listener.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "strconv" 9 | ) 10 | 11 | // 12 | // This implementation of {@link ANTLRErrorListener} can be used to identify 13 | // certain potential correctness and performance problems in grammars. "reports" 14 | // are made by calling {@link Parser//NotifyErrorListeners} with the appropriate 15 | // message. 16 | // 17 | //
    18 | //
  • Ambiguities: These are cases where more than one path through the 19 | // grammar can Match the input.
  • 20 | //
  • Weak context sensitivity: These are cases where full-context 21 | // prediction resolved an SLL conflict to a unique alternative which equaled the 22 | // minimum alternative of the SLL conflict.
  • 23 | //
  • Strong (forced) context sensitivity: These are cases where the 24 | // full-context prediction resolved an SLL conflict to a unique alternative, 25 | // and the minimum alternative of the SLL conflict was found to not be 26 | // a truly viable alternative. Two-stage parsing cannot be used for inputs where 27 | // d situation occurs.
  • 28 | //
29 | 30 | type DiagnosticErrorListener struct { 31 | *DefaultErrorListener 32 | 33 | exactOnly bool 34 | } 35 | 36 | func NewDiagnosticErrorListener(exactOnly bool) *DiagnosticErrorListener { 37 | 38 | n := new(DiagnosticErrorListener) 39 | 40 | // whether all ambiguities or only exact ambiguities are Reported. 41 | n.exactOnly = exactOnly 42 | return n 43 | } 44 | 45 | func (d *DiagnosticErrorListener) ReportAmbiguity(recognizer Parser, dfa *DFA, startIndex, stopIndex int, exact bool, ambigAlts *BitSet, configs ATNConfigSet) { 46 | if d.exactOnly && !exact { 47 | return 48 | } 49 | msg := "reportAmbiguity d=" + 50 | d.getDecisionDescription(recognizer, dfa) + 51 | ": ambigAlts=" + 52 | d.getConflictingAlts(ambigAlts, configs).String() + 53 | ", input='" + 54 | recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'" 55 | recognizer.NotifyErrorListeners(msg, nil, nil) 56 | } 57 | 58 | func (d *DiagnosticErrorListener) ReportAttemptingFullContext(recognizer Parser, dfa *DFA, startIndex, stopIndex int, conflictingAlts *BitSet, configs ATNConfigSet) { 59 | 60 | msg := "reportAttemptingFullContext d=" + 61 | d.getDecisionDescription(recognizer, dfa) + 62 | ", input='" + 63 | recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'" 64 | recognizer.NotifyErrorListeners(msg, nil, nil) 65 | } 66 | 67 | func (d *DiagnosticErrorListener) ReportContextSensitivity(recognizer Parser, dfa *DFA, startIndex, stopIndex, prediction int, configs ATNConfigSet) { 68 | msg := "reportContextSensitivity d=" + 69 | d.getDecisionDescription(recognizer, dfa) + 70 | ", input='" + 71 | recognizer.GetTokenStream().GetTextFromInterval(NewInterval(startIndex, stopIndex)) + "'" 72 | recognizer.NotifyErrorListeners(msg, nil, nil) 73 | } 74 | 75 | func (d *DiagnosticErrorListener) getDecisionDescription(recognizer Parser, dfa *DFA) string { 76 | decision := dfa.decision 77 | ruleIndex := dfa.atnStartState.GetRuleIndex() 78 | 79 | ruleNames := recognizer.GetRuleNames() 80 | if ruleIndex < 0 || ruleIndex >= len(ruleNames) { 81 | return strconv.Itoa(decision) 82 | } 83 | ruleName := ruleNames[ruleIndex] 84 | if ruleName == "" { 85 | return strconv.Itoa(decision) 86 | } 87 | return strconv.Itoa(decision) + " (" + ruleName + ")" 88 | } 89 | 90 | // Computes the set of conflicting or ambiguous alternatives from a 91 | // configuration set, if that information was not already provided by the 92 | // parser. 93 | // 94 | // @param ReportedAlts The set of conflicting or ambiguous alternatives, as 95 | // Reported by the parser. 96 | // @param configs The conflicting or ambiguous configuration set. 97 | // @return Returns {@code ReportedAlts} if it is not {@code nil}, otherwise 98 | // returns the set of alternatives represented in {@code configs}. 99 | func (d *DiagnosticErrorListener) getConflictingAlts(ReportedAlts *BitSet, set ATNConfigSet) *BitSet { 100 | if ReportedAlts != nil { 101 | return ReportedAlts 102 | } 103 | result := NewBitSet() 104 | for _, c := range set.GetItems() { 105 | result.add(c.GetAlt()) 106 | } 107 | 108 | return result 109 | } 110 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/netconn.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "math" 8 | "net" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | // NetConn converts a *websocket.Conn into a net.Conn. 14 | // 15 | // It's for tunneling arbitrary protocols over WebSockets. 16 | // Few users of the library will need this but it's tricky to implement 17 | // correctly and so provided in the library. 18 | // See https://github.com/nhooyr/websocket/issues/100. 19 | // 20 | // Every Write to the net.Conn will correspond to a message write of 21 | // the given type on *websocket.Conn. 22 | // 23 | // The passed ctx bounds the lifetime of the net.Conn. If cancelled, 24 | // all reads and writes on the net.Conn will be cancelled. 25 | // 26 | // If a message is read that is not of the correct type, the connection 27 | // will be closed with StatusUnsupportedData and an error will be returned. 28 | // 29 | // Close will close the *websocket.Conn with StatusNormalClosure. 30 | // 31 | // When a deadline is hit, the connection will be closed. This is 32 | // different from most net.Conn implementations where only the 33 | // reading/writing goroutines are interrupted but the connection is kept alive. 34 | // 35 | // The Addr methods will return a mock net.Addr that returns "websocket" for Network 36 | // and "websocket/unknown-addr" for String. 37 | // 38 | // A received StatusNormalClosure or StatusGoingAway close frame will be translated to 39 | // io.EOF when reading. 40 | func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn { 41 | nc := &netConn{ 42 | c: c, 43 | msgType: msgType, 44 | } 45 | 46 | var cancel context.CancelFunc 47 | nc.writeContext, cancel = context.WithCancel(ctx) 48 | nc.writeTimer = time.AfterFunc(math.MaxInt64, cancel) 49 | if !nc.writeTimer.Stop() { 50 | <-nc.writeTimer.C 51 | } 52 | 53 | nc.readContext, cancel = context.WithCancel(ctx) 54 | nc.readTimer = time.AfterFunc(math.MaxInt64, cancel) 55 | if !nc.readTimer.Stop() { 56 | <-nc.readTimer.C 57 | } 58 | 59 | return nc 60 | } 61 | 62 | type netConn struct { 63 | c *Conn 64 | msgType MessageType 65 | 66 | writeTimer *time.Timer 67 | writeContext context.Context 68 | 69 | readTimer *time.Timer 70 | readContext context.Context 71 | 72 | readMu sync.Mutex 73 | eofed bool 74 | reader io.Reader 75 | } 76 | 77 | var _ net.Conn = &netConn{} 78 | 79 | func (c *netConn) Close() error { 80 | return c.c.Close(StatusNormalClosure, "") 81 | } 82 | 83 | func (c *netConn) Write(p []byte) (int, error) { 84 | err := c.c.Write(c.writeContext, c.msgType, p) 85 | if err != nil { 86 | return 0, err 87 | } 88 | return len(p), nil 89 | } 90 | 91 | func (c *netConn) Read(p []byte) (int, error) { 92 | c.readMu.Lock() 93 | defer c.readMu.Unlock() 94 | 95 | if c.eofed { 96 | return 0, io.EOF 97 | } 98 | 99 | if c.reader == nil { 100 | typ, r, err := c.c.Reader(c.readContext) 101 | if err != nil { 102 | switch CloseStatus(err) { 103 | case StatusNormalClosure, StatusGoingAway: 104 | c.eofed = true 105 | return 0, io.EOF 106 | } 107 | return 0, err 108 | } 109 | if typ != c.msgType { 110 | err := fmt.Errorf("unexpected frame type read (expected %v): %v", c.msgType, typ) 111 | c.c.Close(StatusUnsupportedData, err.Error()) 112 | return 0, err 113 | } 114 | c.reader = r 115 | } 116 | 117 | n, err := c.reader.Read(p) 118 | if err == io.EOF { 119 | c.reader = nil 120 | err = nil 121 | } 122 | return n, err 123 | } 124 | 125 | type websocketAddr struct { 126 | } 127 | 128 | func (a websocketAddr) Network() string { 129 | return "websocket" 130 | } 131 | 132 | func (a websocketAddr) String() string { 133 | return "websocket/unknown-addr" 134 | } 135 | 136 | func (c *netConn) RemoteAddr() net.Addr { 137 | return websocketAddr{} 138 | } 139 | 140 | func (c *netConn) LocalAddr() net.Addr { 141 | return websocketAddr{} 142 | } 143 | 144 | func (c *netConn) SetDeadline(t time.Time) error { 145 | c.SetWriteDeadline(t) 146 | c.SetReadDeadline(t) 147 | return nil 148 | } 149 | 150 | func (c *netConn) SetWriteDeadline(t time.Time) error { 151 | if t.IsZero() { 152 | c.writeTimer.Stop() 153 | } else { 154 | c.writeTimer.Reset(t.Sub(time.Now())) 155 | } 156 | return nil 157 | } 158 | 159 | func (c *netConn) SetReadDeadline(t time.Time) error { 160 | if t.IsZero() { 161 | c.readTimer.Stop() 162 | } else { 163 | c.readTimer.Reset(t.Sub(time.Now())) 164 | } 165 | return nil 166 | } 167 | -------------------------------------------------------------------------------- /vendor/golang.org/x/exp/slices/sort.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package slices 6 | 7 | import ( 8 | "math/bits" 9 | 10 | "golang.org/x/exp/constraints" 11 | ) 12 | 13 | // Sort sorts a slice of any ordered type in ascending order. 14 | // Sort may fail to sort correctly when sorting slices of floating-point 15 | // numbers containing Not-a-number (NaN) values. 16 | // Use slices.SortFunc(x, func(a, b float64) bool {return a < b || (math.IsNaN(a) && !math.IsNaN(b))}) 17 | // instead if the input may contain NaNs. 18 | func Sort[E constraints.Ordered](x []E) { 19 | n := len(x) 20 | pdqsortOrdered(x, 0, n, bits.Len(uint(n))) 21 | } 22 | 23 | // SortFunc sorts the slice x in ascending order as determined by the less function. 24 | // This sort is not guaranteed to be stable. 25 | // 26 | // SortFunc requires that less is a strict weak ordering. 27 | // See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings. 28 | func SortFunc[E any](x []E, less func(a, b E) bool) { 29 | n := len(x) 30 | pdqsortLessFunc(x, 0, n, bits.Len(uint(n)), less) 31 | } 32 | 33 | // SortStable sorts the slice x while keeping the original order of equal 34 | // elements, using less to compare elements. 35 | func SortStableFunc[E any](x []E, less func(a, b E) bool) { 36 | stableLessFunc(x, len(x), less) 37 | } 38 | 39 | // IsSorted reports whether x is sorted in ascending order. 40 | func IsSorted[E constraints.Ordered](x []E) bool { 41 | for i := len(x) - 1; i > 0; i-- { 42 | if x[i] < x[i-1] { 43 | return false 44 | } 45 | } 46 | return true 47 | } 48 | 49 | // IsSortedFunc reports whether x is sorted in ascending order, with less as the 50 | // comparison function. 51 | func IsSortedFunc[E any](x []E, less func(a, b E) bool) bool { 52 | for i := len(x) - 1; i > 0; i-- { 53 | if less(x[i], x[i-1]) { 54 | return false 55 | } 56 | } 57 | return true 58 | } 59 | 60 | // BinarySearch searches for target in a sorted slice and returns the position 61 | // where target is found, or the position where target would appear in the 62 | // sort order; it also returns a bool saying whether the target is really found 63 | // in the slice. The slice must be sorted in increasing order. 64 | func BinarySearch[E constraints.Ordered](x []E, target E) (int, bool) { 65 | // search returns the leftmost position where f returns true, or len(x) if f 66 | // returns false for all x. This is the insertion position for target in x, 67 | // and could point to an element that's either == target or not. 68 | pos := search(len(x), func(i int) bool { return x[i] >= target }) 69 | if pos >= len(x) || x[pos] != target { 70 | return pos, false 71 | } else { 72 | return pos, true 73 | } 74 | } 75 | 76 | // BinarySearchFunc works like BinarySearch, but uses a custom comparison 77 | // function. The slice must be sorted in increasing order, where "increasing" is 78 | // defined by cmp. cmp(a, b) is expected to return an integer comparing the two 79 | // parameters: 0 if a == b, a negative number if a < b and a positive number if 80 | // a > b. 81 | func BinarySearchFunc[E any](x []E, target E, cmp func(E, E) int) (int, bool) { 82 | pos := search(len(x), func(i int) bool { return cmp(x[i], target) >= 0 }) 83 | if pos >= len(x) || cmp(x[pos], target) != 0 { 84 | return pos, false 85 | } else { 86 | return pos, true 87 | } 88 | } 89 | 90 | func search(n int, f func(int) bool) int { 91 | // Define f(-1) == false and f(n) == true. 92 | // Invariant: f(i-1) == false, f(j) == true. 93 | i, j := 0, n 94 | for i < j { 95 | h := int(uint(i+j) >> 1) // avoid overflow when computing h 96 | // i ≤ h < j 97 | if !f(h) { 98 | i = h + 1 // preserves f(i-1) == false 99 | } else { 100 | j = h // preserves f(j) == true 101 | } 102 | } 103 | // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. 104 | return i 105 | } 106 | 107 | type sortedHint int // hint for pdqsort when choosing the pivot 108 | 109 | const ( 110 | unknownHint sortedHint = iota 111 | increasingHint 112 | decreasingHint 113 | ) 114 | 115 | // xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf 116 | type xorshift uint64 117 | 118 | func (r *xorshift) Next() uint64 { 119 | *r ^= *r << 13 120 | *r ^= *r >> 17 121 | *r ^= *r << 5 122 | return uint64(*r) 123 | } 124 | 125 | func nextPowerOfTwo(length int) uint { 126 | return 1 << bits.Len(uint(length)) 127 | } 128 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/internal/wsjs/wsjs_js.go: -------------------------------------------------------------------------------- 1 | // +build js 2 | 3 | // Package wsjs implements typed access to the browser javascript WebSocket API. 4 | // 5 | // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket 6 | package wsjs 7 | 8 | import ( 9 | "syscall/js" 10 | ) 11 | 12 | func handleJSError(err *error, onErr func()) { 13 | r := recover() 14 | 15 | if jsErr, ok := r.(js.Error); ok { 16 | *err = jsErr 17 | 18 | if onErr != nil { 19 | onErr() 20 | } 21 | return 22 | } 23 | 24 | if r != nil { 25 | panic(r) 26 | } 27 | } 28 | 29 | // New is a wrapper around the javascript WebSocket constructor. 30 | func New(url string, protocols []string) (c WebSocket, err error) { 31 | defer handleJSError(&err, func() { 32 | c = WebSocket{} 33 | }) 34 | 35 | jsProtocols := make([]interface{}, len(protocols)) 36 | for i, p := range protocols { 37 | jsProtocols[i] = p 38 | } 39 | 40 | c = WebSocket{ 41 | v: js.Global().Get("WebSocket").New(url, jsProtocols), 42 | } 43 | 44 | c.setBinaryType("arraybuffer") 45 | 46 | return c, nil 47 | } 48 | 49 | // WebSocket is a wrapper around a javascript WebSocket object. 50 | type WebSocket struct { 51 | v js.Value 52 | } 53 | 54 | func (c WebSocket) setBinaryType(typ string) { 55 | c.v.Set("binaryType", string(typ)) 56 | } 57 | 58 | func (c WebSocket) addEventListener(eventType string, fn func(e js.Value)) func() { 59 | f := js.FuncOf(func(this js.Value, args []js.Value) interface{} { 60 | fn(args[0]) 61 | return nil 62 | }) 63 | c.v.Call("addEventListener", eventType, f) 64 | 65 | return func() { 66 | c.v.Call("removeEventListener", eventType, f) 67 | f.Release() 68 | } 69 | } 70 | 71 | // CloseEvent is the type passed to a WebSocket close handler. 72 | type CloseEvent struct { 73 | Code uint16 74 | Reason string 75 | WasClean bool 76 | } 77 | 78 | // OnClose registers a function to be called when the WebSocket is closed. 79 | func (c WebSocket) OnClose(fn func(CloseEvent)) (remove func()) { 80 | return c.addEventListener("close", func(e js.Value) { 81 | ce := CloseEvent{ 82 | Code: uint16(e.Get("code").Int()), 83 | Reason: e.Get("reason").String(), 84 | WasClean: e.Get("wasClean").Bool(), 85 | } 86 | fn(ce) 87 | }) 88 | } 89 | 90 | // OnError registers a function to be called when there is an error 91 | // with the WebSocket. 92 | func (c WebSocket) OnError(fn func(e js.Value)) (remove func()) { 93 | return c.addEventListener("error", fn) 94 | } 95 | 96 | // MessageEvent is the type passed to a message handler. 97 | type MessageEvent struct { 98 | // string or []byte. 99 | Data interface{} 100 | 101 | // There are more fields to the interface but we don't use them. 102 | // See https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent 103 | } 104 | 105 | // OnMessage registers a function to be called when the WebSocket receives a message. 106 | func (c WebSocket) OnMessage(fn func(m MessageEvent)) (remove func()) { 107 | return c.addEventListener("message", func(e js.Value) { 108 | var data interface{} 109 | 110 | arrayBuffer := e.Get("data") 111 | if arrayBuffer.Type() == js.TypeString { 112 | data = arrayBuffer.String() 113 | } else { 114 | data = extractArrayBuffer(arrayBuffer) 115 | } 116 | 117 | me := MessageEvent{ 118 | Data: data, 119 | } 120 | fn(me) 121 | 122 | return 123 | }) 124 | } 125 | 126 | // Subprotocol returns the WebSocket subprotocol in use. 127 | func (c WebSocket) Subprotocol() string { 128 | return c.v.Get("protocol").String() 129 | } 130 | 131 | // OnOpen registers a function to be called when the WebSocket is opened. 132 | func (c WebSocket) OnOpen(fn func(e js.Value)) (remove func()) { 133 | return c.addEventListener("open", fn) 134 | } 135 | 136 | // Close closes the WebSocket with the given code and reason. 137 | func (c WebSocket) Close(code int, reason string) (err error) { 138 | defer handleJSError(&err, nil) 139 | c.v.Call("close", code, reason) 140 | return err 141 | } 142 | 143 | // SendText sends the given string as a text message 144 | // on the WebSocket. 145 | func (c WebSocket) SendText(v string) (err error) { 146 | defer handleJSError(&err, nil) 147 | c.v.Call("send", v) 148 | return err 149 | } 150 | 151 | // SendBytes sends the given message as a binary message 152 | // on the WebSocket. 153 | func (c WebSocket) SendBytes(v []byte) (err error) { 154 | defer handleJSError(&err, nil) 155 | c.v.Call("send", uint8Array(v)) 156 | return err 157 | } 158 | 159 | func extractArrayBuffer(arrayBuffer js.Value) []byte { 160 | uint8Array := js.Global().Get("Uint8Array").New(arrayBuffer) 161 | dst := make([]byte, uint8Array.Length()) 162 | js.CopyBytesToGo(dst, uint8Array) 163 | return dst 164 | } 165 | 166 | func uint8Array(src []byte) js.Value { 167 | uint8Array := js.Global().Get("Uint8Array").New(len(src)) 168 | js.CopyBytesToJS(uint8Array, src) 169 | return uint8Array 170 | } 171 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/dfa.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | type DFA struct { 8 | // atnStartState is the ATN state in which this was created 9 | atnStartState DecisionState 10 | 11 | decision int 12 | 13 | // states is all the DFA states. Use Map to get the old state back; Set can only 14 | // indicate whether it is there. Go maps implement key hash collisions and so on and are very 15 | // good, but the DFAState is an object and can't be used directly as the key as it can in say JAva 16 | // amd C#, whereby if the hashcode is the same for two objects, then Equals() is called against them 17 | // to see if they really are the same object. 18 | // 19 | // 20 | states *JStore[*DFAState, *ObjEqComparator[*DFAState]] 21 | 22 | numstates int 23 | 24 | s0 *DFAState 25 | 26 | // precedenceDfa is the backing field for isPrecedenceDfa and setPrecedenceDfa. 27 | // True if the DFA is for a precedence decision and false otherwise. 28 | precedenceDfa bool 29 | } 30 | 31 | func NewDFA(atnStartState DecisionState, decision int) *DFA { 32 | dfa := &DFA{ 33 | atnStartState: atnStartState, 34 | decision: decision, 35 | states: NewJStore[*DFAState, *ObjEqComparator[*DFAState]](dfaStateEqInst), 36 | } 37 | if s, ok := atnStartState.(*StarLoopEntryState); ok && s.precedenceRuleDecision { 38 | dfa.precedenceDfa = true 39 | dfa.s0 = NewDFAState(-1, NewBaseATNConfigSet(false)) 40 | dfa.s0.isAcceptState = false 41 | dfa.s0.requiresFullContext = false 42 | } 43 | return dfa 44 | } 45 | 46 | // getPrecedenceStartState gets the start state for the current precedence and 47 | // returns the start state corresponding to the specified precedence if a start 48 | // state exists for the specified precedence and nil otherwise. d must be a 49 | // precedence DFA. See also isPrecedenceDfa. 50 | func (d *DFA) getPrecedenceStartState(precedence int) *DFAState { 51 | if !d.getPrecedenceDfa() { 52 | panic("only precedence DFAs may contain a precedence start state") 53 | } 54 | 55 | // s0.edges is never nil for a precedence DFA 56 | if precedence < 0 || precedence >= len(d.getS0().getEdges()) { 57 | return nil 58 | } 59 | 60 | return d.getS0().getIthEdge(precedence) 61 | } 62 | 63 | // setPrecedenceStartState sets the start state for the current precedence. d 64 | // must be a precedence DFA. See also isPrecedenceDfa. 65 | func (d *DFA) setPrecedenceStartState(precedence int, startState *DFAState) { 66 | if !d.getPrecedenceDfa() { 67 | panic("only precedence DFAs may contain a precedence start state") 68 | } 69 | 70 | if precedence < 0 { 71 | return 72 | } 73 | 74 | // Synchronization on s0 here is ok. When the DFA is turned into a 75 | // precedence DFA, s0 will be initialized once and not updated again. s0.edges 76 | // is never nil for a precedence DFA. 77 | s0 := d.getS0() 78 | if precedence >= s0.numEdges() { 79 | edges := append(s0.getEdges(), make([]*DFAState, precedence+1-s0.numEdges())...) 80 | s0.setEdges(edges) 81 | d.setS0(s0) 82 | } 83 | 84 | s0.setIthEdge(precedence, startState) 85 | } 86 | 87 | func (d *DFA) getPrecedenceDfa() bool { 88 | return d.precedenceDfa 89 | } 90 | 91 | // setPrecedenceDfa sets whether d is a precedence DFA. If precedenceDfa differs 92 | // from the current DFA configuration, then d.states is cleared, the initial 93 | // state s0 is set to a new DFAState with an empty outgoing DFAState.edges to 94 | // store the start states for individual precedence values if precedenceDfa is 95 | // true or nil otherwise, and d.precedenceDfa is updated. 96 | func (d *DFA) setPrecedenceDfa(precedenceDfa bool) { 97 | if d.getPrecedenceDfa() != precedenceDfa { 98 | d.states = NewJStore[*DFAState, *ObjEqComparator[*DFAState]](dfaStateEqInst) 99 | d.numstates = 0 100 | 101 | if precedenceDfa { 102 | precedenceState := NewDFAState(-1, NewBaseATNConfigSet(false)) 103 | 104 | precedenceState.setEdges(make([]*DFAState, 0)) 105 | precedenceState.isAcceptState = false 106 | precedenceState.requiresFullContext = false 107 | d.setS0(precedenceState) 108 | } else { 109 | d.setS0(nil) 110 | } 111 | 112 | d.precedenceDfa = precedenceDfa 113 | } 114 | } 115 | 116 | func (d *DFA) getS0() *DFAState { 117 | return d.s0 118 | } 119 | 120 | func (d *DFA) setS0(s *DFAState) { 121 | d.s0 = s 122 | } 123 | 124 | // sortedStates returns the states in d sorted by their state number. 125 | func (d *DFA) sortedStates() []*DFAState { 126 | 127 | vs := d.states.SortedSlice(func(i, j *DFAState) bool { 128 | return i.stateNumber < j.stateNumber 129 | }) 130 | 131 | return vs 132 | } 133 | 134 | func (d *DFA) String(literalNames []string, symbolicNames []string) string { 135 | if d.getS0() == nil { 136 | return "" 137 | } 138 | 139 | return NewDFASerializer(d, literalNames, symbolicNames).String() 140 | } 141 | 142 | func (d *DFA) ToLexerString() string { 143 | if d.getS0() == nil { 144 | return "" 145 | } 146 | 147 | return NewLexerDFASerializer(d).String() 148 | } 149 | -------------------------------------------------------------------------------- /vendor/github.com/tursodatabase/libsql-client-go/libsql/internal/ws/driver.go: -------------------------------------------------------------------------------- 1 | package ws 2 | 3 | import ( 4 | "context" 5 | "database/sql/driver" 6 | "io" 7 | "sort" 8 | ) 9 | 10 | type result struct { 11 | id int64 12 | changes int64 13 | } 14 | 15 | func (r *result) LastInsertId() (int64, error) { 16 | return r.id, nil 17 | } 18 | 19 | func (r *result) RowsAffected() (int64, error) { 20 | return r.changes, nil 21 | } 22 | 23 | type rows struct { 24 | res *execResponse 25 | currentRowIdx int 26 | } 27 | 28 | func (r *rows) Columns() []string { 29 | return r.res.columns() 30 | } 31 | 32 | func (r *rows) Close() error { 33 | return nil 34 | } 35 | 36 | func (r *rows) Next(dest []driver.Value) error { 37 | if r.currentRowIdx == r.res.rowsCount() { 38 | return io.EOF 39 | } 40 | count := r.res.rowLen(r.currentRowIdx) 41 | for idx := 0; idx < count; idx++ { 42 | v, err := r.res.value(r.currentRowIdx, idx) 43 | if err != nil { 44 | return err 45 | } 46 | dest[idx] = v 47 | } 48 | r.currentRowIdx++ 49 | return nil 50 | } 51 | 52 | type conn struct { 53 | ws *websocketConn 54 | } 55 | 56 | func Connect(url string, jwt string) (*conn, error) { 57 | c, err := connect(url, jwt) 58 | if err != nil { 59 | return nil, err 60 | } 61 | return &conn{c}, nil 62 | } 63 | 64 | type stmt struct { 65 | c *conn 66 | query string 67 | } 68 | 69 | func (s stmt) Close() error { 70 | return nil 71 | } 72 | 73 | func (s stmt) NumInput() int { 74 | return -1 75 | } 76 | 77 | func convertToNamed(args []driver.Value) []driver.NamedValue { 78 | if len(args) == 0 { 79 | return nil 80 | } 81 | result := []driver.NamedValue{} 82 | for idx := range args { 83 | result = append(result, driver.NamedValue{Ordinal: idx, Value: args[idx]}) 84 | } 85 | return result 86 | } 87 | 88 | func (s stmt) Exec(args []driver.Value) (driver.Result, error) { 89 | return s.ExecContext(context.Background(), convertToNamed(args)) 90 | } 91 | 92 | func (s stmt) Query(args []driver.Value) (driver.Rows, error) { 93 | return s.QueryContext(context.Background(), convertToNamed(args)) 94 | } 95 | 96 | func (s stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { 97 | return s.c.ExecContext(ctx, s.query, args) 98 | } 99 | 100 | func (s stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { 101 | return s.c.QueryContext(ctx, s.query, args) 102 | } 103 | 104 | func (c *conn) Ping() error { 105 | return c.PingContext(context.Background()) 106 | } 107 | 108 | func (c *conn) PingContext(ctx context.Context) error { 109 | _, err := c.ws.exec(ctx, "SELECT 1", params{}, false) 110 | return err 111 | } 112 | 113 | func (c *conn) Prepare(query string) (driver.Stmt, error) { 114 | return c.PrepareContext(context.Background(), query) 115 | } 116 | 117 | func (c *conn) PrepareContext(_ context.Context, query string) (driver.Stmt, error) { 118 | return stmt{c, query}, nil 119 | } 120 | 121 | func (c *conn) Close() error { 122 | return c.ws.Close() 123 | } 124 | 125 | type tx struct { 126 | c *conn 127 | } 128 | 129 | func (t tx) Commit() error { 130 | _, err := t.c.ExecContext(context.Background(), "COMMIT", nil) 131 | if err != nil { 132 | return err 133 | } 134 | return nil 135 | } 136 | 137 | func (t tx) Rollback() error { 138 | _, err := t.c.ExecContext(context.Background(), "ROLLBACK", nil) 139 | if err != nil { 140 | return err 141 | } 142 | return nil 143 | } 144 | 145 | func (c *conn) Begin() (driver.Tx, error) { 146 | return c.BeginTx(context.Background(), driver.TxOptions{}) 147 | } 148 | 149 | func (c *conn) BeginTx(ctx context.Context, _ driver.TxOptions) (driver.Tx, error) { 150 | _, err := c.ExecContext(ctx, "BEGIN", nil) 151 | if err != nil { 152 | return tx{nil}, err 153 | } 154 | return tx{c}, nil 155 | } 156 | 157 | func convertArgs(args []driver.NamedValue) params { 158 | if len(args) == 0 { 159 | return params{} 160 | } 161 | positionalArgs := [](*driver.NamedValue){} 162 | namedArgs := []namedParam{} 163 | for idx := range args { 164 | if len(args[idx].Name) > 0 { 165 | namedArgs = append(namedArgs, namedParam{args[idx].Name, args[idx].Value}) 166 | } else { 167 | positionalArgs = append(positionalArgs, &args[idx]) 168 | } 169 | } 170 | sort.Slice(positionalArgs, func(i, j int) bool { 171 | return positionalArgs[i].Ordinal < positionalArgs[j].Ordinal 172 | }) 173 | posArgs := [](any){} 174 | for idx := range positionalArgs { 175 | posArgs = append(posArgs, positionalArgs[idx].Value) 176 | } 177 | return params{PositinalArgs: posArgs, NamedArgs: namedArgs} 178 | } 179 | 180 | func (c *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { 181 | res, err := c.ws.exec(ctx, query, convertArgs(args), false) 182 | if err != nil { 183 | return nil, err 184 | } 185 | return &result{res.lastInsertId(), res.affectedRowCount()}, nil 186 | } 187 | 188 | func (c *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { 189 | res, err := c.ws.exec(ctx, query, convertArgs(args), true) 190 | if err != nil { 191 | return nil, err 192 | } 193 | return &rows{res, 0}, nil 194 | } 195 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/chi.go: -------------------------------------------------------------------------------- 1 | // 2 | // Package chi is a small, idiomatic and composable router for building HTTP services. 3 | // 4 | // chi requires Go 1.10 or newer. 5 | // 6 | // Example: 7 | // package main 8 | // 9 | // import ( 10 | // "net/http" 11 | // 12 | // "github.com/go-chi/chi" 13 | // "github.com/go-chi/chi/middleware" 14 | // ) 15 | // 16 | // func main() { 17 | // r := chi.NewRouter() 18 | // r.Use(middleware.Logger) 19 | // r.Use(middleware.Recoverer) 20 | // 21 | // r.Get("/", func(w http.ResponseWriter, r *http.Request) { 22 | // w.Write([]byte("root.")) 23 | // }) 24 | // 25 | // http.ListenAndServe(":3333", r) 26 | // } 27 | // 28 | // See github.com/go-chi/chi/_examples/ for more in-depth examples. 29 | // 30 | // URL patterns allow for easy matching of path components in HTTP 31 | // requests. The matching components can then be accessed using 32 | // chi.URLParam(). All patterns must begin with a slash. 33 | // 34 | // A simple named placeholder {name} matches any sequence of characters 35 | // up to the next / or the end of the URL. Trailing slashes on paths must 36 | // be handled explicitly. 37 | // 38 | // A placeholder with a name followed by a colon allows a regular 39 | // expression match, for example {number:\\d+}. The regular expression 40 | // syntax is Go's normal regexp RE2 syntax, except that regular expressions 41 | // including { or } are not supported, and / will never be 42 | // matched. An anonymous regexp pattern is allowed, using an empty string 43 | // before the colon in the placeholder, such as {:\\d+} 44 | // 45 | // The special placeholder of asterisk matches the rest of the requested 46 | // URL. Any trailing characters in the pattern are ignored. This is the only 47 | // placeholder which will match / characters. 48 | // 49 | // Examples: 50 | // "/user/{name}" matches "/user/jsmith" but not "/user/jsmith/info" or "/user/jsmith/" 51 | // "/user/{name}/info" matches "/user/jsmith/info" 52 | // "/page/*" matches "/page/intro/latest" 53 | // "/page/*/index" also matches "/page/intro/latest" 54 | // "/date/{yyyy:\\d\\d\\d\\d}/{mm:\\d\\d}/{dd:\\d\\d}" matches "/date/2017/04/01" 55 | // 56 | package chi 57 | 58 | import "net/http" 59 | 60 | // NewRouter returns a new Mux object that implements the Router interface. 61 | func NewRouter() *Mux { 62 | return NewMux() 63 | } 64 | 65 | // Router consisting of the core routing methods used by chi's Mux, 66 | // using only the standard net/http. 67 | type Router interface { 68 | http.Handler 69 | Routes 70 | 71 | // Use appends one or more middlewares onto the Router stack. 72 | Use(middlewares ...func(http.Handler) http.Handler) 73 | 74 | // With adds inline middlewares for an endpoint handler. 75 | With(middlewares ...func(http.Handler) http.Handler) Router 76 | 77 | // Group adds a new inline-Router along the current routing 78 | // path, with a fresh middleware stack for the inline-Router. 79 | Group(fn func(r Router)) Router 80 | 81 | // Route mounts a sub-Router along a `pattern`` string. 82 | Route(pattern string, fn func(r Router)) Router 83 | 84 | // Mount attaches another http.Handler along ./pattern/* 85 | Mount(pattern string, h http.Handler) 86 | 87 | // Handle and HandleFunc adds routes for `pattern` that matches 88 | // all HTTP methods. 89 | Handle(pattern string, h http.Handler) 90 | HandleFunc(pattern string, h http.HandlerFunc) 91 | 92 | // Method and MethodFunc adds routes for `pattern` that matches 93 | // the `method` HTTP method. 94 | Method(method, pattern string, h http.Handler) 95 | MethodFunc(method, pattern string, h http.HandlerFunc) 96 | 97 | // HTTP-method routing along `pattern` 98 | Connect(pattern string, h http.HandlerFunc) 99 | Delete(pattern string, h http.HandlerFunc) 100 | Get(pattern string, h http.HandlerFunc) 101 | Head(pattern string, h http.HandlerFunc) 102 | Options(pattern string, h http.HandlerFunc) 103 | Patch(pattern string, h http.HandlerFunc) 104 | Post(pattern string, h http.HandlerFunc) 105 | Put(pattern string, h http.HandlerFunc) 106 | Trace(pattern string, h http.HandlerFunc) 107 | 108 | // NotFound defines a handler to respond whenever a route could 109 | // not be found. 110 | NotFound(h http.HandlerFunc) 111 | 112 | // MethodNotAllowed defines a handler to respond whenever a method is 113 | // not allowed. 114 | MethodNotAllowed(h http.HandlerFunc) 115 | } 116 | 117 | // Routes interface adds two methods for router traversal, which is also 118 | // used by the `docgen` subpackage to generation documentation for Routers. 119 | type Routes interface { 120 | // Routes returns the routing tree in an easily traversable structure. 121 | Routes() []Route 122 | 123 | // Middlewares returns the list of middlewares in use by the router. 124 | Middlewares() Middlewares 125 | 126 | // Match searches the routing tree for a handler that matches 127 | // the method/path - similar to routing a http request, but without 128 | // executing the handler thereafter. 129 | Match(rctx *Context, method, path string) bool 130 | } 131 | 132 | // Middlewares type is a slice of standard middleware handlers with methods 133 | // to compose middleware chains and http.Handler's. 134 | type Middlewares []func(http.Handler) http.Handler 135 | -------------------------------------------------------------------------------- /vendor/github.com/go-chi/chi/context.go: -------------------------------------------------------------------------------- 1 | package chi 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | // URLParam returns the url parameter from a http.Request object. 10 | func URLParam(r *http.Request, key string) string { 11 | if rctx := RouteContext(r.Context()); rctx != nil { 12 | return rctx.URLParam(key) 13 | } 14 | return "" 15 | } 16 | 17 | // URLParamFromCtx returns the url parameter from a http.Request Context. 18 | func URLParamFromCtx(ctx context.Context, key string) string { 19 | if rctx := RouteContext(ctx); rctx != nil { 20 | return rctx.URLParam(key) 21 | } 22 | return "" 23 | } 24 | 25 | // RouteContext returns chi's routing Context object from a 26 | // http.Request Context. 27 | func RouteContext(ctx context.Context) *Context { 28 | val, _ := ctx.Value(RouteCtxKey).(*Context) 29 | return val 30 | } 31 | 32 | // NewRouteContext returns a new routing Context object. 33 | func NewRouteContext() *Context { 34 | return &Context{} 35 | } 36 | 37 | var ( 38 | // RouteCtxKey is the context.Context key to store the request context. 39 | RouteCtxKey = &contextKey{"RouteContext"} 40 | ) 41 | 42 | // Context is the default routing context set on the root node of a 43 | // request context to track route patterns, URL parameters and 44 | // an optional routing path. 45 | type Context struct { 46 | Routes Routes 47 | 48 | // Routing path/method override used during the route search. 49 | // See Mux#routeHTTP method. 50 | RoutePath string 51 | RouteMethod string 52 | 53 | // Routing pattern stack throughout the lifecycle of the request, 54 | // across all connected routers. It is a record of all matching 55 | // patterns across a stack of sub-routers. 56 | RoutePatterns []string 57 | 58 | // URLParams are the stack of routeParams captured during the 59 | // routing lifecycle across a stack of sub-routers. 60 | URLParams RouteParams 61 | 62 | // The endpoint routing pattern that matched the request URI path 63 | // or `RoutePath` of the current sub-router. This value will update 64 | // during the lifecycle of a request passing through a stack of 65 | // sub-routers. 66 | routePattern string 67 | 68 | // Route parameters matched for the current sub-router. It is 69 | // intentionally unexported so it cant be tampered. 70 | routeParams RouteParams 71 | 72 | // methodNotAllowed hint 73 | methodNotAllowed bool 74 | 75 | // parentCtx is the parent of this one, for using Context as a 76 | // context.Context directly. This is an optimization that saves 77 | // 1 allocation. 78 | parentCtx context.Context 79 | } 80 | 81 | // Reset a routing context to its initial state. 82 | func (x *Context) Reset() { 83 | x.Routes = nil 84 | x.RoutePath = "" 85 | x.RouteMethod = "" 86 | x.RoutePatterns = x.RoutePatterns[:0] 87 | x.URLParams.Keys = x.URLParams.Keys[:0] 88 | x.URLParams.Values = x.URLParams.Values[:0] 89 | 90 | x.routePattern = "" 91 | x.routeParams.Keys = x.routeParams.Keys[:0] 92 | x.routeParams.Values = x.routeParams.Values[:0] 93 | x.methodNotAllowed = false 94 | x.parentCtx = nil 95 | } 96 | 97 | // URLParam returns the corresponding URL parameter value from the request 98 | // routing context. 99 | func (x *Context) URLParam(key string) string { 100 | for k := len(x.URLParams.Keys) - 1; k >= 0; k-- { 101 | if x.URLParams.Keys[k] == key { 102 | return x.URLParams.Values[k] 103 | } 104 | } 105 | return "" 106 | } 107 | 108 | // RoutePattern builds the routing pattern string for the particular 109 | // request, at the particular point during routing. This means, the value 110 | // will change throughout the execution of a request in a router. That is 111 | // why its advised to only use this value after calling the next handler. 112 | // 113 | // For example, 114 | // 115 | // func Instrument(next http.Handler) http.Handler { 116 | // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 117 | // next.ServeHTTP(w, r) 118 | // routePattern := chi.RouteContext(r.Context()).RoutePattern() 119 | // measure(w, r, routePattern) 120 | // }) 121 | // } 122 | func (x *Context) RoutePattern() string { 123 | routePattern := strings.Join(x.RoutePatterns, "") 124 | return replaceWildcards(routePattern) 125 | } 126 | 127 | // replaceWildcards takes a route pattern and recursively replaces all 128 | // occurrences of "/*/" to "/". 129 | func replaceWildcards(p string) string { 130 | if strings.Contains(p, "/*/") { 131 | return replaceWildcards(strings.Replace(p, "/*/", "/", -1)) 132 | } 133 | 134 | return p 135 | } 136 | 137 | // RouteParams is a structure to track URL routing parameters efficiently. 138 | type RouteParams struct { 139 | Keys, Values []string 140 | } 141 | 142 | // Add will append a URL parameter to the end of the route param 143 | func (s *RouteParams) Add(key, value string) { 144 | s.Keys = append(s.Keys, key) 145 | s.Values = append(s.Values, value) 146 | } 147 | 148 | // contextKey is a value for use with context.WithValue. It's used as 149 | // a pointer so it fits in an interface{} without allocation. This technique 150 | // for defining context keys was copied from Go 1.7's new use of context in net/http. 151 | type contextKey struct { 152 | name string 153 | } 154 | 155 | func (k *contextKey) String() string { 156 | return "chi context value " + k.name 157 | } 158 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/close_notjs.go: -------------------------------------------------------------------------------- 1 | // +build !js 2 | 3 | package websocket 4 | 5 | import ( 6 | "context" 7 | "encoding/binary" 8 | "errors" 9 | "fmt" 10 | "log" 11 | "time" 12 | 13 | "nhooyr.io/websocket/internal/errd" 14 | ) 15 | 16 | // Close performs the WebSocket close handshake with the given status code and reason. 17 | // 18 | // It will write a WebSocket close frame with a timeout of 5s and then wait 5s for 19 | // the peer to send a close frame. 20 | // All data messages received from the peer during the close handshake will be discarded. 21 | // 22 | // The connection can only be closed once. Additional calls to Close 23 | // are no-ops. 24 | // 25 | // The maximum length of reason must be 125 bytes. Avoid 26 | // sending a dynamic reason. 27 | // 28 | // Close will unblock all goroutines interacting with the connection once 29 | // complete. 30 | func (c *Conn) Close(code StatusCode, reason string) error { 31 | return c.closeHandshake(code, reason) 32 | } 33 | 34 | func (c *Conn) closeHandshake(code StatusCode, reason string) (err error) { 35 | defer errd.Wrap(&err, "failed to close WebSocket") 36 | 37 | writeErr := c.writeClose(code, reason) 38 | closeHandshakeErr := c.waitCloseHandshake() 39 | 40 | if writeErr != nil { 41 | return writeErr 42 | } 43 | 44 | if CloseStatus(closeHandshakeErr) == -1 { 45 | return closeHandshakeErr 46 | } 47 | 48 | return nil 49 | } 50 | 51 | var errAlreadyWroteClose = errors.New("already wrote close") 52 | 53 | func (c *Conn) writeClose(code StatusCode, reason string) error { 54 | c.closeMu.Lock() 55 | wroteClose := c.wroteClose 56 | c.wroteClose = true 57 | c.closeMu.Unlock() 58 | if wroteClose { 59 | return errAlreadyWroteClose 60 | } 61 | 62 | ce := CloseError{ 63 | Code: code, 64 | Reason: reason, 65 | } 66 | 67 | var p []byte 68 | var marshalErr error 69 | if ce.Code != StatusNoStatusRcvd { 70 | p, marshalErr = ce.bytes() 71 | if marshalErr != nil { 72 | log.Printf("websocket: %v", marshalErr) 73 | } 74 | } 75 | 76 | writeErr := c.writeControl(context.Background(), opClose, p) 77 | if CloseStatus(writeErr) != -1 { 78 | // Not a real error if it's due to a close frame being received. 79 | writeErr = nil 80 | } 81 | 82 | // We do this after in case there was an error writing the close frame. 83 | c.setCloseErr(fmt.Errorf("sent close frame: %w", ce)) 84 | 85 | if marshalErr != nil { 86 | return marshalErr 87 | } 88 | return writeErr 89 | } 90 | 91 | func (c *Conn) waitCloseHandshake() error { 92 | defer c.close(nil) 93 | 94 | ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 95 | defer cancel() 96 | 97 | err := c.readMu.lock(ctx) 98 | if err != nil { 99 | return err 100 | } 101 | defer c.readMu.unlock() 102 | 103 | if c.readCloseFrameErr != nil { 104 | return c.readCloseFrameErr 105 | } 106 | 107 | for { 108 | h, err := c.readLoop(ctx) 109 | if err != nil { 110 | return err 111 | } 112 | 113 | for i := int64(0); i < h.payloadLength; i++ { 114 | _, err := c.br.ReadByte() 115 | if err != nil { 116 | return err 117 | } 118 | } 119 | } 120 | } 121 | 122 | func parseClosePayload(p []byte) (CloseError, error) { 123 | if len(p) == 0 { 124 | return CloseError{ 125 | Code: StatusNoStatusRcvd, 126 | }, nil 127 | } 128 | 129 | if len(p) < 2 { 130 | return CloseError{}, fmt.Errorf("close payload %q too small, cannot even contain the 2 byte status code", p) 131 | } 132 | 133 | ce := CloseError{ 134 | Code: StatusCode(binary.BigEndian.Uint16(p)), 135 | Reason: string(p[2:]), 136 | } 137 | 138 | if !validWireCloseCode(ce.Code) { 139 | return CloseError{}, fmt.Errorf("invalid status code %v", ce.Code) 140 | } 141 | 142 | return ce, nil 143 | } 144 | 145 | // See http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number 146 | // and https://tools.ietf.org/html/rfc6455#section-7.4.1 147 | func validWireCloseCode(code StatusCode) bool { 148 | switch code { 149 | case statusReserved, StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: 150 | return false 151 | } 152 | 153 | if code >= StatusNormalClosure && code <= StatusBadGateway { 154 | return true 155 | } 156 | if code >= 3000 && code <= 4999 { 157 | return true 158 | } 159 | 160 | return false 161 | } 162 | 163 | func (ce CloseError) bytes() ([]byte, error) { 164 | p, err := ce.bytesErr() 165 | if err != nil { 166 | err = fmt.Errorf("failed to marshal close frame: %w", err) 167 | ce = CloseError{ 168 | Code: StatusInternalError, 169 | } 170 | p, _ = ce.bytesErr() 171 | } 172 | return p, err 173 | } 174 | 175 | const maxCloseReason = maxControlPayload - 2 176 | 177 | func (ce CloseError) bytesErr() ([]byte, error) { 178 | if len(ce.Reason) > maxCloseReason { 179 | return nil, fmt.Errorf("reason string max is %v but got %q with length %v", maxCloseReason, ce.Reason, len(ce.Reason)) 180 | } 181 | 182 | if !validWireCloseCode(ce.Code) { 183 | return nil, fmt.Errorf("status code %v cannot be set", ce.Code) 184 | } 185 | 186 | buf := make([]byte, 2+len(ce.Reason)) 187 | binary.BigEndian.PutUint16(buf, uint16(ce.Code)) 188 | copy(buf[2:], ce.Reason) 189 | return buf, nil 190 | } 191 | 192 | func (c *Conn) setCloseErr(err error) { 193 | c.closeMu.Lock() 194 | c.setCloseErrLocked(err) 195 | c.closeMu.Unlock() 196 | } 197 | 198 | func (c *Conn) setCloseErrLocked(err error) { 199 | if c.closeErr == nil { 200 | c.closeErr = fmt.Errorf("WebSocket closed: %w", err) 201 | } 202 | } 203 | 204 | func (c *Conn) isClosed() bool { 205 | select { 206 | case <-c.closed: 207 | return true 208 | default: 209 | return false 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /vendor/nhooyr.io/websocket/README.md: -------------------------------------------------------------------------------- 1 | # websocket 2 | 3 | [![godoc](https://godoc.org/nhooyr.io/websocket?status.svg)](https://pkg.go.dev/nhooyr.io/websocket) 4 | [![coverage](https://img.shields.io/badge/coverage-88%25-success)](https://nhooyrio-websocket-coverage.netlify.app) 5 | 6 | websocket is a minimal and idiomatic WebSocket library for Go. 7 | 8 | ## Install 9 | 10 | ```bash 11 | go get nhooyr.io/websocket 12 | ``` 13 | 14 | ## Highlights 15 | 16 | - Minimal and idiomatic API 17 | - First class [context.Context](https://blog.golang.org/context) support 18 | - Fully passes the WebSocket [autobahn-testsuite](https://github.com/crossbario/autobahn-testsuite) 19 | - [Single dependency](https://pkg.go.dev/nhooyr.io/websocket?tab=imports) 20 | - JSON and protobuf helpers in the [wsjson](https://pkg.go.dev/nhooyr.io/websocket/wsjson) and [wspb](https://pkg.go.dev/nhooyr.io/websocket/wspb) subpackages 21 | - Zero alloc reads and writes 22 | - Concurrent writes 23 | - [Close handshake](https://pkg.go.dev/nhooyr.io/websocket#Conn.Close) 24 | - [net.Conn](https://pkg.go.dev/nhooyr.io/websocket#NetConn) wrapper 25 | - [Ping pong](https://pkg.go.dev/nhooyr.io/websocket#Conn.Ping) API 26 | - [RFC 7692](https://tools.ietf.org/html/rfc7692) permessage-deflate compression 27 | - Compile to [Wasm](https://pkg.go.dev/nhooyr.io/websocket#hdr-Wasm) 28 | 29 | ## Roadmap 30 | 31 | - [ ] HTTP/2 [#4](https://github.com/nhooyr/websocket/issues/4) 32 | 33 | ## Examples 34 | 35 | For a production quality example that demonstrates the complete API, see the 36 | [echo example](./examples/echo). 37 | 38 | For a full stack example, see the [chat example](./examples/chat). 39 | 40 | ### Server 41 | 42 | ```go 43 | http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { 44 | c, err := websocket.Accept(w, r, nil) 45 | if err != nil { 46 | // ... 47 | } 48 | defer c.Close(websocket.StatusInternalError, "the sky is falling") 49 | 50 | ctx, cancel := context.WithTimeout(r.Context(), time.Second*10) 51 | defer cancel() 52 | 53 | var v interface{} 54 | err = wsjson.Read(ctx, c, &v) 55 | if err != nil { 56 | // ... 57 | } 58 | 59 | log.Printf("received: %v", v) 60 | 61 | c.Close(websocket.StatusNormalClosure, "") 62 | }) 63 | ``` 64 | 65 | ### Client 66 | 67 | ```go 68 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) 69 | defer cancel() 70 | 71 | c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil) 72 | if err != nil { 73 | // ... 74 | } 75 | defer c.Close(websocket.StatusInternalError, "the sky is falling") 76 | 77 | err = wsjson.Write(ctx, c, "hi") 78 | if err != nil { 79 | // ... 80 | } 81 | 82 | c.Close(websocket.StatusNormalClosure, "") 83 | ``` 84 | 85 | ## Comparison 86 | 87 | ### gorilla/websocket 88 | 89 | Advantages of [gorilla/websocket](https://github.com/gorilla/websocket): 90 | 91 | - Mature and widely used 92 | - [Prepared writes](https://pkg.go.dev/github.com/gorilla/websocket#PreparedMessage) 93 | - Configurable [buffer sizes](https://pkg.go.dev/github.com/gorilla/websocket#hdr-Buffers) 94 | 95 | Advantages of nhooyr.io/websocket: 96 | 97 | - Minimal and idiomatic API 98 | - Compare godoc of [nhooyr.io/websocket](https://pkg.go.dev/nhooyr.io/websocket) with [gorilla/websocket](https://pkg.go.dev/github.com/gorilla/websocket) side by side. 99 | - [net.Conn](https://pkg.go.dev/nhooyr.io/websocket#NetConn) wrapper 100 | - Zero alloc reads and writes ([gorilla/websocket#535](https://github.com/gorilla/websocket/issues/535)) 101 | - Full [context.Context](https://blog.golang.org/context) support 102 | - Dial uses [net/http.Client](https://golang.org/pkg/net/http/#Client) 103 | - Will enable easy HTTP/2 support in the future 104 | - Gorilla writes directly to a net.Conn and so duplicates features of net/http.Client. 105 | - Concurrent writes 106 | - Close handshake ([gorilla/websocket#448](https://github.com/gorilla/websocket/issues/448)) 107 | - Idiomatic [ping pong](https://pkg.go.dev/nhooyr.io/websocket#Conn.Ping) API 108 | - Gorilla requires registering a pong callback before sending a Ping 109 | - Can target Wasm ([gorilla/websocket#432](https://github.com/gorilla/websocket/issues/432)) 110 | - Transparent message buffer reuse with [wsjson](https://pkg.go.dev/nhooyr.io/websocket/wsjson) and [wspb](https://pkg.go.dev/nhooyr.io/websocket/wspb) subpackages 111 | - [1.75x](https://github.com/nhooyr/websocket/releases/tag/v1.7.4) faster WebSocket masking implementation in pure Go 112 | - Gorilla's implementation is slower and uses [unsafe](https://golang.org/pkg/unsafe/). 113 | - Full [permessage-deflate](https://tools.ietf.org/html/rfc7692) compression extension support 114 | - Gorilla only supports no context takeover mode 115 | - We use [klauspost/compress](https://github.com/klauspost/compress) for much lower memory usage ([gorilla/websocket#203](https://github.com/gorilla/websocket/issues/203)) 116 | - [CloseRead](https://pkg.go.dev/nhooyr.io/websocket#Conn.CloseRead) helper ([gorilla/websocket#492](https://github.com/gorilla/websocket/issues/492)) 117 | - Actively maintained ([gorilla/websocket#370](https://github.com/gorilla/websocket/issues/370)) 118 | 119 | #### golang.org/x/net/websocket 120 | 121 | [golang.org/x/net/websocket](https://pkg.go.dev/golang.org/x/net/websocket) is deprecated. 122 | See [golang/go/issues/18152](https://github.com/golang/go/issues/18152). 123 | 124 | The [net.Conn](https://pkg.go.dev/nhooyr.io/websocket#NetConn) can help in transitioning 125 | to nhooyr.io/websocket. 126 | 127 | #### gobwas/ws 128 | 129 | [gobwas/ws](https://github.com/gobwas/ws) has an extremely flexible API that allows it to be used 130 | in an event driven style for performance. See the author's [blog post](https://medium.freecodecamp.org/million-websockets-and-go-cc58418460bb). 131 | 132 | However when writing idiomatic Go, nhooyr.io/websocket will be faster and easier to use. 133 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/utils_set.go: -------------------------------------------------------------------------------- 1 | package antlr 2 | 3 | import "math" 4 | 5 | const ( 6 | _initalCapacity = 16 7 | _initalBucketCapacity = 8 8 | _loadFactor = 0.75 9 | ) 10 | 11 | type Set interface { 12 | Add(value interface{}) (added interface{}) 13 | Len() int 14 | Get(value interface{}) (found interface{}) 15 | Contains(value interface{}) bool 16 | Values() []interface{} 17 | Each(f func(interface{}) bool) 18 | } 19 | 20 | type array2DHashSet struct { 21 | buckets [][]Collectable[any] 22 | hashcodeFunction func(interface{}) int 23 | equalsFunction func(Collectable[any], Collectable[any]) bool 24 | 25 | n int // How many elements in set 26 | threshold int // when to expand 27 | 28 | currentPrime int // jump by 4 primes each expand or whatever 29 | initialBucketCapacity int 30 | } 31 | 32 | func (as *array2DHashSet) Each(f func(interface{}) bool) { 33 | if as.Len() < 1 { 34 | return 35 | } 36 | 37 | for _, bucket := range as.buckets { 38 | for _, o := range bucket { 39 | if o == nil { 40 | break 41 | } 42 | if !f(o) { 43 | return 44 | } 45 | } 46 | } 47 | } 48 | 49 | func (as *array2DHashSet) Values() []interface{} { 50 | if as.Len() < 1 { 51 | return nil 52 | } 53 | 54 | values := make([]interface{}, 0, as.Len()) 55 | as.Each(func(i interface{}) bool { 56 | values = append(values, i) 57 | return true 58 | }) 59 | return values 60 | } 61 | 62 | func (as *array2DHashSet) Contains(value Collectable[any]) bool { 63 | return as.Get(value) != nil 64 | } 65 | 66 | func (as *array2DHashSet) Add(value Collectable[any]) interface{} { 67 | if as.n > as.threshold { 68 | as.expand() 69 | } 70 | return as.innerAdd(value) 71 | } 72 | 73 | func (as *array2DHashSet) expand() { 74 | old := as.buckets 75 | 76 | as.currentPrime += 4 77 | 78 | var ( 79 | newCapacity = len(as.buckets) << 1 80 | newTable = as.createBuckets(newCapacity) 81 | newBucketLengths = make([]int, len(newTable)) 82 | ) 83 | 84 | as.buckets = newTable 85 | as.threshold = int(float64(newCapacity) * _loadFactor) 86 | 87 | for _, bucket := range old { 88 | if bucket == nil { 89 | continue 90 | } 91 | 92 | for _, o := range bucket { 93 | if o == nil { 94 | break 95 | } 96 | 97 | b := as.getBuckets(o) 98 | bucketLength := newBucketLengths[b] 99 | var newBucket []Collectable[any] 100 | if bucketLength == 0 { 101 | // new bucket 102 | newBucket = as.createBucket(as.initialBucketCapacity) 103 | newTable[b] = newBucket 104 | } else { 105 | newBucket = newTable[b] 106 | if bucketLength == len(newBucket) { 107 | // expand 108 | newBucketCopy := make([]Collectable[any], len(newBucket)<<1) 109 | copy(newBucketCopy[:bucketLength], newBucket) 110 | newBucket = newBucketCopy 111 | newTable[b] = newBucket 112 | } 113 | } 114 | 115 | newBucket[bucketLength] = o 116 | newBucketLengths[b]++ 117 | } 118 | } 119 | } 120 | 121 | func (as *array2DHashSet) Len() int { 122 | return as.n 123 | } 124 | 125 | func (as *array2DHashSet) Get(o Collectable[any]) interface{} { 126 | if o == nil { 127 | return nil 128 | } 129 | 130 | b := as.getBuckets(o) 131 | bucket := as.buckets[b] 132 | if bucket == nil { // no bucket 133 | return nil 134 | } 135 | 136 | for _, e := range bucket { 137 | if e == nil { 138 | return nil // empty slot; not there 139 | } 140 | if as.equalsFunction(e, o) { 141 | return e 142 | } 143 | } 144 | 145 | return nil 146 | } 147 | 148 | func (as *array2DHashSet) innerAdd(o Collectable[any]) interface{} { 149 | b := as.getBuckets(o) 150 | 151 | bucket := as.buckets[b] 152 | 153 | // new bucket 154 | if bucket == nil { 155 | bucket = as.createBucket(as.initialBucketCapacity) 156 | bucket[0] = o 157 | 158 | as.buckets[b] = bucket 159 | as.n++ 160 | return o 161 | } 162 | 163 | // look for it in bucket 164 | for i := 0; i < len(bucket); i++ { 165 | existing := bucket[i] 166 | if existing == nil { // empty slot; not there, add. 167 | bucket[i] = o 168 | as.n++ 169 | return o 170 | } 171 | 172 | if as.equalsFunction(existing, o) { // found existing, quit 173 | return existing 174 | } 175 | } 176 | 177 | // full bucket, expand and add to end 178 | oldLength := len(bucket) 179 | bucketCopy := make([]Collectable[any], oldLength<<1) 180 | copy(bucketCopy[:oldLength], bucket) 181 | bucket = bucketCopy 182 | as.buckets[b] = bucket 183 | bucket[oldLength] = o 184 | as.n++ 185 | return o 186 | } 187 | 188 | func (as *array2DHashSet) getBuckets(value Collectable[any]) int { 189 | hash := as.hashcodeFunction(value) 190 | return hash & (len(as.buckets) - 1) 191 | } 192 | 193 | func (as *array2DHashSet) createBuckets(cap int) [][]Collectable[any] { 194 | return make([][]Collectable[any], cap) 195 | } 196 | 197 | func (as *array2DHashSet) createBucket(cap int) []Collectable[any] { 198 | return make([]Collectable[any], cap) 199 | } 200 | 201 | func newArray2DHashSetWithCap( 202 | hashcodeFunction func(interface{}) int, 203 | equalsFunction func(Collectable[any], Collectable[any]) bool, 204 | initCap int, 205 | initBucketCap int, 206 | ) *array2DHashSet { 207 | if hashcodeFunction == nil { 208 | hashcodeFunction = standardHashFunction 209 | } 210 | 211 | if equalsFunction == nil { 212 | equalsFunction = standardEqualsFunction 213 | } 214 | 215 | ret := &array2DHashSet{ 216 | hashcodeFunction: hashcodeFunction, 217 | equalsFunction: equalsFunction, 218 | 219 | n: 0, 220 | threshold: int(math.Floor(_initalCapacity * _loadFactor)), 221 | 222 | currentPrime: 1, 223 | initialBucketCapacity: initBucketCap, 224 | } 225 | 226 | ret.buckets = ret.createBuckets(initCap) 227 | return ret 228 | } 229 | 230 | func newArray2DHashSet( 231 | hashcodeFunction func(interface{}) int, 232 | equalsFunction func(Collectable[any], Collectable[any]) bool, 233 | ) *array2DHashSet { 234 | return newArray2DHashSetWithCap(hashcodeFunction, equalsFunction, _initalCapacity, _initalBucketCapacity) 235 | } 236 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/token.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | type TokenSourceCharStreamPair struct { 13 | tokenSource TokenSource 14 | charStream CharStream 15 | } 16 | 17 | // A token has properties: text, type, line, character position in the line 18 | // (so we can ignore tabs), token channel, index, and source from which 19 | // we obtained this token. 20 | 21 | type Token interface { 22 | GetSource() *TokenSourceCharStreamPair 23 | GetTokenType() int 24 | GetChannel() int 25 | GetStart() int 26 | GetStop() int 27 | GetLine() int 28 | GetColumn() int 29 | 30 | GetText() string 31 | SetText(s string) 32 | 33 | GetTokenIndex() int 34 | SetTokenIndex(v int) 35 | 36 | GetTokenSource() TokenSource 37 | GetInputStream() CharStream 38 | } 39 | 40 | type BaseToken struct { 41 | source *TokenSourceCharStreamPair 42 | tokenType int // token type of the token 43 | channel int // The parser ignores everything not on DEFAULT_CHANNEL 44 | start int // optional return -1 if not implemented. 45 | stop int // optional return -1 if not implemented. 46 | tokenIndex int // from 0..n-1 of the token object in the input stream 47 | line int // line=1..n of the 1st character 48 | column int // beginning of the line at which it occurs, 0..n-1 49 | text string // text of the token. 50 | readOnly bool 51 | } 52 | 53 | const ( 54 | TokenInvalidType = 0 55 | 56 | // During lookahead operations, this "token" signifies we hit rule end ATN state 57 | // and did not follow it despite needing to. 58 | TokenEpsilon = -2 59 | 60 | TokenMinUserTokenType = 1 61 | 62 | TokenEOF = -1 63 | 64 | // All tokens go to the parser (unless Skip() is called in that rule) 65 | // on a particular "channel". The parser tunes to a particular channel 66 | // so that whitespace etc... can go to the parser on a "hidden" channel. 67 | 68 | TokenDefaultChannel = 0 69 | 70 | // Anything on different channel than DEFAULT_CHANNEL is not parsed 71 | // by parser. 72 | 73 | TokenHiddenChannel = 1 74 | ) 75 | 76 | func (b *BaseToken) GetChannel() int { 77 | return b.channel 78 | } 79 | 80 | func (b *BaseToken) GetStart() int { 81 | return b.start 82 | } 83 | 84 | func (b *BaseToken) GetStop() int { 85 | return b.stop 86 | } 87 | 88 | func (b *BaseToken) GetLine() int { 89 | return b.line 90 | } 91 | 92 | func (b *BaseToken) GetColumn() int { 93 | return b.column 94 | } 95 | 96 | func (b *BaseToken) GetTokenType() int { 97 | return b.tokenType 98 | } 99 | 100 | func (b *BaseToken) GetSource() *TokenSourceCharStreamPair { 101 | return b.source 102 | } 103 | 104 | func (b *BaseToken) GetTokenIndex() int { 105 | return b.tokenIndex 106 | } 107 | 108 | func (b *BaseToken) SetTokenIndex(v int) { 109 | b.tokenIndex = v 110 | } 111 | 112 | func (b *BaseToken) GetTokenSource() TokenSource { 113 | return b.source.tokenSource 114 | } 115 | 116 | func (b *BaseToken) GetInputStream() CharStream { 117 | return b.source.charStream 118 | } 119 | 120 | type CommonToken struct { 121 | *BaseToken 122 | } 123 | 124 | func NewCommonToken(source *TokenSourceCharStreamPair, tokenType, channel, start, stop int) *CommonToken { 125 | 126 | t := new(CommonToken) 127 | 128 | t.BaseToken = new(BaseToken) 129 | 130 | t.source = source 131 | t.tokenType = tokenType 132 | t.channel = channel 133 | t.start = start 134 | t.stop = stop 135 | t.tokenIndex = -1 136 | if t.source.tokenSource != nil { 137 | t.line = source.tokenSource.GetLine() 138 | t.column = source.tokenSource.GetCharPositionInLine() 139 | } else { 140 | t.column = -1 141 | } 142 | return t 143 | } 144 | 145 | // An empty {@link Pair} which is used as the default value of 146 | // {@link //source} for tokens that do not have a source. 147 | 148 | //CommonToken.EMPTY_SOURCE = [ nil, nil ] 149 | 150 | // Constructs a New{@link CommonToken} as a copy of another {@link Token}. 151 | // 152 | //

153 | // If {@code oldToken} is also a {@link CommonToken} instance, the newly 154 | // constructed token will share a reference to the {@link //text} field and 155 | // the {@link Pair} stored in {@link //source}. Otherwise, {@link //text} will 156 | // be assigned the result of calling {@link //GetText}, and {@link //source} 157 | // will be constructed from the result of {@link Token//GetTokenSource} and 158 | // {@link Token//GetInputStream}.

159 | // 160 | // @param oldToken The token to copy. 161 | func (c *CommonToken) clone() *CommonToken { 162 | t := NewCommonToken(c.source, c.tokenType, c.channel, c.start, c.stop) 163 | t.tokenIndex = c.GetTokenIndex() 164 | t.line = c.GetLine() 165 | t.column = c.GetColumn() 166 | t.text = c.GetText() 167 | return t 168 | } 169 | 170 | func (c *CommonToken) GetText() string { 171 | if c.text != "" { 172 | return c.text 173 | } 174 | input := c.GetInputStream() 175 | if input == nil { 176 | return "" 177 | } 178 | n := input.Size() 179 | if c.start < n && c.stop < n { 180 | return input.GetTextFromInterval(NewInterval(c.start, c.stop)) 181 | } 182 | return "" 183 | } 184 | 185 | func (c *CommonToken) SetText(text string) { 186 | c.text = text 187 | } 188 | 189 | func (c *CommonToken) String() string { 190 | txt := c.GetText() 191 | if txt != "" { 192 | txt = strings.Replace(txt, "\n", "\\n", -1) 193 | txt = strings.Replace(txt, "\r", "\\r", -1) 194 | txt = strings.Replace(txt, "\t", "\\t", -1) 195 | } else { 196 | txt = "" 197 | } 198 | 199 | var ch string 200 | if c.channel > 0 { 201 | ch = ",channel=" + strconv.Itoa(c.channel) 202 | } else { 203 | ch = "" 204 | } 205 | 206 | return "[@" + strconv.Itoa(c.tokenIndex) + "," + strconv.Itoa(c.start) + ":" + strconv.Itoa(c.stop) + "='" + 207 | txt + "',<" + strconv.Itoa(c.tokenType) + ">" + 208 | ch + "," + strconv.Itoa(c.line) + ":" + strconv.Itoa(c.column) + "]" 209 | } 210 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/dfa_state.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 2 | // Use of this file is governed by the BSD 3-clause license that 3 | // can be found in the LICENSE.txt file in the project root. 4 | 5 | package antlr 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | // PredPrediction maps a predicate to a predicted alternative. 12 | type PredPrediction struct { 13 | alt int 14 | pred SemanticContext 15 | } 16 | 17 | func NewPredPrediction(pred SemanticContext, alt int) *PredPrediction { 18 | return &PredPrediction{alt: alt, pred: pred} 19 | } 20 | 21 | func (p *PredPrediction) String() string { 22 | return "(" + fmt.Sprint(p.pred) + ", " + fmt.Sprint(p.alt) + ")" 23 | } 24 | 25 | // DFAState represents a set of possible ATN configurations. As Aho, Sethi, 26 | // Ullman p. 117 says: "The DFA uses its state to keep track of all possible 27 | // states the ATN can be in after reading each input symbol. That is to say, 28 | // after reading input a1a2..an, the DFA is in a state that represents the 29 | // subset T of the states of the ATN that are reachable from the ATN's start 30 | // state along some path labeled a1a2..an." In conventional NFA-to-DFA 31 | // conversion, therefore, the subset T would be a bitset representing the set of 32 | // states the ATN could be in. We need to track the alt predicted by each state 33 | // as well, however. More importantly, we need to maintain a stack of states, 34 | // tracking the closure operations as they jump from rule to rule, emulating 35 | // rule invocations (method calls). I have to add a stack to simulate the proper 36 | // lookahead sequences for the underlying LL grammar from which the ATN was 37 | // derived. 38 | // 39 | // I use a set of ATNConfig objects, not simple states. An ATNConfig is both a 40 | // state (ala normal conversion) and a RuleContext describing the chain of rules 41 | // (if any) followed to arrive at that state. 42 | // 43 | // A DFAState may have multiple references to a particular state, but with 44 | // different ATN contexts (with same or different alts) meaning that state was 45 | // reached via a different set of rule invocations. 46 | type DFAState struct { 47 | stateNumber int 48 | configs ATNConfigSet 49 | 50 | // edges elements point to the target of the symbol. Shift up by 1 so (-1) 51 | // Token.EOF maps to the first element. 52 | edges []*DFAState 53 | 54 | isAcceptState bool 55 | 56 | // prediction is the ttype we match or alt we predict if the state is accept. 57 | // Set to ATN.INVALID_ALT_NUMBER when predicates != nil or 58 | // requiresFullContext. 59 | prediction int 60 | 61 | lexerActionExecutor *LexerActionExecutor 62 | 63 | // requiresFullContext indicates it was created during an SLL prediction that 64 | // discovered a conflict between the configurations in the state. Future 65 | // ParserATNSimulator.execATN invocations immediately jump doing 66 | // full context prediction if true. 67 | requiresFullContext bool 68 | 69 | // predicates is the predicates associated with the ATN configurations of the 70 | // DFA state during SLL parsing. When we have predicates, requiresFullContext 71 | // is false, since full context prediction evaluates predicates on-the-fly. If 72 | // d is 73 | // not nil, then prediction is ATN.INVALID_ALT_NUMBER. 74 | // 75 | // We only use these for non-requiresFullContext but conflicting states. That 76 | // means we know from the context (it's $ or we don't dip into outer context) 77 | // that it's an ambiguity not a conflict. 78 | // 79 | // This list is computed by 80 | // ParserATNSimulator.predicateDFAState. 81 | predicates []*PredPrediction 82 | } 83 | 84 | func NewDFAState(stateNumber int, configs ATNConfigSet) *DFAState { 85 | if configs == nil { 86 | configs = NewBaseATNConfigSet(false) 87 | } 88 | 89 | return &DFAState{configs: configs, stateNumber: stateNumber} 90 | } 91 | 92 | // GetAltSet gets the set of all alts mentioned by all ATN configurations in d. 93 | func (d *DFAState) GetAltSet() []int { 94 | var alts []int 95 | 96 | if d.configs != nil { 97 | for _, c := range d.configs.GetItems() { 98 | alts = append(alts, c.GetAlt()) 99 | } 100 | } 101 | 102 | if len(alts) == 0 { 103 | return nil 104 | } 105 | 106 | return alts 107 | } 108 | 109 | func (d *DFAState) getEdges() []*DFAState { 110 | return d.edges 111 | } 112 | 113 | func (d *DFAState) numEdges() int { 114 | return len(d.edges) 115 | } 116 | 117 | func (d *DFAState) getIthEdge(i int) *DFAState { 118 | return d.edges[i] 119 | } 120 | 121 | func (d *DFAState) setEdges(newEdges []*DFAState) { 122 | d.edges = newEdges 123 | } 124 | 125 | func (d *DFAState) setIthEdge(i int, edge *DFAState) { 126 | d.edges[i] = edge 127 | } 128 | 129 | func (d *DFAState) setPrediction(v int) { 130 | d.prediction = v 131 | } 132 | 133 | func (d *DFAState) String() string { 134 | var s string 135 | if d.isAcceptState { 136 | if d.predicates != nil { 137 | s = "=>" + fmt.Sprint(d.predicates) 138 | } else { 139 | s = "=>" + fmt.Sprint(d.prediction) 140 | } 141 | } 142 | 143 | return fmt.Sprintf("%d:%s%s", d.stateNumber, fmt.Sprint(d.configs), s) 144 | } 145 | 146 | func (d *DFAState) Hash() int { 147 | h := murmurInit(7) 148 | h = murmurUpdate(h, d.configs.Hash()) 149 | return murmurFinish(h, 1) 150 | } 151 | 152 | // Equals returns whether d equals other. Two DFAStates are equal if their ATN 153 | // configuration sets are the same. This method is used to see if a state 154 | // already exists. 155 | // 156 | // Because the number of alternatives and number of ATN configurations are 157 | // finite, there is a finite number of DFA states that can be processed. This is 158 | // necessary to show that the algorithm terminates. 159 | // 160 | // Cannot test the DFA state numbers here because in 161 | // ParserATNSimulator.addDFAState we need to know if any other state exists that 162 | // has d exact set of ATN configurations. The stateNumber is irrelevant. 163 | func (d *DFAState) Equals(o Collectable[*DFAState]) bool { 164 | if d == o { 165 | return true 166 | } 167 | 168 | return d.configs.Equals(o.(*DFAState).configs) 169 | } 170 | -------------------------------------------------------------------------------- /vendor/github.com/antlr/antlr4/runtime/Go/antlr/v4/comparators.go: -------------------------------------------------------------------------------- 1 | package antlr 2 | 3 | // Copyright (c) 2012-2022 The ANTLR Project. All rights reserved. 4 | // Use of this file is governed by the BSD 3-clause license that 5 | // can be found in the LICENSE.txt file in the project root. 6 | 7 | // This file contains all the implementations of custom comparators used for generic collections when the 8 | // Hash() and Equals() funcs supplied by the struct objects themselves need to be overridden. Normally, we would 9 | // put the comparators in the source file for the struct themselves, but given the organization of this code is 10 | // sorta kinda based upon the Java code, I found it confusing trying to find out which comparator was where and used by 11 | // which instantiation of a collection. For instance, an Array2DHashSet in the Java source, when used with ATNConfig 12 | // collections requires three different comparators depending on what the collection is being used for. Collecting - pun intended - 13 | // all the comparators here, makes it much easier to see which implementation of hash and equals is used by which collection. 14 | // It also makes it easy to verify that the Hash() and Equals() functions marry up with the Java implementations. 15 | 16 | // ObjEqComparator is the equivalent of the Java ObjectEqualityComparator, which is the default instance of 17 | // Equality comparator. We do not have inheritance in Go, only interfaces, so we use generics to enforce some 18 | // type safety and avoid having to implement this for every type that we want to perform comparison on. 19 | // 20 | // This comparator works by using the standard Hash() and Equals() methods of the type T that is being compared. Which 21 | // allows us to use it in any collection instance that does nto require a special hash or equals implementation. 22 | type ObjEqComparator[T Collectable[T]] struct{} 23 | 24 | var ( 25 | aStateEqInst = &ObjEqComparator[ATNState]{} 26 | aConfEqInst = &ObjEqComparator[ATNConfig]{} 27 | aConfCompInst = &ATNConfigComparator[ATNConfig]{} 28 | atnConfCompInst = &BaseATNConfigComparator[ATNConfig]{} 29 | dfaStateEqInst = &ObjEqComparator[*DFAState]{} 30 | semctxEqInst = &ObjEqComparator[SemanticContext]{} 31 | atnAltCfgEqInst = &ATNAltConfigComparator[ATNConfig]{} 32 | ) 33 | 34 | // Equals2 delegates to the Equals() method of type T 35 | func (c *ObjEqComparator[T]) Equals2(o1, o2 T) bool { 36 | return o1.Equals(o2) 37 | } 38 | 39 | // Hash1 delegates to the Hash() method of type T 40 | func (c *ObjEqComparator[T]) Hash1(o T) int { 41 | 42 | return o.Hash() 43 | } 44 | 45 | type SemCComparator[T Collectable[T]] struct{} 46 | 47 | // ATNConfigComparator is used as the compartor for the configLookup field of an ATNConfigSet 48 | // and has a custom Equals() and Hash() implementation, because equality is not based on the 49 | // standard Hash() and Equals() methods of the ATNConfig type. 50 | type ATNConfigComparator[T Collectable[T]] struct { 51 | } 52 | 53 | // Equals2 is a custom comparator for ATNConfigs specifically for configLookup 54 | func (c *ATNConfigComparator[T]) Equals2(o1, o2 ATNConfig) bool { 55 | 56 | // Same pointer, must be equal, even if both nil 57 | // 58 | if o1 == o2 { 59 | return true 60 | 61 | } 62 | 63 | // If either are nil, but not both, then the result is false 64 | // 65 | if o1 == nil || o2 == nil { 66 | return false 67 | } 68 | 69 | return o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() && 70 | o1.GetAlt() == o2.GetAlt() && 71 | o1.GetSemanticContext().Equals(o2.GetSemanticContext()) 72 | } 73 | 74 | // Hash1 is custom hash implementation for ATNConfigs specifically for configLookup 75 | func (c *ATNConfigComparator[T]) Hash1(o ATNConfig) int { 76 | hash := 7 77 | hash = 31*hash + o.GetState().GetStateNumber() 78 | hash = 31*hash + o.GetAlt() 79 | hash = 31*hash + o.GetSemanticContext().Hash() 80 | return hash 81 | } 82 | 83 | // ATNAltConfigComparator is used as the comparator for mapping configs to Alt Bitsets 84 | type ATNAltConfigComparator[T Collectable[T]] struct { 85 | } 86 | 87 | // Equals2 is a custom comparator for ATNConfigs specifically for configLookup 88 | func (c *ATNAltConfigComparator[T]) Equals2(o1, o2 ATNConfig) bool { 89 | 90 | // Same pointer, must be equal, even if both nil 91 | // 92 | if o1 == o2 { 93 | return true 94 | 95 | } 96 | 97 | // If either are nil, but not both, then the result is false 98 | // 99 | if o1 == nil || o2 == nil { 100 | return false 101 | } 102 | 103 | return o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() && 104 | o1.GetContext().Equals(o2.GetContext()) 105 | } 106 | 107 | // Hash1 is custom hash implementation for ATNConfigs specifically for configLookup 108 | func (c *ATNAltConfigComparator[T]) Hash1(o ATNConfig) int { 109 | h := murmurInit(7) 110 | h = murmurUpdate(h, o.GetState().GetStateNumber()) 111 | h = murmurUpdate(h, o.GetContext().Hash()) 112 | return murmurFinish(h, 2) 113 | } 114 | 115 | // BaseATNConfigComparator is used as the comparator for the configLookup field of a BaseATNConfigSet 116 | // and has a custom Equals() and Hash() implementation, because equality is not based on the 117 | // standard Hash() and Equals() methods of the ATNConfig type. 118 | type BaseATNConfigComparator[T Collectable[T]] struct { 119 | } 120 | 121 | // Equals2 is a custom comparator for ATNConfigs specifically for baseATNConfigSet 122 | func (c *BaseATNConfigComparator[T]) Equals2(o1, o2 ATNConfig) bool { 123 | 124 | // Same pointer, must be equal, even if both nil 125 | // 126 | if o1 == o2 { 127 | return true 128 | 129 | } 130 | 131 | // If either are nil, but not both, then the result is false 132 | // 133 | if o1 == nil || o2 == nil { 134 | return false 135 | } 136 | 137 | return o1.GetState().GetStateNumber() == o2.GetState().GetStateNumber() && 138 | o1.GetAlt() == o2.GetAlt() && 139 | o1.GetSemanticContext().Equals(o2.GetSemanticContext()) 140 | } 141 | 142 | // Hash1 is custom hash implementation for ATNConfigs specifically for configLookup, but in fact just 143 | // delegates to the standard Hash() method of the ATNConfig type. 144 | func (c *BaseATNConfigComparator[T]) Hash1(o ATNConfig) int { 145 | 146 | return o.Hash() 147 | } 148 | --------------------------------------------------------------------------------