mirror of
https://github.com/bitcoinresearchkit/brk.git
synced 2026-04-24 06:39:58 -07:00
bitview: reorg part 8
This commit is contained in:
@@ -20,7 +20,7 @@ pub trait Bridge {
|
||||
|
||||
impl Bridge for Interface<'static> {
|
||||
fn generate_js_files(&self, packages_path: &Path) -> io::Result<()> {
|
||||
let path = packages_path.join("brk");
|
||||
let path = packages_path.join("brk-client");
|
||||
|
||||
if !fs::exists(&path)? {
|
||||
return Ok(());
|
||||
|
||||
@@ -38,7 +38,8 @@ pub async fn bundle(
|
||||
let absolute_source_sw_path_clone = absolute_source_sw_path.clone();
|
||||
|
||||
let absolute_dist_path = relative_dist_path.absolutize();
|
||||
let absolute_dist_scripts_entry_path = absolute_dist_path.join("scripts/entry.js");
|
||||
let absolute_dist_scripts_path = absolute_dist_path.join("scripts");
|
||||
let absolute_dist_scripts_entry_path = absolute_dist_scripts_path.join("entry.js");
|
||||
let absolute_dist_scripts_entry_path_clone = absolute_dist_scripts_entry_path.clone();
|
||||
let absolute_dist_index_path = absolute_dist_path.join("index.html");
|
||||
let absolute_dist_sw_path = absolute_dist_path.join("service-worker.js");
|
||||
@@ -50,6 +51,8 @@ pub async fn bundle(
|
||||
&absolute_source_scripts_packages_path,
|
||||
)?;
|
||||
copy_dir_all(&absolute_source_path, &absolute_dist_path)?;
|
||||
fs::remove_dir_all(&absolute_dist_scripts_path)?;
|
||||
fs::create_dir(&absolute_dist_scripts_path)?;
|
||||
|
||||
let mut bundler = Bundler::new(BundlerOptions {
|
||||
input: Some(vec![format!("./{source_folder}/scripts/entry.js").into()]),
|
||||
@@ -65,7 +68,7 @@ pub async fn bundle(
|
||||
error!("{error:?}");
|
||||
}
|
||||
|
||||
let write_index = move || {
|
||||
let update_dist_index = move || {
|
||||
let mut contents = fs::read_to_string(&absolute_source_index_path).unwrap();
|
||||
|
||||
if let Ok(entry) = fs::read_to_string(&absolute_dist_scripts_entry_path_clone)
|
||||
@@ -79,23 +82,21 @@ pub async fn bundle(
|
||||
let _ = fs::write(&absolute_dist_index_path, contents);
|
||||
};
|
||||
|
||||
let write_sw = move || {
|
||||
let update_source_sw = move || {
|
||||
let contents = fs::read_to_string(&absolute_source_sw_path)
|
||||
.unwrap()
|
||||
.replace("__VERSION__", &format!("v{VERSION}"));
|
||||
let _ = fs::write(&absolute_dist_sw_path, contents);
|
||||
};
|
||||
|
||||
write_index();
|
||||
write_sw();
|
||||
update_dist_index();
|
||||
update_source_sw();
|
||||
|
||||
if !watch {
|
||||
return Ok(relative_dist_path);
|
||||
}
|
||||
|
||||
tokio::spawn(async move {
|
||||
let absolute_websites_path = absolute_websites_path_clone.clone();
|
||||
|
||||
let mut event_watcher = notify::recommended_watcher(
|
||||
move |res: Result<notify::Event, notify::Error>| match res {
|
||||
Ok(event) => match event.kind {
|
||||
@@ -105,28 +106,26 @@ pub async fn bundle(
|
||||
}
|
||||
.into_iter()
|
||||
.for_each(|path| {
|
||||
let path = path.absolutize();
|
||||
|
||||
if path == absolute_dist_scripts_entry_path
|
||||
|| path == absolute_source_index_path_clone
|
||||
{
|
||||
write_index();
|
||||
update_dist_index();
|
||||
} else if path == absolute_source_sw_path_clone {
|
||||
write_sw();
|
||||
} else if path.starts_with(&absolute_packages_path) {
|
||||
let suffix = path.strip_prefix(&absolute_websites_path).unwrap();
|
||||
let dist_path = absolute_source_scripts_path.join(suffix);
|
||||
|
||||
dbg!(&suffix, &dist_path);
|
||||
update_source_sw();
|
||||
} else if let Ok(suffix) = path.strip_prefix(&absolute_packages_path) {
|
||||
let source_packages_path =
|
||||
absolute_source_scripts_packages_path.join(suffix);
|
||||
if path.is_file() {
|
||||
let _ = fs::create_dir_all(path.parent().unwrap());
|
||||
let _ = fs::copy(&path, &dist_path);
|
||||
let _ = fs::copy(&path, &source_packages_path);
|
||||
}
|
||||
} else if path.starts_with(&absolute_source_path)
|
||||
} else if let Ok(suffix) = path.strip_prefix(&absolute_source_path)
|
||||
// scripts are handled by rolldown
|
||||
&& !path.starts_with(&absolute_source_scripts_path)
|
||||
{
|
||||
let suffix = path.strip_prefix(&absolute_source_path).unwrap();
|
||||
let dist_path = absolute_dist_path.join(suffix);
|
||||
|
||||
if path.is_file() {
|
||||
let _ = fs::create_dir_all(path.parent().unwrap());
|
||||
let _ = fs::copy(&path, &dist_path);
|
||||
|
||||
@@ -121,10 +121,11 @@ pub fn run() -> color_eyre::Result<()> {
|
||||
Ok(()) as Result<()>
|
||||
};
|
||||
|
||||
let _handle = tokio::runtime::Builder::new_multi_thread()
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()?
|
||||
.spawn(future);
|
||||
.build()?;
|
||||
|
||||
let _handle = runtime.spawn(future);
|
||||
|
||||
loop {
|
||||
wait_for_synced_node(rpc)?;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use bitcoincore_rpc::Client;
|
||||
use brk_error::{Error, Result};
|
||||
use brk_parser::NUMBER_OF_UNSAFE_BLOCKS;
|
||||
use brk_structs::{
|
||||
BlockHash, CheckedSub, EmptyOutputIndex, Height, InputIndex, OpReturnIndex, OutputIndex,
|
||||
OutputType, P2AAddressIndex, P2MSOutputIndex, P2PK33AddressIndex, P2PK65AddressIndex,
|
||||
@@ -13,6 +12,8 @@ use vecdb::{
|
||||
|
||||
use crate::{Stores, Vecs};
|
||||
|
||||
const NUMBER_OF_UNSAFE_BLOCKS: usize = 100;
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Indexes {
|
||||
pub emptyoutputindex: EmptyOutputIndex,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
use std::path::Path;
|
||||
|
||||
use bitcoincore_rpc::{Auth, Client};
|
||||
use brk_error::Result;
|
||||
@@ -23,15 +23,8 @@ fn main() -> Result<()> {
|
||||
let start = None;
|
||||
// let start = Some(916037_u32.into());
|
||||
let end = None;
|
||||
// let mut blk_index = 0;
|
||||
// let mut diff = BTreeMap::new();
|
||||
parser.parse(start, end).iter().for_each(|block| {
|
||||
println!("{}: {}", block.height(), block.hash());
|
||||
// let new_blk_index = block.metadata().blk_index();
|
||||
// if new_blk_index < blk_index {
|
||||
// diff.insert(blk_index - new_blk_index, block.height());
|
||||
// }
|
||||
// blk_index = new_blk_index;
|
||||
});
|
||||
|
||||
// let v = diff.iter().rev().take(10).collect::<Vec<_>>();
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::{
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use bitcoin::{block::Header, consensus::Decodable};
|
||||
@@ -29,8 +30,6 @@ use any_block::*;
|
||||
pub use xor_bytes::*;
|
||||
pub use xor_index::*;
|
||||
|
||||
pub const NUMBER_OF_UNSAFE_BLOCKS: usize = 100;
|
||||
|
||||
const MAGIC_BYTES: [u8; 4] = [249, 190, 180, 217];
|
||||
const BOUND_CAP: usize = 50;
|
||||
|
||||
@@ -79,7 +78,7 @@ impl Parser {
|
||||
pub fn parse(&self, start: Option<Height>, end: Option<Height>) -> Receiver<ParsedBlock> {
|
||||
let rpc = self.rpc;
|
||||
|
||||
let (send_bytes, recv_bytes) = bounded(BOUND_CAP);
|
||||
let (send_bytes, recv_bytes) = bounded(BOUND_CAP / 2);
|
||||
let (send_block, recv_block) = bounded(BOUND_CAP);
|
||||
let (send_ordered, recv_ordered) = bounded(BOUND_CAP);
|
||||
|
||||
@@ -183,10 +182,13 @@ impl Parser {
|
||||
recv_bytes.iter().try_for_each(|tuple| {
|
||||
bulk.push(tuple);
|
||||
|
||||
if bulk.len() < BOUND_CAP {
|
||||
if bulk.len() < BOUND_CAP / 2 {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
|
||||
while send_block.len() >= bulk.len() {
|
||||
thread::sleep(Duration::from_micros(100));
|
||||
}
|
||||
drain_and_send(&mut bulk)
|
||||
})?;
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ use vecdb::{AnyIterableVec, VecIterator};
|
||||
use super::AppState;
|
||||
|
||||
mod explorer;
|
||||
mod vecs;
|
||||
mod metrics;
|
||||
|
||||
pub trait ApiRoutes {
|
||||
fn add_api_routes(self) -> Self;
|
||||
@@ -273,7 +273,7 @@ impl ApiRoutes for Router<AppState> {
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/api/vecs/id-to-indexes",
|
||||
"/api/vecs/metric-to-indexes",
|
||||
get(
|
||||
async |State(app_state): State<AppState>,
|
||||
Query(param): Query<IdParam>|
|
||||
@@ -282,8 +282,9 @@ impl ApiRoutes for Router<AppState> {
|
||||
},
|
||||
),
|
||||
)
|
||||
// .route("/api/vecs/variants", get(variants_handler))
|
||||
.route("/api/vecs/query", get(vecs::handler))
|
||||
// DEPRECATED
|
||||
.route("/api/vecs/query", get(metrics::handler))
|
||||
// DEPRECATED
|
||||
.route(
|
||||
"/api/vecs/{variant}",
|
||||
get(
|
||||
@@ -301,7 +302,7 @@ impl ApiRoutes for Router<AppState> {
|
||||
(index, split.collect::<Vec<_>>().join(TO_SEPARATOR)),
|
||||
params_opt,
|
||||
));
|
||||
vecs::handler(uri, headers, Query(params), state).await
|
||||
metrics::handler(uri, headers, Query(params), state).await
|
||||
} else {
|
||||
"Bad variant".into_response()
|
||||
}
|
||||
|
||||
122
packages/brk-client/index.js
Normal file
122
packages/brk-client/index.js
Normal file
@@ -0,0 +1,122 @@
|
||||
import { runWhenIdle } from "./idle";
|
||||
|
||||
import { POOL_ID_TO_POOL_NAME } from "./generated/pools";
|
||||
import { hasMetric, metricToIndexes } from "./metrics";
|
||||
|
||||
/**
|
||||
* @typedef {ReturnType<createClient>} BRKClient
|
||||
*/
|
||||
|
||||
const CACHE_NAME = "__BRK_CLIENT__";
|
||||
|
||||
/**
|
||||
* @param {string} [origin] - defaults to /
|
||||
*/
|
||||
export function createClient(origin = "/") {
|
||||
/**
|
||||
* @template T
|
||||
* @param {(value: T) => void} callback
|
||||
* @param {string} url
|
||||
*/
|
||||
async function fetchJson(callback, url) {
|
||||
/** @type {T | null} */
|
||||
let cachedJson = null;
|
||||
|
||||
/** @type {Cache | undefined} */
|
||||
let cache;
|
||||
/** @type {Response | undefined} */
|
||||
let cachedResponse;
|
||||
try {
|
||||
cache = await caches.open(CACHE_NAME);
|
||||
cachedResponse = await cache.match(url);
|
||||
if (cachedResponse) {
|
||||
console.debug(`cache: ${url}`);
|
||||
const json = /** @type {T} */ (await cachedResponse.json());
|
||||
cachedJson = json;
|
||||
callback(json);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
if (!navigator.onLine) {
|
||||
throw "Offline";
|
||||
}
|
||||
|
||||
console.debug(`fetch: ${url}`);
|
||||
|
||||
const fetchedResponse = await fetch(url, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!fetchedResponse.ok) {
|
||||
throw `Bad response: ${fetchedResponse}`;
|
||||
}
|
||||
|
||||
if (
|
||||
cachedResponse?.headers.get("ETag") ===
|
||||
fetchedResponse.headers.get("ETag")
|
||||
) {
|
||||
return cachedJson;
|
||||
}
|
||||
|
||||
const clonedResponse = fetchedResponse.clone();
|
||||
|
||||
const fetchedJson = /** @type {T} */ (await fetchedResponse.json());
|
||||
if (!fetchedJson) throw `JSON is false`;
|
||||
|
||||
callback(fetchedJson);
|
||||
|
||||
runWhenIdle(async function () {
|
||||
try {
|
||||
await cache?.put(url, clonedResponse);
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
return fetchedJson;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return cachedJson;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Metric} metric
|
||||
* @param {Index} index
|
||||
* @param {number} [from]
|
||||
* @param {number} [to]
|
||||
*/
|
||||
function genMetricURL(metric, index, from, to) {
|
||||
let path = `${origin}api/metrics/${metric.replaceAll("_", "-")}/${index}?`;
|
||||
|
||||
if (from !== undefined) {
|
||||
path += `from=${from}`;
|
||||
}
|
||||
if (to !== undefined) {
|
||||
if (!path.endsWith("?")) {
|
||||
path += `&`;
|
||||
}
|
||||
path += `to=${to}`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {(v: T[]) => void} callback
|
||||
* @param {Index} index
|
||||
* @param {Metric} metric
|
||||
* @param {number} [from]
|
||||
* @param {number} [to]
|
||||
*/
|
||||
function fetchMetric(callback, index, metric, from, to) {
|
||||
return fetchJson(callback, genMetricURL(metric, index, from, to));
|
||||
}
|
||||
|
||||
return {
|
||||
POOL_ID_TO_POOL_NAME,
|
||||
hasMetric,
|
||||
metricToIndexes,
|
||||
|
||||
genMetricURL,
|
||||
fetchMetric,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { INDEX_TO_WORD } from "./generated/metrics";
|
||||
import {
|
||||
INDEX_TO_WORD,
|
||||
COMPRESSED_METRIC_TO_INDEXES,
|
||||
} from "./generated/metrics";
|
||||
|
||||
/** @type {Record<string, number>} */
|
||||
const WORD_TO_INDEX = {};
|
||||
@@ -7,6 +10,20 @@ INDEX_TO_WORD.forEach((word, index) => {
|
||||
WORD_TO_INDEX[word] = index;
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {Metric} metric
|
||||
*/
|
||||
export function metricToIndexes(metric) {
|
||||
return COMPRESSED_METRIC_TO_INDEXES[compressMetric(metric)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Metric} metric
|
||||
*/
|
||||
export function hasMetric(metric) {
|
||||
return compressMetric(metric) in COMPRESSED_METRIC_TO_INDEXES;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} metric
|
||||
*/
|
||||
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* @import { Signal, Signals, Accessor } from "../solidjs-signals/index";
|
||||
*
|
||||
* @import { Index } from "./generated/metrics"
|
||||
*
|
||||
* @typedef {[number, number, number, number]} OHLCTuple
|
||||
* @import { BRKClient } from "./index"
|
||||
*
|
||||
* @typedef {typeof import("./generated/metrics")["COMPRESSED_METRIC_TO_INDEXES"]} MetricToIndexes
|
||||
* @typedef {string} Metric
|
||||
* @typedef {[number, number, number, number]} OHLCTuple
|
||||
*/
|
||||
129
packages/brk-resources/index.js
Normal file
129
packages/brk-resources/index.js
Normal file
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* @import { Signal, Signals } from "../brk-signals/index";
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {ReturnType<createResources>} BRKResources
|
||||
* @typedef {ReturnType<BRKResources["metrics"]["getOrCreate"]>} BRKMetricResource
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {BRKClient} client
|
||||
* @param {Signals} signals
|
||||
*/
|
||||
export function createResources(client, signals) {
|
||||
const owner = signals.getOwner();
|
||||
|
||||
const defaultFrom = -10_000;
|
||||
const defaultTo = undefined;
|
||||
|
||||
/**
|
||||
* @param {Object} [args]
|
||||
* @param {number} [args.from]
|
||||
* @param {number} [args.to]
|
||||
*/
|
||||
function genKey(args) {
|
||||
return `${args?.from ?? defaultFrom}-${args?.to ?? ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {Metric} metric
|
||||
* @param {Index} index
|
||||
*/
|
||||
function createMetricResource(metric, index) {
|
||||
if (client.hasMetric(metric)) {
|
||||
throw Error(`${metric} is invalid`);
|
||||
}
|
||||
|
||||
return signals.runWithOwner(owner, () => {
|
||||
const fetchedRecord = signals.createSignal(
|
||||
/** @type {Map<string, {loading: boolean, at: Date | null, data: Signal<T[] | null>}>} */ (
|
||||
new Map()
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
url: client.genMetricURL(metric, index, defaultFrom),
|
||||
fetched: fetchedRecord,
|
||||
/**
|
||||
* Defaults
|
||||
* - from: -10_000
|
||||
* - to: undefined
|
||||
*
|
||||
* @param {Object} [args]
|
||||
* @param {number} [args.from]
|
||||
* @param {number} [args.to]
|
||||
*/
|
||||
async fetch(args) {
|
||||
const from = args?.from ?? defaultFrom;
|
||||
const to = args?.to ?? defaultTo;
|
||||
const fetchedKey = genKey({ from, to });
|
||||
if (!fetchedRecord().has(fetchedKey)) {
|
||||
fetchedRecord.set((map) => {
|
||||
map.set(fetchedKey, {
|
||||
loading: false,
|
||||
at: null,
|
||||
data: signals.createSignal(/** @type {T[] | null} */ (null), {
|
||||
equals: false,
|
||||
}),
|
||||
});
|
||||
return map;
|
||||
});
|
||||
}
|
||||
const fetched = fetchedRecord().get(fetchedKey);
|
||||
if (!fetched) throw Error("Unreachable");
|
||||
if (fetched.loading) return fetched.data();
|
||||
if (fetched.at) {
|
||||
const diff = new Date().getTime() - fetched.at.getTime();
|
||||
const ONE_MINUTE_IN_MS = 60_000;
|
||||
if (diff < ONE_MINUTE_IN_MS) return fetched.data();
|
||||
}
|
||||
fetched.loading = true;
|
||||
const res = /** @type {T[] | null} */ (
|
||||
await client.fetchMetric(
|
||||
(data) => {
|
||||
if (data.length || !fetched.data()) {
|
||||
fetched.data.set(data);
|
||||
}
|
||||
},
|
||||
index,
|
||||
metric,
|
||||
from,
|
||||
to,
|
||||
)
|
||||
);
|
||||
fetched.at = new Date();
|
||||
fetched.loading = false;
|
||||
return res;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** @type {Map<string, NonNullable<ReturnType<typeof createMetricResource>>>} */
|
||||
const map = new Map();
|
||||
|
||||
const metrics = {
|
||||
/**
|
||||
* @template T
|
||||
* @param {Metric} metric
|
||||
* @param {Index} index
|
||||
*/
|
||||
getOrCreate(metric, index) {
|
||||
const key = `${metric}/${index}`;
|
||||
const found = map.get(key);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
|
||||
const resource = createMetricResource(metric, index);
|
||||
if (!resource) throw Error("metric is undefined");
|
||||
map.set(key, /** @type {any} */ (resource));
|
||||
return resource;
|
||||
},
|
||||
genKey,
|
||||
};
|
||||
|
||||
return { metrics };
|
||||
}
|
||||
3
packages/brk-resources/types.js
Normal file
3
packages/brk-resources/types.js
Normal file
@@ -0,0 +1,3 @@
|
||||
/**
|
||||
* @import { BRKResources, BRKMetricResource } from "./index"
|
||||
*/
|
||||
@@ -1,9 +1,12 @@
|
||||
/**
|
||||
* @import { SignalOptions } from "./0.4.11/dist/types/core/core"
|
||||
* @import { getOwner as GetOwner, onCleanup as OnCleanup } from "./0.4.11/dist/types/core/owner"
|
||||
* @import { createSignal as CreateSignal, createEffect as CreateEffect, createMemo as CreateMemo, createRoot as CreateRoot, runWithOwner as RunWithOwner, Setter } from "./0.4.11/dist/types/signals";
|
||||
* @import { SignalOptions } from "../solidjs-signals/0.6.3/dist/types/core/core"
|
||||
* @import { getOwner as GetOwner, onCleanup as OnCleanup } from "../solidjs-signals/0.6.3/dist/types/core/owner"
|
||||
* @import { createSignal as CreateSignal, createEffect as CreateEffect, createMemo as CreateMemo, createRoot as CreateRoot, runWithOwner as RunWithOwner, Setter } from "../solidjs-signals/0.6.3/dist/types/signals";
|
||||
*/
|
||||
|
||||
// test
|
||||
// wkopwfk
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @typedef {() => T} Accessor
|
||||
@@ -22,7 +25,7 @@ import {
|
||||
createRoot,
|
||||
runWithOwner,
|
||||
onCleanup,
|
||||
} from "./0.4.11/dist/prod.js";
|
||||
} from "../solidjs-signals/0.6.3/dist/prod.js";
|
||||
|
||||
let effectCount = 0;
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
import { runWhenIdle } from "./idle";
|
||||
import { POOL_ID_TO_POOL_NAME } from "./generated/pools";
|
||||
import { createMetricToIndexes } from "./metrics";
|
||||
|
||||
const localhost = window.location.hostname === "localhost";
|
||||
|
||||
/**
|
||||
* @param {Signals} signals
|
||||
*/
|
||||
export default function (signals) {
|
||||
const owner = signals.getOwner();
|
||||
|
||||
const pools = POOL_ID_TO_POOL_NAME;
|
||||
const metricToIndexes = createMetricToIndexes();
|
||||
|
||||
const defaultFrom = -10_000;
|
||||
const defaultTo = undefined;
|
||||
|
||||
/**
|
||||
* Defaults
|
||||
* - from: -10_000
|
||||
* - to: undefined
|
||||
*
|
||||
* @param {Object} [args]
|
||||
* @param {number} [args.from]
|
||||
* @param {number} [args.to]
|
||||
*/
|
||||
function genFetchedKey(args) {
|
||||
return `${args?.from}-${args?.to}`;
|
||||
}
|
||||
|
||||
const defaultFetchedKey = genFetchedKey({ from: defaultFrom, to: defaultTo });
|
||||
|
||||
/**
|
||||
* @template {number | OHLCTuple} [T=number]
|
||||
* @param {Metric} metric
|
||||
* @param {Index} index
|
||||
*/
|
||||
function createMetricResource(metric, index) {
|
||||
if (localhost && !(metric in metricToIndexes)) {
|
||||
throw Error(`${metric} not recognized`);
|
||||
}
|
||||
|
||||
return signals.runWithOwner(owner, () => {
|
||||
const fetchedRecord = signals.createSignal(
|
||||
/** @type {Map<string, {loading: boolean, at: Date | null, vec: Signal<T[] | null>}>} */ (
|
||||
new Map()
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
url: api.genUrl(index, metric, defaultFrom),
|
||||
fetched: fetchedRecord,
|
||||
/**
|
||||
* Defaults
|
||||
* - from: -10_000
|
||||
* - to: undefined
|
||||
*
|
||||
* @param {Object} [args]
|
||||
* @param {number} [args.from]
|
||||
* @param {number} [args.to]
|
||||
*/
|
||||
async fetch(args) {
|
||||
const from = args?.from ?? defaultFrom;
|
||||
const to = args?.to ?? defaultTo;
|
||||
const fetchedKey = genFetchedKey({ from, to });
|
||||
if (!fetchedRecord().has(fetchedKey)) {
|
||||
fetchedRecord.set((map) => {
|
||||
map.set(fetchedKey, {
|
||||
loading: false,
|
||||
at: null,
|
||||
vec: signals.createSignal(/** @type {T[] | null} */ (null), {
|
||||
equals: false,
|
||||
}),
|
||||
});
|
||||
return map;
|
||||
});
|
||||
}
|
||||
const fetched = fetchedRecord().get(fetchedKey);
|
||||
if (!fetched) throw Error("Unreachable");
|
||||
if (fetched.loading) return fetched.vec();
|
||||
if (fetched.at) {
|
||||
const diff = new Date().getTime() - fetched.at.getTime();
|
||||
const ONE_MINUTE_IN_MS = 60_000;
|
||||
if (diff < ONE_MINUTE_IN_MS) return fetched.vec();
|
||||
}
|
||||
fetched.loading = true;
|
||||
const res = /** @type {T[] | null} */ (
|
||||
await fetchVec(
|
||||
(values) => {
|
||||
if (values.length || !fetched.vec()) {
|
||||
fetched.vec.set(values);
|
||||
}
|
||||
},
|
||||
index,
|
||||
metric,
|
||||
from,
|
||||
to,
|
||||
)
|
||||
);
|
||||
fetched.at = new Date();
|
||||
fetched.loading = false;
|
||||
return res;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** @type {Map<string, NonNullable<ReturnType<typeof createMetricResource>>>} */
|
||||
const map = new Map();
|
||||
|
||||
const metrics = {
|
||||
/**
|
||||
* @template {number | OHLCTuple} [T=number]
|
||||
* @param {Metric} metric
|
||||
* @param {Index} index
|
||||
*/
|
||||
getOrCreate(metric, index) {
|
||||
const key = `${metric}/${index}`;
|
||||
const found = map.get(key);
|
||||
if (found) {
|
||||
return found;
|
||||
}
|
||||
|
||||
const vec = createMetricResource(index, metric);
|
||||
if (!vec) throw Error("vec is undefined");
|
||||
map.set(key, /** @type {any} */ (vec));
|
||||
return vec;
|
||||
},
|
||||
genFetchedKey,
|
||||
defaultFetchedKey,
|
||||
};
|
||||
|
||||
return { metrics, pools };
|
||||
}
|
||||
// /** @typedef {ReturnType<typeof createVecsResources>} VecsResources */
|
||||
// /** @typedef {ReturnType<VecsResources["getOrCreate"]>} VecResource */
|
||||
|
||||
const CACHE_NAME = "api";
|
||||
const API_VECS_PREFIX = "/api/vecs";
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {(value: T) => void} callback
|
||||
* @param {string} path
|
||||
*/
|
||||
async function fetchApi(callback, path) {
|
||||
const url = `${API_VECS_PREFIX}${path}`;
|
||||
|
||||
/** @type {T | null} */
|
||||
let cachedJson = null;
|
||||
|
||||
/** @type {Cache | undefined} */
|
||||
let cache;
|
||||
try {
|
||||
cache = await caches.open(CACHE_NAME);
|
||||
const cachedResponse = await cache.match(url);
|
||||
if (cachedResponse) {
|
||||
console.debug(`cache: ${url}`);
|
||||
const json = /** @type {T} */ await cachedResponse.json();
|
||||
cachedJson = json;
|
||||
callback(json);
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (navigator.onLine) {
|
||||
// TODO: rerun after 10s instead of returning (due to some kind of error)
|
||||
|
||||
/** @type {Response | undefined} */
|
||||
let fetchedResponse;
|
||||
try {
|
||||
fetchedResponse = await fetch(url, {
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
if (!fetchedResponse.ok) {
|
||||
throw Error;
|
||||
}
|
||||
} catch {
|
||||
return cachedJson;
|
||||
}
|
||||
|
||||
const clonedResponse = fetchedResponse.clone();
|
||||
|
||||
let fetchedJson = /** @type {T | null} */ (null);
|
||||
try {
|
||||
const f = await fetchedResponse.json();
|
||||
fetchedJson = /** @type {T} */ (f);
|
||||
} catch (_) {
|
||||
return cachedJson;
|
||||
}
|
||||
|
||||
if (!fetchedJson) return cachedJson;
|
||||
|
||||
console.debug(`fetch: ${url}`);
|
||||
|
||||
if (Array.isArray(cachedJson) && Array.isArray(fetchedJson)) {
|
||||
const previousLength = cachedJson?.length || 0;
|
||||
const newLength = fetchedJson.length;
|
||||
|
||||
if (!newLength) {
|
||||
return cachedJson;
|
||||
}
|
||||
|
||||
if (previousLength && previousLength === newLength) {
|
||||
const previousLastValue = Object.values(cachedJson || []).at(-1);
|
||||
const newLastValue = Object.values(fetchedJson).at(-1);
|
||||
if (
|
||||
JSON.stringify(previousLastValue) === JSON.stringify(newLastValue)
|
||||
) {
|
||||
return cachedJson;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callback(fetchedJson);
|
||||
|
||||
runWhenIdle(async function () {
|
||||
try {
|
||||
await cache?.put(url, clonedResponse);
|
||||
} catch (_) {}
|
||||
});
|
||||
|
||||
return fetchedJson;
|
||||
} else {
|
||||
return cachedJson;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Index} index
|
||||
* @param {Metric} metric
|
||||
* @param {number} [from]
|
||||
* @param {number} [to]
|
||||
*/
|
||||
function genPath(index, metric, from, to) {
|
||||
let path = `/${serdeIndex.serialize(index)}-to-${metric.replaceAll("_", "-")}?`;
|
||||
|
||||
if (from !== undefined) {
|
||||
path += `from=${from}`;
|
||||
}
|
||||
if (to !== undefined) {
|
||||
if (!path.endsWith("?")) {
|
||||
path += `&`;
|
||||
}
|
||||
path += `to=${to}`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * @template {number | OHLCTuple} [T=number]
|
||||
// * @param {(v: T[]) => void} callback
|
||||
// * @param {Index} index
|
||||
// * @param {Metric} metric
|
||||
// * @param {number} [from]
|
||||
// * @param {number} [to]
|
||||
// */
|
||||
// function fetchMetric(callback, index, metric, from, to) {
|
||||
// return fetchApi(callback, genPath(index, metric, from, to));
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * @param {Index} index
|
||||
// * @param {Metric} metric
|
||||
// * @param {number} from
|
||||
// */
|
||||
// function genUrl(index, metric, from) {
|
||||
// return `${API_VECS_PREFIX}${genPath(index, metric, from)}`;
|
||||
// }
|
||||
@@ -1,4 +0,0 @@
|
||||
import signals from "../solidjs-signals/index";
|
||||
import brk from "./index";
|
||||
|
||||
export default () => brk(signals);
|
||||
491
packages/lean-qr/2.5.0/index.d.ts
vendored
491
packages/lean-qr/2.5.0/index.d.ts
vendored
@@ -1,491 +0,0 @@
|
||||
declare module 'lean-qr' {
|
||||
interface ImageDataLike {
|
||||
readonly data: Uint8ClampedArray;
|
||||
}
|
||||
|
||||
interface Context2DLike<DataT extends ImageDataLike> {
|
||||
createImageData(width: number, height: number): DataT;
|
||||
putImageData(data: DataT, x: number, y: number): void;
|
||||
}
|
||||
|
||||
interface CanvasLike<DataT extends ImageDataLike> {
|
||||
width: number;
|
||||
height: number;
|
||||
getContext(type: '2d'): Context2DLike<DataT> | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A colour in `[red, green, blue, alpha]` format (all values from 0 to 255).
|
||||
* If alpha is omitted, it is assumed to be 255 (opaque).
|
||||
*/
|
||||
export type RGBA = readonly [number, number, number, number?];
|
||||
|
||||
export interface Bitmap1D {
|
||||
/**
|
||||
* Appends a sequence of bits.
|
||||
*
|
||||
* @param value an integer containing the bits to append (big endian).
|
||||
* @param bits the number of bits to read from `value`. Must be between 1 and 24.
|
||||
*/
|
||||
push(value: number, bits: number): void;
|
||||
}
|
||||
|
||||
export interface StringOptions {
|
||||
/** the text to use for modules which are 'on' (typically black) */
|
||||
on?: string;
|
||||
|
||||
/** the text to use for modules which are 'off' (typically white) */
|
||||
off?: string;
|
||||
|
||||
/** the text to use for linefeeds between rows */
|
||||
lf?: string;
|
||||
|
||||
/** the padding to apply on the left and right of the output (populated with 'off' modules) */
|
||||
padX?: number;
|
||||
|
||||
/** the padding to apply on the top and bottom of the output (populated with 'off' modules) */
|
||||
padY?: number;
|
||||
}
|
||||
|
||||
export interface ImageDataOptions {
|
||||
/** the colour to use for modules which are 'on' (typically black) */
|
||||
on?: RGBA;
|
||||
|
||||
/** the colour to use for modules which are 'off' (typically white) */
|
||||
off?: RGBA;
|
||||
|
||||
/** the padding to apply on the left and right of the output (filled with 'off') */
|
||||
padX?: number;
|
||||
|
||||
/** the padding to apply on the top and bottom of the output (filled with 'off') */
|
||||
padY?: number;
|
||||
}
|
||||
|
||||
export interface Bitmap2D {
|
||||
/** the width / height of the QR code in modules (excluding any padding) */
|
||||
readonly size: number;
|
||||
|
||||
/**
|
||||
* Read the state of a module from the QR code.
|
||||
*
|
||||
* @param x the x coordinate to read. Can be negative / out of bounds.
|
||||
* @param y the y coordinate to read. Can be negative / out of bounds.
|
||||
* @returns true if the requested module is set (i.e. typically black)
|
||||
*/
|
||||
get(x: number, y: number): boolean;
|
||||
|
||||
/**
|
||||
* Generate a string containing the QR code, suitable for displaying in a
|
||||
* terminal environment. Generally, you should customise on and off to use
|
||||
* the ANSI escapes of your target terminal for better rendering.
|
||||
*
|
||||
* @param options optional configuration for the display.
|
||||
*/
|
||||
toString(options?: Readonly<StringOptions>): string;
|
||||
|
||||
/**
|
||||
* Generate image data containing the QR code, at a scale of 1 pixel per
|
||||
* module. Use this if you need more control than toCanvas allows.
|
||||
*
|
||||
* @param context a context to use for creating the image data.
|
||||
* @param options optional configuration for the display.
|
||||
*/
|
||||
toImageData<DataT extends ImageDataLike>(
|
||||
context: Context2DLike<DataT>,
|
||||
options?: Readonly<ImageDataOptions>,
|
||||
): DataT;
|
||||
|
||||
/**
|
||||
* Generate a `data:image/*` URL for the QR code.
|
||||
*
|
||||
* @param options optional configuration for the output.
|
||||
* @returns a string suitable for use as the `src` of an `img` tag.
|
||||
*/
|
||||
toDataURL(
|
||||
options?: Readonly<
|
||||
ImageDataOptions & {
|
||||
type?: `image/${string}`;
|
||||
scale?: number;
|
||||
}
|
||||
>,
|
||||
): string;
|
||||
|
||||
/**
|
||||
* Populate a given canvas with the QR code, at a scale of 1 pixel per
|
||||
* module. Set image-rendering: pixelated and scale the canvas using CSS
|
||||
* for a large image. Automatically resizes the canvas to fit the QR code
|
||||
* if necessary.
|
||||
*
|
||||
* @param canvas the canvas to populate.
|
||||
* @param options optional configuration for the display.
|
||||
*/
|
||||
toCanvas(
|
||||
canvas: CanvasLike<ImageDataLike>,
|
||||
options?: Readonly<ImageDataOptions>,
|
||||
): void;
|
||||
}
|
||||
|
||||
export type Mask = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
||||
export type Mode = (data: Bitmap1D, version: number) => void;
|
||||
export interface ModeFactory {
|
||||
(value: string): Mode;
|
||||
/** a function which returns true when given a character which the current mode can represent */
|
||||
test(string: string): boolean;
|
||||
/** a function which returns an estimate of the number of bits required to encode a given value */
|
||||
est(value: string, version: number): number;
|
||||
/** an optional ECI which must be active for this mode to be interpreted correctly by a reader */
|
||||
eci?: number;
|
||||
}
|
||||
|
||||
interface ModeAutoOptions {
|
||||
/** a list of modes which can be considered when encoding a message */
|
||||
modes?: ReadonlyArray<ModeFactory>;
|
||||
}
|
||||
|
||||
export const mode: Readonly<{
|
||||
/** automatically picks the most optimal combination of modes for the requested message */
|
||||
auto(value: string, options?: Readonly<ModeAutoOptions>): Mode;
|
||||
/** concatenates multiple modes together */
|
||||
multi(...modes: ReadonlyArray<Mode>): Mode;
|
||||
/** sets the Extended Channel Interpretation for the message from this point onwards */
|
||||
eci(id: number): Mode;
|
||||
/** supports `0-9` and stores 3 characters per 10 bits */
|
||||
numeric: ModeFactory;
|
||||
/** supports `0-9A-Z $%*+-./:` and stores 2 characters per 11 bits */
|
||||
alphaNumeric: ModeFactory;
|
||||
/** arbitrary byte data, typically combined with `eci` */
|
||||
bytes(data: Uint8Array | ReadonlyArray<number>): Mode;
|
||||
/** supports 7-bit ASCII and stores 1 character per 8 bits with no ECI */
|
||||
ascii: ModeFactory;
|
||||
/** supports 8-bit ISO-8859-1 and stores 1 character per 8 bits with ECI 3 */
|
||||
iso8859_1: ModeFactory;
|
||||
/** supports double-byte Shift-JIS characters stores 1 character per 13 bits */
|
||||
shift_jis: ModeFactory;
|
||||
/** supports variable length UTF-8 with ECI 26 */
|
||||
utf8: ModeFactory;
|
||||
}>;
|
||||
|
||||
export type Correction = number & { readonly _: unique symbol };
|
||||
export const correction: Readonly<{
|
||||
/** minimum possible correction level (same as L) */
|
||||
min: Correction;
|
||||
/** ~7.5% error tolerance, ~25% data overhead */
|
||||
L: Correction;
|
||||
/** ~15% error tolerance, ~60% data overhead */
|
||||
M: Correction;
|
||||
/** ~22.5% error tolerance, ~120% data overhead */
|
||||
Q: Correction;
|
||||
/** ~30% error tolerance, ~190% data overhead */
|
||||
H: Correction;
|
||||
/** maximum possible correction level (same as H) */
|
||||
max: Correction;
|
||||
}>;
|
||||
|
||||
export interface GenerateOptions extends ModeAutoOptions {
|
||||
/** the minimum correction level to use (higher levels may still be used if the chosen version has space) */
|
||||
minCorrectionLevel?: Correction;
|
||||
/** the maximum correction level to use */
|
||||
maxCorrectionLevel?: Correction;
|
||||
/** the minimum version (size) of code to generate (must be between 1 and 40) */
|
||||
minVersion?: number;
|
||||
/** the maximum version (size) of code to generate (must be between 1 and 40) */
|
||||
maxVersion?: number;
|
||||
/** a mask to use on the QR code (should be left as `null` for ISO compliance but may be changed for artistic effect) */
|
||||
mask?: null | Mask;
|
||||
/** padding bits to use for extra space in the QR code (should be left as the default for ISO compliance but may be changed for artistic effect) */
|
||||
trailer?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a QR code.
|
||||
*
|
||||
* @param data either a string, or a pre-encoded mode.
|
||||
* @param options optional configuration for the QR code.
|
||||
* @returns the requested QR code.
|
||||
*/
|
||||
export type GenerateFn = (
|
||||
data: Mode | string,
|
||||
options?: Readonly<GenerateOptions>,
|
||||
) => Bitmap2D;
|
||||
interface Generate extends GenerateFn {
|
||||
/**
|
||||
* Creates a scoped `generate` function which considers additional modes
|
||||
* when using auto encoding.
|
||||
*
|
||||
* @param modes the modes to add.
|
||||
* @returns a `generate` function which will additionally consider the
|
||||
* given modes when using auto encoding.
|
||||
*/
|
||||
with(...modes: ReadonlyArray<ModeFactory>): GenerateFn;
|
||||
}
|
||||
export const generate: Generate;
|
||||
}
|
||||
|
||||
declare module 'lean-qr/nano' {
|
||||
import type {
|
||||
Correction,
|
||||
Bitmap2D as FullBitmap2D,
|
||||
GenerateOptions as FullGenerateOptions,
|
||||
} from 'lean-qr';
|
||||
import { correction as fullCorrection } from 'lean-qr';
|
||||
|
||||
export type { Correction };
|
||||
|
||||
export const correction: Pick<typeof fullCorrection, 'L' | 'M' | 'Q' | 'H'>;
|
||||
|
||||
export type Bitmap2D = Pick<FullBitmap2D, 'size' | 'get' | 'toCanvas'>;
|
||||
|
||||
export type GenerateOptions = Pick<
|
||||
FullGenerateOptions,
|
||||
'minCorrectionLevel' | 'minVersion'
|
||||
>;
|
||||
|
||||
/**
|
||||
* Generate a QR code.
|
||||
*
|
||||
* @param data either a string, or a pre-encoded mode.
|
||||
* @param options optional configuration for the QR code.
|
||||
* @returns the requested QR code.
|
||||
*/
|
||||
export function generate(
|
||||
data: string,
|
||||
options?: Readonly<GenerateOptions>,
|
||||
): Bitmap2D;
|
||||
}
|
||||
|
||||
declare module 'lean-qr/extras/svg' {
|
||||
import type { Bitmap2D as FullBitmap2D } from 'lean-qr';
|
||||
|
||||
type Bitmap2D = Pick<FullBitmap2D, 'size' | 'get'>;
|
||||
|
||||
export interface SVGOptions {
|
||||
/** the colour to use for modules which are 'on' (typically black) */
|
||||
on?: string;
|
||||
/** the colour to use for modules which are 'off' (typically white) */
|
||||
off?: string;
|
||||
/** the padding to apply on the left and right of the output (filled with 'off') */
|
||||
padX?: number;
|
||||
/** the padding to apply on the top and bottom of the output (filled with 'off') */
|
||||
padY?: number;
|
||||
/** a width to apply to the resulting image (overrides `scale`) */
|
||||
width?: number | null;
|
||||
/** a height to apply to the resulting image (overrides `scale`) */
|
||||
height?: number | null;
|
||||
/** a scale to apply to the resulting image (`scale` pixels = 1 module) */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the raw outline of the QR code for use in an existing SVG.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @returns a string suitable for passing to the `d` attribute of a `path`.
|
||||
*/
|
||||
export function toSvgPath(code: Bitmap2D): string;
|
||||
|
||||
/**
|
||||
* Generate an SVG element which can be added to the DOM.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @param options optional configuration for the display.
|
||||
* @returns an SVG element.
|
||||
*/
|
||||
export function toSvg(
|
||||
code: Bitmap2D,
|
||||
target: Document | SVGElement,
|
||||
options?: Readonly<SVGOptions>,
|
||||
): SVGElement;
|
||||
|
||||
/**
|
||||
* Generate an SVG document which can be exported to a file or served from a
|
||||
* web server.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @param options optional configuration for the display.
|
||||
* @returns an SVG document.
|
||||
*/
|
||||
export function toSvgSource(
|
||||
code: Bitmap2D,
|
||||
options?: Readonly<
|
||||
SVGOptions & {
|
||||
/** `true` to include an XML declaration at the start of the source (for standalone documents which will not be embedded inside another document) */
|
||||
xmlDeclaration?: boolean;
|
||||
}
|
||||
>,
|
||||
): string;
|
||||
|
||||
/**
|
||||
* Generate a `data:image/svg+xml` URL.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @param options optional configuration for the display.
|
||||
* @returns a string suitable for use as the `src` of an `img` tag.
|
||||
*/
|
||||
export function toSvgDataURL(
|
||||
code: Bitmap2D,
|
||||
options?: Readonly<SVGOptions>,
|
||||
): string;
|
||||
}
|
||||
|
||||
declare module 'lean-qr/extras/node_export' {
|
||||
import type { RGBA, Bitmap2D as FullBitmap2D } from 'lean-qr';
|
||||
|
||||
type Bitmap2D = Pick<FullBitmap2D, 'size' | 'get'>;
|
||||
|
||||
export interface PNGOptions {
|
||||
/** the colour to use for modules which are 'on' (typically black) */
|
||||
on?: RGBA;
|
||||
/** the colour to use for modules which are 'off' (typically white) */
|
||||
off?: RGBA;
|
||||
/** the padding to apply on the left and right of the output (filled with 'off') */
|
||||
padX?: number;
|
||||
/** the padding to apply on the top and bottom of the output (filled with 'off') */
|
||||
padY?: number;
|
||||
/** a scale to apply to the resulting image (`scale` pixels = 1 module) */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a PNG document which can be exported to a file or served from a
|
||||
* web server.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @param options optional configuration for the display.
|
||||
* @returns a PNG document.
|
||||
*/
|
||||
export function toPngBuffer(
|
||||
code: Bitmap2D,
|
||||
options?: Readonly<PNGOptions>,
|
||||
): Uint8Array;
|
||||
|
||||
/**
|
||||
* Generate a `data:image/png` URL.
|
||||
*
|
||||
* @param code the QR code to convert.
|
||||
* @param options optional configuration for the display.
|
||||
* @returns a string suitable for use as the `src` of an `img` tag.
|
||||
*/
|
||||
export function toPngDataURL(
|
||||
code: Bitmap2D,
|
||||
options?: Readonly<PNGOptions>,
|
||||
): string;
|
||||
}
|
||||
|
||||
declare module 'lean-qr/extras/react' {
|
||||
import type {
|
||||
Bitmap2D as FullBitmap2D,
|
||||
GenerateOptions,
|
||||
ImageDataOptions,
|
||||
} from 'lean-qr';
|
||||
import type {
|
||||
SVGOptions,
|
||||
toSvgDataURL as toSvgDataURLFn,
|
||||
} from 'lean-qr/extras/svg';
|
||||
|
||||
export interface AsyncFramework<T> {
|
||||
createElement: (
|
||||
type: 'canvas',
|
||||
props: {
|
||||
ref: any;
|
||||
style: { imageRendering: 'pixelated' };
|
||||
className: string;
|
||||
},
|
||||
) => T;
|
||||
useRef<T>(initialValue: T | null): { readonly current: T | null };
|
||||
useEffect(fn: () => void | (() => void), deps: unknown[]): void;
|
||||
}
|
||||
|
||||
interface QRComponentProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export interface AsyncQRComponentProps
|
||||
extends ImageDataOptions,
|
||||
GenerateOptions,
|
||||
QRComponentProps {}
|
||||
|
||||
export type AsyncQRComponent<T> = (
|
||||
props: Readonly<AsyncQRComponentProps>,
|
||||
) => T;
|
||||
|
||||
/**
|
||||
* Generate an asynchronous QR component (rendering to a `canvas`).
|
||||
* You should call this just once, in the global scope.
|
||||
*
|
||||
* This is not suitable for server-side rendering (use `makeSyncComponent`
|
||||
* instead).
|
||||
*
|
||||
* @param framework the framework to use (e.g. `React`).
|
||||
* @param generate the `generate` function to use
|
||||
* (from `lean-qr` or `lean-qr/nano`).
|
||||
* @param defaultProps optional default properties to apply when the
|
||||
* component is used (overridden by properties set on use).
|
||||
* @returns a component which can be rendered elsewhere.
|
||||
*/
|
||||
export function makeAsyncComponent<T>(
|
||||
framework: Readonly<AsyncFramework<T>>,
|
||||
generate: (
|
||||
data: string,
|
||||
options?: Readonly<GenerateOptions>,
|
||||
) => Pick<FullBitmap2D, 'toCanvas'>,
|
||||
defaultProps?: Readonly<Partial<AsyncQRComponentProps>>,
|
||||
): AsyncQRComponent<T>;
|
||||
|
||||
export interface SyncFramework<T> {
|
||||
createElement: (
|
||||
type: 'img',
|
||||
props: {
|
||||
src: string;
|
||||
style: { imageRendering: 'pixelated' };
|
||||
className: string;
|
||||
},
|
||||
) => T;
|
||||
useMemo<T>(fn: () => T, deps: unknown[]): T;
|
||||
}
|
||||
|
||||
export interface SyncQRComponentProps
|
||||
extends SVGOptions,
|
||||
GenerateOptions,
|
||||
QRComponentProps {}
|
||||
|
||||
export type SyncQRComponent<T> = (props: Readonly<SyncQRComponentProps>) => T;
|
||||
|
||||
/**
|
||||
* Generate a synchronous QR component (rendering to an SVG).
|
||||
* You should call this just once, in the global scope.
|
||||
*
|
||||
* This is best suited for server-side rendering (prefer
|
||||
* `makeAsyncComponent` if you only need client-side rendering).
|
||||
*
|
||||
* @param framework the framework to use (e.g. `React`).
|
||||
* @param generate the `generate` function to use
|
||||
* (from `lean-qr` or `lean-qr/nano`).
|
||||
* @param toSvgDataURL the `toSvgDataURL` function to use
|
||||
* (from `lean-qr/extras/svg`).
|
||||
* @param defaultProps optional default properties to apply when the
|
||||
* component is used (overridden by properties set on use).
|
||||
* @returns a component which can be rendered elsewhere.
|
||||
*/
|
||||
export function makeSyncComponent<T>(
|
||||
framework: Readonly<SyncFramework<T>>,
|
||||
generate: (
|
||||
data: string,
|
||||
options?: Readonly<GenerateOptions>,
|
||||
) => Pick<FullBitmap2D, 'size' | 'get'>,
|
||||
toSvgDataURL: typeof toSvgDataURLFn,
|
||||
defaultProps?: Readonly<Partial<SyncQRComponentProps>>,
|
||||
): SyncQRComponent<T>;
|
||||
}
|
||||
|
||||
declare module 'lean-qr/extras/errors' {
|
||||
/**
|
||||
* Convert an error into a human-readable message. This is intended for use
|
||||
* with Lean QR errors, but will return somewhat meaningful messages for
|
||||
* other errors too.
|
||||
*
|
||||
* @param error the error to convert.
|
||||
* @returns a human-readable message explaining the error.
|
||||
*/
|
||||
export function readError(error: unknown): string;
|
||||
}
|
||||
1
packages/lean-qr/2.5.0/index.mjs
vendored
1
packages/lean-qr/2.5.0/index.mjs
vendored
File diff suppressed because one or more lines are too long
2395
packages/solidjs-signals/0.4.11/dist/prod.js
vendored
2395
packages/solidjs-signals/0.4.11/dist/prod.js
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,22 +0,0 @@
|
||||
import { Computation, Queue } from "./core/index.js";
|
||||
import type { Effect } from "./core/index.js";
|
||||
export declare class CollectionQueue extends Queue {
|
||||
_collectionType: number;
|
||||
_nodes: Set<Effect>;
|
||||
_disabled: Computation<boolean>;
|
||||
constructor(type: number);
|
||||
run(type: number): void;
|
||||
notify(node: Effect, type: number, flags: number): any;
|
||||
merge(queue: CollectionQueue): void;
|
||||
}
|
||||
export declare enum BoundaryMode {
|
||||
VISIBLE = "visible",
|
||||
HIDDEN = "hidden"
|
||||
}
|
||||
export declare function createBoundary<T>(fn: () => T, condition: () => BoundaryMode): () => T | undefined;
|
||||
export declare function createSuspense(fn: () => any, fallback: () => any): () => any;
|
||||
export declare function createErrorBoundary<U>(fn: () => any, fallback: (error: unknown, reset: () => void) => U): () => any;
|
||||
export declare function flatten(children: any, options?: {
|
||||
skipNonRendered?: boolean;
|
||||
doNotUnwrap?: boolean;
|
||||
}): any;
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* See https://dev.to/modderme123/super-charging-fine-grained-reactive-performance-47ph
|
||||
* State clean corresponds to a node where all the sources are fully up to date
|
||||
* State check corresponds to a node where some sources (including grandparents) may have changed
|
||||
* State dirty corresponds to a node where the direct parents of a node has changed
|
||||
*/
|
||||
export declare const STATE_CLEAN = 0;
|
||||
export declare const STATE_CHECK = 1;
|
||||
export declare const STATE_DIRTY = 2;
|
||||
export declare const STATE_DISPOSED = 3;
|
||||
export declare const EFFECT_PURE = 0;
|
||||
export declare const EFFECT_RENDER = 1;
|
||||
export declare const EFFECT_USER = 2;
|
||||
export declare const SUPPORTS_PROXY: boolean;
|
||||
@@ -1,162 +0,0 @@
|
||||
/**
|
||||
* Nodes for constructing a graph of reactive values and reactive computations.
|
||||
*
|
||||
* - The graph is acyclic.
|
||||
* - The user inputs new values into the graph by calling .write() on one more computation nodes.
|
||||
* - The user retrieves computed results from the graph by calling .read() on one or more computation nodes.
|
||||
* - The library is responsible for running any necessary computations so that .read() is up to date
|
||||
* with all prior .write() calls anywhere in the graph.
|
||||
* - We call the input nodes 'roots' and the output nodes 'leaves' of the graph here.
|
||||
* - Changes flow from roots to leaves. It would be effective but inefficient to immediately
|
||||
* propagate all changes from a root through the graph to descendant leaves. Instead, we defer
|
||||
* change most change propagation computation until a leaf is accessed. This allows us to
|
||||
* coalesce computations and skip altogether recalculating unused sections of the graph.
|
||||
* - Each computation node tracks its sources and its observers (observers are other
|
||||
* elements that have this node as a source). Source and observer links are updated automatically
|
||||
* as observer computations re-evaluate and call get() on their sources.
|
||||
* - Each node stores a cache state (clean/check/dirty) to support the change propagation algorithm:
|
||||
*
|
||||
* In general, execution proceeds in three passes:
|
||||
*
|
||||
* 1. write() propagates changes down the graph to the leaves
|
||||
* direct children are marked as dirty and their deeper descendants marked as check
|
||||
* (no computations are evaluated)
|
||||
* 2. read() requests that parent nodes updateIfNecessary(), which proceeds recursively up the tree
|
||||
* to decide whether the node is clean (parents unchanged) or dirty (parents changed)
|
||||
* 3. updateIfNecessary() evaluates the computation if the node is dirty (the computations are
|
||||
* executed in root to leaf order)
|
||||
*/
|
||||
import { type Flags } from "./flags.js";
|
||||
import { Owner } from "./owner.js";
|
||||
import { type Transition } from "./scheduler.js";
|
||||
export interface SignalOptions<T> {
|
||||
id?: string;
|
||||
name?: string;
|
||||
equals?: ((prev: T, next: T) => boolean) | false;
|
||||
pureWrite?: boolean;
|
||||
unobserved?: () => void;
|
||||
}
|
||||
export interface SourceType {
|
||||
_observers: ObserverType[] | null;
|
||||
_unobserved?: () => void;
|
||||
_updateIfNecessary: () => void;
|
||||
_stateFlags: Flags;
|
||||
_time: number;
|
||||
_transition?: Transition;
|
||||
_cloned?: Computation;
|
||||
}
|
||||
export interface ObserverType {
|
||||
_sources: SourceType[] | null;
|
||||
_notify: (state: number, skipQueue?: boolean) => void;
|
||||
_handlerMask: Flags;
|
||||
_notifyFlags: (mask: Flags, newFlags: Flags) => void;
|
||||
_time: number;
|
||||
_cloned?: Computation;
|
||||
}
|
||||
/**
|
||||
* Returns the current observer.
|
||||
*/
|
||||
export declare function getObserver(): Computation | null;
|
||||
export declare const UNCHANGED: unique symbol;
|
||||
export type UNCHANGED = typeof UNCHANGED;
|
||||
export declare class Computation<T = any> extends Owner implements SourceType, ObserverType {
|
||||
_sources: SourceType[] | null;
|
||||
_observers: ObserverType[] | null;
|
||||
_value: T | undefined;
|
||||
_error: unknown;
|
||||
_compute: null | ((p?: T) => T);
|
||||
_name: string | undefined;
|
||||
_equals: false | ((a: T, b: T) => boolean);
|
||||
_unobserved: (() => void) | undefined;
|
||||
_pureWrite: boolean;
|
||||
/** Whether the computation is an error or has ancestors that are unresolved */
|
||||
_stateFlags: number;
|
||||
/** Which flags raised by sources are handled, vs. being passed through. */
|
||||
_handlerMask: number;
|
||||
_time: number;
|
||||
_forceNotify: boolean;
|
||||
_transition?: Transition | undefined;
|
||||
_cloned?: Computation;
|
||||
constructor(initialValue: T | undefined, compute: null | ((p?: T) => T), options?: SignalOptions<T>);
|
||||
_read(): T;
|
||||
/**
|
||||
* Return the current value of this computation
|
||||
* Automatically re-executes the surrounding computation when the value changes
|
||||
*/
|
||||
read(): T;
|
||||
/**
|
||||
* Return the current value of this computation
|
||||
* Automatically re-executes the surrounding computation when the value changes
|
||||
*
|
||||
* If the computation has any unresolved ancestors, this function waits for the value to resolve
|
||||
* before continuing
|
||||
*/
|
||||
wait(): T;
|
||||
/** Update the computation with a new value. */
|
||||
write(value: T | ((currentValue: T) => T) | UNCHANGED, flags?: number, raw?: boolean): T;
|
||||
/**
|
||||
* Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
|
||||
*/
|
||||
_notify(state: number, skipQueue?: boolean): void;
|
||||
/**
|
||||
* Notify the computation that one of its sources has changed flags.
|
||||
*
|
||||
* @param mask A bitmask for which flag(s) were changed.
|
||||
* @param newFlags The source's new flags, masked to just the changed ones.
|
||||
*/
|
||||
_notifyFlags(mask: Flags, newFlags: Flags): void;
|
||||
_setError(error: unknown): void;
|
||||
/**
|
||||
* This is the core part of the reactivity system, which makes sure that the values are updated
|
||||
* before they are read. We've also adapted it to return the loading state of the computation,
|
||||
* so that we can propagate that to the computation's observers.
|
||||
*
|
||||
* This function will ensure that the value and states we read from the computation are up to date
|
||||
*/
|
||||
_updateIfNecessary(): void;
|
||||
/**
|
||||
* Remove ourselves from the owner graph and the computation graph
|
||||
*/
|
||||
_disposeNode(): void;
|
||||
}
|
||||
/**
|
||||
* Reruns a computation's _compute function, producing a new value and keeping track of dependencies.
|
||||
*
|
||||
* It handles the updating of sources and observers, disposal of previous executions,
|
||||
* and error handling if the _compute function throws. It also sets the node as loading
|
||||
* if it reads any parents that are currently loading.
|
||||
*/
|
||||
export declare function update<T>(node: Computation<T>): void;
|
||||
export declare function isEqual<T>(a: T, b: T): boolean;
|
||||
/**
|
||||
* Returns the current value stored inside the given compute function without triggering any
|
||||
* dependencies. Use `untrack` if you want to also disable owner tracking.
|
||||
*/
|
||||
export declare function untrack<T>(fn: () => T): T;
|
||||
/**
|
||||
* Returns true if the given functinon contains signals that have been updated since the last time
|
||||
* the parent computation was run.
|
||||
*/
|
||||
export declare function hasUpdated(fn: () => any): boolean;
|
||||
/**
|
||||
* Returns an accessor that is true if the given function contains async signals that are out of date.
|
||||
*/
|
||||
export declare function isPending(fn: () => any): boolean;
|
||||
export declare function isPending(fn: () => any, loadingValue: boolean): boolean;
|
||||
/**
|
||||
* Attempts to resolve value of expression synchronously returning the last resolved value for any async computation.
|
||||
*/
|
||||
export declare function latest<T>(fn: () => T): T;
|
||||
export declare function latest<T, U>(fn: () => T, fallback: U): T | U;
|
||||
/**
|
||||
* Runs the given function in the given observer.
|
||||
*
|
||||
* Warning: Usually there are simpler ways of modeling a problem that avoid using this function
|
||||
*/
|
||||
export declare function runWithObserver<T>(observer: Computation, run: () => T): T | undefined;
|
||||
/**
|
||||
* A convenient wrapper that calls `compute` with the `owner` and `observer` and is guaranteed
|
||||
* to reset the global context after the computation is finished even if an error is thrown.
|
||||
*/
|
||||
export declare function compute<T>(owner: Owner | null, fn: (val: T) => T, observer: Computation<T>): T;
|
||||
export declare function compute<T>(owner: Owner | null, fn: (val: undefined) => T, observer: null): T;
|
||||
@@ -1,39 +0,0 @@
|
||||
import { EFFECT_RENDER, EFFECT_USER } from "./constants.js";
|
||||
import { Computation, type SignalOptions } from "./core.js";
|
||||
import { type Flags } from "./flags.js";
|
||||
/**
|
||||
* Effects are the leaf nodes of our reactive graph. When their sources change, they are
|
||||
* automatically added to the queue of effects to re-execute, which will cause them to fetch their
|
||||
* sources and recompute
|
||||
*/
|
||||
export declare class Effect<T = any> extends Computation<T> {
|
||||
_effect: (val: T, prev: T | undefined) => void | (() => void);
|
||||
_onerror: ((err: unknown, cleanup: () => void) => void) | undefined;
|
||||
_cleanup: (() => void) | undefined;
|
||||
_modified: boolean;
|
||||
_prevValue: T | undefined;
|
||||
_type: typeof EFFECT_RENDER | typeof EFFECT_USER;
|
||||
constructor(initialValue: T, compute: (val?: T) => T, effect: (val: T, prev: T | undefined) => void | (() => void), error?: (err: unknown) => void | (() => void), options?: SignalOptions<T> & {
|
||||
render?: boolean;
|
||||
defer?: boolean;
|
||||
});
|
||||
write(value: T, flags?: number): T;
|
||||
_notify(state: number, skipQueue?: boolean): void;
|
||||
_notifyFlags(mask: Flags, newFlags: Flags): void;
|
||||
_setError(error: unknown): void;
|
||||
_disposeNode(): void;
|
||||
_run(type: number): void;
|
||||
}
|
||||
export declare class EagerComputation<T = any> extends Computation<T> {
|
||||
constructor(initialValue: T, compute: () => T, options?: SignalOptions<T> & {
|
||||
defer?: boolean;
|
||||
});
|
||||
_notify(state: number, skipQueue?: boolean): void;
|
||||
_run(): void;
|
||||
}
|
||||
export declare class FirewallComputation extends Computation {
|
||||
firewall: boolean;
|
||||
constructor(compute: () => void);
|
||||
_notify(state: number, skipQueue?: boolean): void;
|
||||
_run(): void;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export declare class NotReadyError extends Error {
|
||||
}
|
||||
export declare class NoOwnerError extends Error {
|
||||
constructor();
|
||||
}
|
||||
export declare class ContextNotFoundError extends Error {
|
||||
constructor();
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
export type Flags = number;
|
||||
export declare const ERROR_OFFSET = 0;
|
||||
export declare const ERROR_BIT: number;
|
||||
export declare const ERROR: unique symbol;
|
||||
export declare const LOADING_OFFSET = 1;
|
||||
export declare const LOADING_BIT: number;
|
||||
export declare const LOADING: unique symbol;
|
||||
export declare const UNINITIALIZED_OFFSET = 2;
|
||||
export declare const UNINITIALIZED_BIT: number;
|
||||
export declare const UNINITIALIZED: unique symbol;
|
||||
export declare const DEFAULT_FLAGS: number;
|
||||
@@ -1,7 +0,0 @@
|
||||
export { ContextNotFoundError, NoOwnerError, NotReadyError } from "./error.js";
|
||||
export { Owner, createContext, getContext, setContext, hasContext, getOwner, onCleanup, type Context, type ContextRecord, type Disposable } from "./owner.js";
|
||||
export { Computation, getObserver, isEqual, untrack, hasUpdated, isPending, latest, UNCHANGED, compute, runWithObserver, type SignalOptions } from "./core.js";
|
||||
export { Effect, EagerComputation } from "./effect.js";
|
||||
export { flush, Queue, incrementClock, transition, ActiveTransition, type IQueue } from "./scheduler.js";
|
||||
export * from "./constants.js";
|
||||
export * from "./flags.js";
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* Owner tracking is used to enable nested tracking scopes with automatic cleanup.
|
||||
* We also use owners to also keep track of which error handling context we are in.
|
||||
*
|
||||
* If you write the following
|
||||
*
|
||||
* const a = createOwner(() => {
|
||||
* const b = createOwner(() => {});
|
||||
*
|
||||
* const c = createOwner(() => {
|
||||
* const d = createOwner(() => {});
|
||||
* });
|
||||
*
|
||||
* const e = createOwner(() => {});
|
||||
* });
|
||||
*
|
||||
* The owner tree will look like this:
|
||||
*
|
||||
* a
|
||||
* /|\
|
||||
* b-c-e
|
||||
* |
|
||||
* d
|
||||
*
|
||||
* Following the _nextSibling pointers of each owner will first give you its children, and then its siblings (in reverse).
|
||||
* a -> e -> c -> d -> b
|
||||
*
|
||||
* Note that the owner tree is largely orthogonal to the reactivity tree, and is much closer to the component tree.
|
||||
*/
|
||||
import { type IQueue } from "./scheduler.js";
|
||||
export type ContextRecord = Record<string | symbol, unknown>;
|
||||
export interface Disposable {
|
||||
(): void;
|
||||
}
|
||||
/**
|
||||
* Returns the currently executing parent owner.
|
||||
*/
|
||||
export declare function getOwner(): Owner | null;
|
||||
export declare function setOwner(owner: Owner | null): Owner | null;
|
||||
export declare class Owner {
|
||||
_parent: Owner | null;
|
||||
_nextSibling: Owner | null;
|
||||
_prevSibling: Owner | null;
|
||||
_state: number;
|
||||
_disposal: Disposable | Disposable[] | null;
|
||||
_context: ContextRecord;
|
||||
_queue: IQueue;
|
||||
_childCount: number;
|
||||
id: string | null;
|
||||
constructor(id?: string | null, skipAppend?: boolean);
|
||||
append(child: Owner): void;
|
||||
dispose(this: Owner, self?: boolean): void;
|
||||
_disposeNode(): void;
|
||||
emptyDisposal(): void;
|
||||
getNextChildId(): string;
|
||||
}
|
||||
export interface Context<T> {
|
||||
readonly id: symbol;
|
||||
readonly defaultValue: T | undefined;
|
||||
}
|
||||
/**
|
||||
* Context provides a form of dependency injection. It is used to save from needing to pass
|
||||
* data as props through intermediate components. This function creates a new context object
|
||||
* that can be used with `getContext` and `setContext`.
|
||||
*
|
||||
* A default value can be provided here which will be used when a specific value is not provided
|
||||
* via a `setContext` call.
|
||||
*/
|
||||
export declare function createContext<T>(defaultValue?: T, description?: string): Context<T>;
|
||||
/**
|
||||
* Attempts to get a context value for the given key.
|
||||
*
|
||||
* @throws `NoOwnerError` if there's no owner at the time of call.
|
||||
* @throws `ContextNotFoundError` if a context value has not been set yet.
|
||||
*/
|
||||
export declare function getContext<T>(context: Context<T>, owner?: Owner | null): T;
|
||||
/**
|
||||
* Attempts to set a context value on the parent scope with the given key.
|
||||
*
|
||||
* @throws `NoOwnerError` if there's no owner at the time of call.
|
||||
*/
|
||||
export declare function setContext<T>(context: Context<T>, value?: T, owner?: Owner | null): void;
|
||||
/**
|
||||
* Whether the given context is currently defined.
|
||||
*/
|
||||
export declare function hasContext(context: Context<any>, owner?: Owner | null): boolean;
|
||||
/**
|
||||
* Runs an effect once before the reactive scope is disposed
|
||||
* @param fn an effect that should run only once on cleanup
|
||||
*
|
||||
* @returns the same {@link fn} function that was passed in
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/lifecycle/on-cleanup
|
||||
*/
|
||||
export declare function onCleanup(fn: Disposable): Disposable;
|
||||
@@ -1,85 +0,0 @@
|
||||
import type { Computation, ObserverType, SourceType } from "./core.js";
|
||||
import type { Effect } from "./effect.js";
|
||||
export declare let clock: number;
|
||||
export declare function incrementClock(): void;
|
||||
export declare let ActiveTransition: Transition | null;
|
||||
export declare let Unobserved: SourceType[];
|
||||
export type QueueCallback = (type: number) => void;
|
||||
export interface IQueue {
|
||||
enqueue(type: number, fn: QueueCallback): void;
|
||||
run(type: number): boolean | void;
|
||||
flush(): void;
|
||||
addChild(child: IQueue): void;
|
||||
removeChild(child: IQueue): void;
|
||||
created: number;
|
||||
notify(...args: any[]): boolean;
|
||||
merge(queue: IQueue): void;
|
||||
_parent: IQueue | null;
|
||||
_cloned?: IQueue | undefined;
|
||||
}
|
||||
export declare class Queue implements IQueue {
|
||||
_parent: IQueue | null;
|
||||
_running: boolean;
|
||||
_queues: [QueueCallback[], QueueCallback[]];
|
||||
_children: IQueue[];
|
||||
created: number;
|
||||
enqueue(type: number, fn: QueueCallback): void;
|
||||
run(type: number): void;
|
||||
flush(): void;
|
||||
addChild(child: IQueue): any;
|
||||
removeChild(child: IQueue): any;
|
||||
notify(...args: any[]): any;
|
||||
merge(queue: Queue): void;
|
||||
}
|
||||
export declare const globalQueue: Queue;
|
||||
/**
|
||||
* By default, changes are batched on the microtask queue which is an async process. You can flush
|
||||
* the queue synchronously to get the latest updates by calling `flush()`.
|
||||
*/
|
||||
export declare function flush(): void;
|
||||
export declare function removeSourceObservers(node: ObserverType, index: number): void;
|
||||
export declare class Transition implements IQueue {
|
||||
_sources: Map<Computation, Computation>;
|
||||
_pendingNodes: Set<Effect>;
|
||||
_promises: Set<Promise<any>>;
|
||||
_optimistic: Set<(() => void) & {
|
||||
_transition?: Transition;
|
||||
}>;
|
||||
_done: Transition | boolean;
|
||||
_queues: [QueueCallback[], QueueCallback[]];
|
||||
_clonedQueues: Map<Queue, Queue>;
|
||||
_pureQueue: QueueCallback[];
|
||||
_children: IQueue[];
|
||||
_parent: IQueue | null;
|
||||
_running: boolean;
|
||||
_scheduled: boolean;
|
||||
_cloned: Queue;
|
||||
created: number;
|
||||
constructor();
|
||||
enqueue(type: number, fn: QueueCallback): void;
|
||||
run(type: number): void;
|
||||
flush(): void;
|
||||
addChild(child: IQueue): void;
|
||||
removeChild(child: IQueue): void;
|
||||
notify(node: Effect, type: number, flags: number): boolean;
|
||||
merge(queue: Transition): void;
|
||||
schedule(): void;
|
||||
runTransition(fn: () => any | Promise<any>, force?: boolean): void;
|
||||
addOptimistic(fn: (() => void) & {
|
||||
_transition?: Transition;
|
||||
}): void;
|
||||
}
|
||||
/**
|
||||
* Runs the given function in a transition scope, allowing for batch updates and optimizations.
|
||||
* This is useful for grouping multiple state updates together to avoid unnecessary re-renders.
|
||||
*
|
||||
* @param fn A function that receives a resume function to continue the transition.
|
||||
* The resume function can be called with another function to continue the transition.
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/advanced-reactivity/transition
|
||||
*/
|
||||
export declare function transition(fn: (resume: (fn: () => any | Promise<any>) => void) => any | Promise<any>): void;
|
||||
export declare function cloneGraph(node: Computation): Computation;
|
||||
export declare function getOGSource<T extends Computation>(input: T): T;
|
||||
export declare function getTransitionSource<T extends Computation>(input: T): T;
|
||||
export declare function initialDispose(node: any): void;
|
||||
@@ -1,6 +0,0 @@
|
||||
export { Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, Queue, createContext, flush, getContext, setContext, hasContext, getOwner, onCleanup, getObserver, isEqual, untrack, hasUpdated, isPending, latest, runWithObserver, transition, SUPPORTS_PROXY } from "./core/index.js";
|
||||
export type { SignalOptions, Context, ContextRecord, Disposable, IQueue } from "./core/index.js";
|
||||
export { mapArray, repeat, type Maybe } from "./map.js";
|
||||
export * from "./signals.js";
|
||||
export * from "./store/index.js";
|
||||
export { createSuspense, createErrorBoundary, createBoundary, flatten, type BoundaryMode } from "./boundaries.js";
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { Accessor } from "./signals.js";
|
||||
export type Maybe<T> = T | void | null | undefined | false;
|
||||
/**
|
||||
* Reactively transforms an array with a callback function - underlying helper for the `<For>` control flow
|
||||
*
|
||||
* similar to `Array.prototype.map`, but gets the value and index as accessors, transforms only values that changed and returns an accessor and reactively tracks changes to the list.
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/reactive-utilities/map-array
|
||||
*/
|
||||
export declare function mapArray<Item, MappedItem>(list: Accessor<Maybe<readonly Item[]>>, map: (value: Accessor<Item>, index: Accessor<number>) => MappedItem, options?: {
|
||||
keyed?: boolean | ((item: Item) => any);
|
||||
fallback?: Accessor<any>;
|
||||
}): Accessor<MappedItem[]>;
|
||||
/**
|
||||
* Reactively repeats a callback function the count provided - underlying helper for the `<Repeat>` control flow
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/reactive-utilities/repeat
|
||||
*/
|
||||
export declare function repeat(count: Accessor<number>, map: (index: number) => any, options?: {
|
||||
from?: Accessor<number | undefined>;
|
||||
fallback?: Accessor<any>;
|
||||
}): Accessor<any[]>;
|
||||
@@ -1,173 +0,0 @@
|
||||
import type { SignalOptions } from "./core/index.js";
|
||||
import { Owner } from "./core/index.js";
|
||||
export type Accessor<T> = () => T;
|
||||
export type Setter<in out T> = {
|
||||
<U extends T>(...args: undefined extends T ? [] : [value: Exclude<U, Function> | ((prev: T) => U)]): undefined extends T ? undefined : U;
|
||||
<U extends T>(value: (prev: T) => U): U;
|
||||
<U extends T>(value: Exclude<U, Function>): U;
|
||||
<U extends T>(value: Exclude<U, Function> | ((prev: T) => U)): U;
|
||||
};
|
||||
export type Signal<T> = [get: Accessor<T>, set: Setter<T>];
|
||||
export type ComputeFunction<Prev, Next extends Prev = Prev> = (v: Prev) => Next;
|
||||
export type EffectFunction<Prev, Next extends Prev = Prev> = (v: Next, p?: Prev) => (() => void) | void;
|
||||
export type EffectBundle<Prev, Next extends Prev = Prev> = {
|
||||
effect: EffectFunction<Prev, Next>;
|
||||
error: (err: unknown, cleanup: () => void) => void;
|
||||
};
|
||||
export interface EffectOptions {
|
||||
name?: string;
|
||||
defer?: boolean;
|
||||
}
|
||||
export interface MemoOptions<T> {
|
||||
name?: string;
|
||||
equals?: false | ((prev: T, next: T) => boolean);
|
||||
}
|
||||
export type NoInfer<T extends any> = [T][T extends any ? 0 : never];
|
||||
/**
|
||||
* Creates a simple reactive state with a getter and setter
|
||||
* ```typescript
|
||||
* const [state: Accessor<T>, setState: Setter<T>] = createSignal<T>(
|
||||
* value: T,
|
||||
* options?: { name?: string, equals?: false | ((prev: T, next: T) => boolean) }
|
||||
* )
|
||||
* ```
|
||||
* @param value initial value of the state; if empty, the state's type will automatically extended with undefined; otherwise you need to extend the type manually if you want setting to undefined not be an error
|
||||
* @param options optional object with a name for debugging purposes and equals, a comparator function for the previous and next value to allow fine-grained control over the reactivity
|
||||
*
|
||||
* @returns ```typescript
|
||||
* [state: Accessor<T>, setState: Setter<T>]
|
||||
* ```
|
||||
* * the Accessor is a function that returns the current value and registers each call to the reactive root
|
||||
* * the Setter is a function that allows directly setting or mutating the value:
|
||||
* ```typescript
|
||||
* const [count, setCount] = createSignal(0);
|
||||
* setCount(count => count + 1);
|
||||
* ```
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/basic-reactivity/create-signal
|
||||
*/
|
||||
export declare function createSignal<T>(): Signal<T | undefined>;
|
||||
export declare function createSignal<T>(value: Exclude<T, Function>, options?: SignalOptions<T>): Signal<T>;
|
||||
export declare function createSignal<T>(fn: ComputeFunction<T>, initialValue?: T, options?: SignalOptions<T>): Signal<T>;
|
||||
/**
|
||||
* Creates a readonly derived reactive memoized signal
|
||||
* ```typescript
|
||||
* export function createMemo<T>(
|
||||
* compute: (v: T) => T,
|
||||
* value?: T,
|
||||
* options?: { name?: string, equals?: false | ((prev: T, next: T) => boolean) }
|
||||
* ): () => T;
|
||||
* ```
|
||||
* @param compute a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
|
||||
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
|
||||
* @param options allows to set a name in dev mode for debugging purposes and use a custom comparison function in equals
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/basic-reactivity/create-memo
|
||||
*/
|
||||
export declare function createMemo<Next extends Prev, Prev = Next>(compute: ComputeFunction<undefined | NoInfer<Prev>, Next>): Accessor<Next>;
|
||||
export declare function createMemo<Next extends Prev, Init = Next, Prev = Next>(compute: ComputeFunction<Init | Prev, Next>, value: Init, options?: MemoOptions<Next>): Accessor<Next>;
|
||||
/**
|
||||
* Creates a readonly derived async reactive memoized signal
|
||||
* ```typescript
|
||||
* export function createAsync<T>(
|
||||
* compute: (v: T) => Promise<T> | T,
|
||||
* value?: T,
|
||||
* options?: { name?: string, equals?: false | ((prev: T, next: T) => boolean) }
|
||||
* ): () => T;
|
||||
* ```
|
||||
* @param compute a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
|
||||
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
|
||||
* @param options allows to set a name in dev mode for debugging purposes and use a custom comparison function in equals
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/basic-reactivity/create-async
|
||||
*/
|
||||
export declare function createAsync<T>(compute: (prev: T | undefined, refreshing: boolean) => Promise<T> | AsyncIterable<T> | T, value?: T, options?: MemoOptions<T>): Accessor<T> & {
|
||||
refresh: () => void;
|
||||
};
|
||||
/**
|
||||
* Creates a reactive effect that runs after the render phase
|
||||
* ```typescript
|
||||
* export function createEffect<T>(
|
||||
* compute: (prev: T) => T,
|
||||
* effect: (v: T, prev: T) => (() => void) | void,
|
||||
* value?: T,
|
||||
* options?: { name?: string }
|
||||
* ): void;
|
||||
* ```
|
||||
* @param compute a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
|
||||
* @param effect a function that receives the new value and is used to perform side effects, return a cleanup function to run on disposal
|
||||
* @param error an optional function that receives an error if thrown during the computation
|
||||
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
|
||||
* @param options allows to set a name in dev mode for debugging purposes
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/basic-reactivity/create-effect
|
||||
*/
|
||||
export declare function createEffect<Next>(compute: ComputeFunction<undefined | NoInfer<Next>, Next>, effect: EffectFunction<NoInfer<Next>, Next> | EffectBundle<NoInfer<Next>, Next>): void;
|
||||
export declare function createEffect<Next, Init = Next>(compute: ComputeFunction<Init | Next, Next>, effect: EffectFunction<Next, Next> | EffectBundle<Next, Next>, value: Init, options?: EffectOptions): void;
|
||||
/**
|
||||
* Creates a reactive computation that runs during the render phase as DOM elements are created and updated but not necessarily connected
|
||||
* ```typescript
|
||||
* export function createRenderEffect<T>(
|
||||
* compute: (prev: T) => T,
|
||||
* effect: (v: T, prev: T) => (() => void) | void,
|
||||
* value?: T,
|
||||
* options?: { name?: string }
|
||||
* ): void;
|
||||
* ```
|
||||
* @param compute a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
|
||||
* @param effect a function that receives the new value and is used to perform side effects
|
||||
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
|
||||
* @param options allows to set a name in dev mode for debugging purposes
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/secondary-primitives/create-render-effect
|
||||
*/
|
||||
export declare function createRenderEffect<Next>(compute: ComputeFunction<undefined | NoInfer<Next>, Next>, effect: EffectFunction<NoInfer<Next>, Next>): void;
|
||||
export declare function createRenderEffect<Next, Init = Next>(compute: ComputeFunction<Init | Next, Next>, effect: EffectFunction<Next, Next>, value: Init, options?: EffectOptions): void;
|
||||
/**
|
||||
* Creates a new non-tracked reactive context with manual disposal
|
||||
*
|
||||
* @param fn a function in which the reactive state is scoped
|
||||
* @returns the output of `fn`.
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/reactive-utilities/create-root
|
||||
*/
|
||||
export declare function createRoot<T>(init: ((dispose: () => void) => T) | (() => T), options?: {
|
||||
id: string;
|
||||
}): T;
|
||||
/**
|
||||
* Runs the given function in the given owner to move ownership of nested primitives and cleanups.
|
||||
* This method untracks the current scope.
|
||||
*
|
||||
* Warning: Usually there are simpler ways of modeling a problem that avoid using this function
|
||||
*/
|
||||
export declare function runWithOwner<T>(owner: Owner | null, run: () => T): T;
|
||||
/**
|
||||
* Returns a promise of the resolved value of a reactive expression
|
||||
* @param fn a reactive expression to resolve
|
||||
*/
|
||||
export declare function resolve<T>(fn: () => T): Promise<T>;
|
||||
/**
|
||||
* Runs the given function and returns a tuple with the result or an error.
|
||||
* If the function throws an error, it will be caught and returned as the first element of the tuple.
|
||||
* If the function returns a promise, it will resolve to a tuple with the result or an error.
|
||||
*
|
||||
* @param fn The function to run.
|
||||
* @returns A tuple with either [undefined, result] or [error].
|
||||
*
|
||||
* @description https://docs.solidjs.com/reference/reactive-utilities/try-catch
|
||||
*/
|
||||
export type TryCatchResult<T, E> = [undefined, T] | [E];
|
||||
export declare function tryCatch<T, E = Error>(fn: () => Promise<T>): Promise<TryCatchResult<T, E>>;
|
||||
export declare function tryCatch<T, E = Error>(fn: () => T): TryCatchResult<T, E>;
|
||||
/**
|
||||
* Creates an optimistic signal that can be used to optimistically update a value
|
||||
* and then revert it back to the previous value at end of transition.
|
||||
*
|
||||
* @param initial The initial value of the signal.
|
||||
* @param compute An optional function to compute the next value based on the previous value and change.
|
||||
* @param options Optional signal options.
|
||||
*
|
||||
* @returns A tuple containing an accessor for the current value and a setter function to apply changes.
|
||||
*/
|
||||
export declare function createOptimistic<T>(initial: Exclude<T, Function>, compute?: never): [Accessor<T>, (value: T | ((v?: T) => T)) => void];
|
||||
export declare function createOptimistic<T extends object, U>(initial: T | Accessor<T>, compute: (prev: T, change: U) => void, key: string | ((item: any) => any)): [Accessor<T>, (value: U | ((v?: U) => U)) => void];
|
||||
@@ -1,6 +0,0 @@
|
||||
export type { Store, StoreSetter, StoreNode, NotWrappable, SolidStore } from "./store.js";
|
||||
export type { Merge, Omit } from "./utils.js";
|
||||
export { isWrappable, createStore, deep, $TRACK, $PROXY, $TARGET } from "./store.js";
|
||||
export { createProjection } from "./projection.js";
|
||||
export { reconcile } from "./reconcile.js";
|
||||
export { snapshot, merge, omit } from "./utils.js";
|
||||
@@ -1,7 +0,0 @@
|
||||
import { type Store } from "./store.js";
|
||||
/**
|
||||
* Creates a mutable derived value
|
||||
*
|
||||
* @see {@link https://github.com/solidjs/x-reactivity#createprojection}
|
||||
*/
|
||||
export declare function createProjection<T extends Object>(fn: (draft: T) => void, initialValue?: T): Store<T>;
|
||||
@@ -1 +0,0 @@
|
||||
export declare function reconcile<T extends U, U>(value: T, key: string | ((item: NonNullable<any>) => any), all?: boolean): (state: U) => void;
|
||||
@@ -1,33 +0,0 @@
|
||||
import { Computation } from "../core/index.js";
|
||||
export type Store<T> = Readonly<T>;
|
||||
export type StoreSetter<T> = (fn: (state: T) => void) => void;
|
||||
type DataNode = Computation<any>;
|
||||
type DataNodes = Record<PropertyKey, DataNode>;
|
||||
export declare const $TRACK: unique symbol, $DEEP: unique symbol, $TARGET: unique symbol, $PROXY: unique symbol, $DELETED: unique symbol;
|
||||
export declare const STORE_VALUE = "v", STORE_OVERRIDE = "o", STORE_NODE = "n", STORE_HAS = "h", STORE_WRAP = "w", STORE_LOOKUP = "l";
|
||||
export type StoreNode = {
|
||||
[$PROXY]: any;
|
||||
[STORE_VALUE]: Record<PropertyKey, any>;
|
||||
[STORE_OVERRIDE]?: Record<PropertyKey, any>;
|
||||
[STORE_NODE]?: DataNodes;
|
||||
[STORE_HAS]?: DataNodes;
|
||||
[STORE_WRAP]?: (value: any, target?: StoreNode) => any;
|
||||
[STORE_LOOKUP]?: WeakMap<any, any>;
|
||||
};
|
||||
export declare namespace SolidStore {
|
||||
interface Unwrappable {
|
||||
}
|
||||
}
|
||||
export type NotWrappable = string | number | bigint | symbol | boolean | Function | null | undefined | SolidStore.Unwrappable[keyof SolidStore.Unwrappable];
|
||||
export declare function createStoreProxy<T extends object>(value: T, traps?: ProxyHandler<StoreNode>, extend?: Record<PropertyKey, any>): any;
|
||||
export declare const storeLookup: WeakMap<object, any>;
|
||||
export declare function wrap<T extends Record<PropertyKey, any>>(value: T, target?: StoreNode): T;
|
||||
export declare function isWrappable<T>(obj: T | NotWrappable): obj is T;
|
||||
export declare function getKeys(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined, enumerable?: boolean): PropertyKey[];
|
||||
export declare function getPropertyDescriptor(source: Record<PropertyKey, any>, override: Record<PropertyKey, any> | undefined, property: PropertyKey): PropertyDescriptor | undefined;
|
||||
export declare const storeTraps: ProxyHandler<StoreNode>;
|
||||
export declare function storeSetter<T extends object>(store: Store<T>, fn: (draft: T) => void): void;
|
||||
export declare function createStore<T extends object = {}>(store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
|
||||
export declare function createStore<T extends object = {}>(fn: (store: T) => void, store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
|
||||
export declare function deep<T extends object>(store: Store<T>): Store<any>;
|
||||
export {};
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* Returns a non reactive copy of the store object.
|
||||
* It will attempt to preserver the original reference unless the value has been modified.
|
||||
* @param item store proxy object
|
||||
*/
|
||||
export declare function snapshot<T>(item: T): T;
|
||||
export declare function snapshot<T>(item: T, map?: Map<unknown, unknown>, lookup?: WeakMap<any, any>): T;
|
||||
type DistributeOverride<T, F> = T extends undefined ? F : T;
|
||||
type Override<T, U> = T extends any ? U extends any ? {
|
||||
[K in keyof T]: K extends keyof U ? DistributeOverride<U[K], T[K]> : T[K];
|
||||
} & {
|
||||
[K in keyof U]: K extends keyof T ? DistributeOverride<U[K], T[K]> : U[K];
|
||||
} : T & U : T & U;
|
||||
type OverrideSpread<T, U> = T extends any ? {
|
||||
[K in keyof ({
|
||||
[K in keyof T]: any;
|
||||
} & {
|
||||
[K in keyof U]?: any;
|
||||
} & {
|
||||
[K in U extends any ? keyof U : keyof U]?: any;
|
||||
})]: K extends keyof T ? Exclude<U extends any ? U[K & keyof U] : never, undefined> | T[K] : U extends any ? U[K & keyof U] : never;
|
||||
} : T & U;
|
||||
type Simplify<T> = T extends any ? {
|
||||
[K in keyof T]: T[K];
|
||||
} : T;
|
||||
type _Merge<T extends unknown[], Curr = {}> = T extends [
|
||||
infer Next | (() => infer Next),
|
||||
...infer Rest
|
||||
] ? _Merge<Rest, Override<Curr, Next>> : T extends [...infer Rest, infer Next | (() => infer Next)] ? Override<_Merge<Rest, Curr>, Next> : T extends [] ? Curr : T extends (infer I | (() => infer I))[] ? OverrideSpread<Curr, I> : Curr;
|
||||
export type Merge<T extends unknown[]> = Simplify<_Merge<T>>;
|
||||
export declare function merge<T extends unknown[]>(...sources: T): Merge<T>;
|
||||
export type Omit<T, K extends readonly (keyof T)[]> = {
|
||||
[P in keyof T as Exclude<P, K[number]>]: T[P];
|
||||
};
|
||||
export declare function omit<T extends Record<any, any>, K extends readonly (keyof T)[]>(props: T, ...keys: K): Omit<T, K>;
|
||||
export {};
|
||||
@@ -26,7 +26,7 @@ sw.addEventListener("activate", (event) => {
|
||||
.then((keys) =>
|
||||
Promise.all(
|
||||
keys
|
||||
.filter((key) => key !== "api" && key !== CACHE_VERSION)
|
||||
.filter((key) => key !== CACHE_VERSION)
|
||||
.map((key) => caches.delete(key)),
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user