feat: Add complete PDPA compliance pages

- Admin dashboard (/admin/consent-logs) with password auth
- Consent API (/api/consent) with SQLite + IP hashing
- Privacy Policy (Thai) - PDPA Section 36 compliant
- Terms & Conditions (Thai) - 9 standard clauses
- .env.example template with Umami placeholder

All pages preserve current design system.
This commit is contained in:
Kunthawat committed 2026-03-10 21:28:23 +07:00
1 parent e98b9f2bff
commit b2e427791b
3282 files changed
+302503 -435

No files matched your search

+11 -3
View File
@@ -162,11 +162,19 @@ declare module 'astro:content' {
};
type DataEntryMap = {
"products": Record<string, {
"blog": Record<string, {
id: string;
body?: string;
collection: "blog";
data: any;
rendered?: RenderedContent;
filePath?: string;
}>;
"products": Record<string, {
id: string;
body?: string;
collection: "products";
data: InferEntrySchema<"products">;
data: any;
rendered?: RenderedContent;
filePath?: string;
}>;
@@ -202,6 +210,6 @@ declare module 'astro:content' {
LiveContentConfig['collections'][C]['loader']
>;
export type ContentConfig = typeof import("../src/content.config.js");
export type ContentConfig = typeof import("../src/content.config.mjs");
export type LiveContentConfig = never;
}
+19
View File
@@ -0,0 +1,19 @@
# Environment Variables for Deal Plus Tech Astro Website
# Umami Analytics (optional - setup later)
PUBLIC_UMAMI_WEBSITE_ID=your-website-id-here
PUBLIC_UMAMI_DOMAIN=https://analytics.moreminimore.com
# Admin Dashboard
ADMIN_PASSWORD=changeme
# Database Configuration
# For development (SQLite file)
ASTRO_DB_REMOTE_URL=file:./data/consent.db
# For production (Turso - optional)
# ASTRO_DB_REMOTE_URL=libsql://your-db.turso.io
# ASTRO_DB_APP_TOKEN=your-turso-token
# Site Configuration
PUBLIC_SITE_URL=https://dealplustech.co.th
-5
View File
@@ -1,5 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="บทความความรู้เกี่ยวกับวัสดุท่อ อุปกรณ์ระบบท่อ และเทคนิคการติดตั้ง"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="บทความความรู้"><meta property="og:description" content="บทความความรู้เกี่ยวกับวัสดุท่อ อุปกรณ์ระบบท่อ และเทคนิคการติดตั้ง"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>บทความความรู้ | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
</style></head> <body class="flex flex-col min-h-screen"> <main class="pt-32 pb-16"> <div class="container mx-auto px-4"> <!-- Hero --> <div class="text-center mb-12"> <h1 class="text-4xl md:text-5xl font-bold text-secondary-900 mb-4">
บทความ<span class="text-primary-600">ความรู้</span> </h1> <p class="text-xl text-secondary-600 max-w-2xl mx-auto">
บทความความรู้เกี่ยวกับวัสดุท่อ อุปกรณ์ระบบท่อ และเทคนิคการติดตั้ง
</p> </div> <!-- Blog Grid --> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"> </div> </div> </main> </body></html>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 B

-9
View File
@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 128 128">
<path d="M50.4 78.5a75.1 75.1 0 0 0-28.5 6.9l24.2-65.7c.7-2 1.9-3.2 3.4-3.2h29c1.5 0 2.7 1.2 3.4 3.2l24.2 65.7s-11.6-7-28.5-7L67 45.5c-.4-1.7-1.6-2.8-2.9-2.8-1.3 0-2.5 1.1-2.9 2.7L50.4 78.5Zm-1.1 28.2Zm-4.2-20.2c-2 6.6-.6 15.8 4.2 20.2a17.5 17.5 0 0 1 .2-.7 5.5 5.5 0 0 1 5.7-4.5c2.8.1 4.3 1.5 4.7 4.7.2 1.1.2 2.3.2 3.5v.4c0 2.7.7 5.2 2.2 7.4a13 13 0 0 0 5.7 4.9v-.3l-.2-.3c-1.8-5.6-.5-9.5 4.4-12.8l1.5-1a73 73 0 0 0 3.2-2.2 16 16 0 0 0 6.8-11.4c.3-2 .1-4-.6-6l-.8.6-1.6 1a37 37 0 0 1-22.4 2.7c-5-.7-9.7-2-13.2-6.2Z" />
<style>
path { fill: #000; }
@media (prefers-color-scheme: dark) {
path { fill: #FFF; }
}
</style>
</svg>

Before

Width:  |  Height:  |  Size: 749 B

-36
View File
@@ -1,36 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="บริษัท ดีล พลัส เทค จำกัด - ผู้เชี่ยวชาญด้านระบบท่อและ HVAC"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="หน้าแรก"><meta property="og:description" content="บริษัท ดีล พลัส เทค จำกัด - ผู้เชี่ยวชาญด้านระบบท่อและ HVAC"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>หน้าแรก | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
</style></head> <body class="flex flex-col min-h-screen"> <main> <!-- Hero Section --> <section class="relative h-[70vh] min-h-[500px] bg-secondary-900"> <div class="absolute inset-0 bg-gradient-to-r from-secondary-900 via-secondary-900/90 to-secondary-900/60 z-10"></div> <img src="/images/2021/03/ppr-pipe_000C.jpg" alt="ท่อพีพีอาร์คุณภาพสูง" class="absolute inset-0 w-full h-full object-cover opacity-50" loading="eager"> <div class="relative z-20 container mx-auto px-4 h-full flex items-center"> <div class="max-w-2xl"> <span class="inline-block px-4 py-2 bg-primary-600 text-white font-semibold mb-4 rounded">
ผู้เชี่ยวชาญด้านระบบท่อและ HVAC
</span> <h1 class="text-4xl md:text-5xl lg:text-6xl font-bold text-white mb-6 leading-tight">
วัสดุท่อ อุปกรณ์ HVAC
<span class="text-primary-400 block">และฉนวนหุ้มท่อ</span> </h1> <p class="text-lg md:text-xl text-secondary-200 mb-8">
จำหน่ายและติดตั้งท่อ PPR, ท่อ HDPE, กริลแอร์, เทอร์โมเบรค และอุปกรณ์ระบบท่อครบวงจร พร้อมบริการให้คำปรึกษาจากทีมมืออาชีพ
</p> <div class="flex flex-wrap gap-4"> <a href="/products/" class="btn-primary">
ดูสินค้าทั้งหมด
</a> <a href="/contact-us/" class="btn-outline border-white text-white hover:bg-white hover:text-secondary-900">
ขอใบเสนอราคา
</a> </div> </div> </div> </section> <!-- Features Section --> <section class="py-16 bg-secondary-800"> <div class="container mx-auto px-4"> <div class="grid grid-cols-1 md:grid-cols-3 gap-8"> <div class="text-center p-6"> <div class="w-16 h-16 bg-primary-600 rounded-lg flex items-center justify-center mx-auto mb-4"> <svg class="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"></path> </svg> </div> <h3 class="text-xl font-bold text-white mb-2">สินค้าคุณภาพ</h3> <p class="text-secondary-300">
สินค้าทุกชิ้นผ่านมาตรฐานคุณภาพ พร้อมรับประกัน
</p> </div> <div class="text-center p-6"> <div class="w-16 h-16 bg-primary-600 rounded-lg flex items-center justify-center mx-auto mb-4"> <svg class="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path> </svg> </div> <h3 class="text-xl font-bold text-white mb-2">จัดส่งรวดเร็ว</h3> <p class="text-secondary-300">
จัดส่งสินค้าทั่วประเทศ รวดเร็วและปลอดภัย
</p> </div> <div class="text-center p-6"> <div class="w-16 h-16 bg-primary-600 rounded-lg flex items-center justify-center mx-auto mb-4"> <svg class="w-8 h-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"></path> </svg> </div> <h3 class="text-xl font-bold text-white mb-2">บริการหลังการขาย</h3> <p class="text-secondary-300">
ทีมงานพร้อมให้คำปรึกษาและดูแลอย่างต่อเนื่อง
</p> </div> </div> </div> </section> <!-- Featured Products --> <section class="py-16 bg-secondary-50"> <div class="container mx-auto px-4"> <div class="text-center mb-12"> <h2 class="text-3xl md:text-4xl font-bold text-secondary-900 mb-4">
สินค้า<span class="text-primary-600">เด่น</span> </h2> <p class="text-secondary-600 text-lg">ผลิตภัณฑ์คุณภาพสูงที่ได้รับความนิยม</p> </div> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"> <a href="/ท่อพีพีอาร์ตราช้าง/" class="card group"> <div class="relative aspect-video bg-secondary-100 overflow-hidden"> <img src="/images/2021/03/ppr-pipe_000C.jpg" alt="ท่อพีพีอาร์ตราช้าง" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อพีพีอาร์ตราช้าง </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อพีพีอาร์ตราช้าง SCG มาตรฐาน DIN 8077/8078 </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/pp-r-pp-rct-poloplast/" class="card group"> <div class="relative aspect-video bg-secondary-100 overflow-hidden"> <img src="/images/2021/03/poloplast_000C.jpg" alt="ท่อ PP-R/PP-RCT POLOPLAST" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อ PP-R/PP-RCT POLOPLAST </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อ PP-R/PP-RCT POLOPLAST คุณภาพเยอรมัน </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/ท่อhdpe/" class="card group"> <div class="relative aspect-video bg-secondary-100 overflow-hidden"> <img src="/images/2021/03/hdpe-pipe_000C.jpg" alt="ท่อ HDPE" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อ HDPE </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อเอชดีพีอี PE80/PE100 มาตรฐาน มอก. </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/ท่อไซเลอร์/" class="card group"> <div class="relative aspect-video bg-secondary-100 overflow-hidden"> <img src="/images/2021/03/syler_000C.jpg" alt="ท่อไซเลอร์" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อไซเลอร์ </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อเหล็กบุ PE BS1387 FM APPROVED </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/ท่อระบายน้ำ-3-ชั้น-ไซเลนท/" class="card group"> <div class="relative aspect-video bg-secondary-100 overflow-hidden"> <img src="/images/2021/03/xylent_000C.jpg" alt="ท่อระบายน้ำ 3 ชั้น ไซเลนท์" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อระบายน้ำ 3 ชั้น ไซเลนท์ </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อระบายน้ำไซเลนท์ 22dB Push Fit </p> <div class="mt-4 flex items-center text-primarLine truncated
ดูสินค้าทั้งหมด
</a> </div> </div> </section> <!-- About Preview --> <section class="py-16 bg-white"> <div class="container mx-auto px-4"> <div class="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center"> <div> <h2 class="text-3xl md:text-4xl font-bold text-secondary-900 mb-6">
เกี่ยวกับ<span class="text-primary-600">เรา</span> </h2> <p class="text-lg text-secondary-600 mb-6">
บริษัท ดีล พลัส เทค จำกัด เราเป็นผู้เชียวชาญด้านระบบน้ำ ให้คำแนะนำและจำหน่ายท่อ PPR ตราช้าง ท่อพีพีอาร์ ท่อ PPR ท่อ HDPE Thai PPR คุณภาพสูง ราคาถูก
</p> <p class="text-secondary-700 mb-8">
ด้วยประสบการณ์ยาวนาน เราพร้อมให้บริการสินค้าคุณภาพและคำแนะนำจากผู้เชี่ยวชาญ เพื่อให้งานระบบของคุณมีประสิทธิภาพสูงสุด
</p> <a href="/about-us/" class="btn-secondary">
อ่านเพิ่มเติม
</a> </div> <div class="relative aspect-video bg-secondary-100 rounded-xl overflow-hidden"> <img src="/images/2021/03/ppr-pipe_000C.jpg" alt="เกี่ยวกับดีลพลัสเทค" class="object-cover w-full h-full" loading="lazy"> </div> </div> </div> </section> <!-- CTA Section --> <section class="py-16 bg-primary-600"> <div class="container mx-auto px-4 text-center"> <h2 class="text-3xl md:text-4xl font-bold text-white mb-4">
สนใจสินค้าหรือต้องการคำปรึกษา?
</h2> <p class="text-xl text-primary-100 mb-8 max-w-2xl mx-auto">
ทีมงานของเราพร้อมให้คำแนะนำและช่วยคุณเลือกสินค้าที่เหมาะสมที่สุด
</p> <div class="flex flex-wrap justify-center gap-4"> <a href="tel:090-555-1415" class="btn-secondary bg-white text-primary-600 hover:bg-primary-50">
โทร: 090-555-1415
</a> <a href="https://line.me/ti/p/@dealplustech" target="_blank" rel="noopener" class="btn-outline border-white text-white hover:bg-white hover:text-primary-600">
เพิ่มเพื่อน LINE
</a> </div> </div> </section> </main> <div class="fixed bottom-6 right-6 z-40 flex flex-col gap-3"> <!-- LINE --> <a href="https://line.me/ti/p/@dealplustech" target="_blank" rel="noopener noreferrer" class="w-14 h-14 bg-[#00B900] rounded-full flex items-center justify-center shadow-lg hover:scale-110 transition-transform" aria-label="ติดต่อผ่าน LINE"> <svg class="w-7 h-7 text-white" viewBox="0 0 24 24" fill="currentColor"> <path d="M19.365 9.863c.349 0 .63.285.63.631 0 .345-.281.63-.63.63H17.61v1.125h1.755c.349 0 .63.283.63.63 0 .344-.281.629-.63.629h-2.386c-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63h2.386c.346 0 .627.285.627.63 0 .349-.281.63-.63.63H17.61v1.125h1.755zm-3.855 3.016c0 .27-.174.51-.432.596-.064.021-.133.031-.199.031-.211 0-.391-.09-.51-.25l-2.443-3.317v2.94c0 .344-.279.629-.631.629-.346 0-.626-.285-.626-.629V8.108c0-.27.173-.51.43-.595.06-.023.136-.033.194-.033.195 0 .375.104.495.254l2.462 3.33V8.108c0-.345.282-.63.63-.63.345 0 .63.285.63.63v4.771zm-5.741 0c0 .344-.282.629-.631.629-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63.346 0 .628.285.628.63v4.771zm-2.466.629H4.917c-.345 0-.63-.285-.63-.629V8.108c0-.345.285-.63.63-.63.348 0 .63.285.63.63v4.141h1.756c.348 0 .629.283.629.63 0 .344-.282.629-.629.629M24 10.314C24 4.943 18.615.572 12 .572S0 4.943 0 10.314c0 4.811 4.27 8.842 10.035 9.608.391.082.923.258 1.058.59.12.301.079.766.038 1.08l-.164 1.02c-.045.301-.24 1.186 1.049.645 1.291-.539 6.916-4.078 9.436-6.975C23.176 14.393 24 12.458 24 10.314"></path> </svg> </a> <!-- Phone --> <a href="tel:090-555-1415" class="w-14 h-14 bg-primary-600 rounded-full flex items-center justify-center shadow-lg hover:scale-110 transition-transform" aria-label="โทรหาเรา"> <svg class="w-7 h-7 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path> </svg> </a> </div> </body></html>
-2
View File
@@ -1,2 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="รายการสินค้าทั้งหมดจาก Deal Plus Tech"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="สินค้าทั้งหมด"><meta property="og:description" content="รายการสินค้าทั้งหมดจาก Deal Plus Tech"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>สินค้าทั้งหมด | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12"> <div class="container mx-auto px-4 max-w-6xl"> <h1 class="section-title mb-8">สินค้าทั้งหมด</h1> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <a href="/products/ท่อไซเลอร์" class="card group"> <div class="aspect-w-16 aspect-h-9 overflow-hidden bg-secondary-100"> <img src="/images/2021/03/syler_000C.jpg" alt="ท่อไซเลอร์" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อไซเลอร์ </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อเหล็กบุ PE BS1387 FM APPROVED </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/products/pp-r-pp-rct-poloplast" class="card group"> <div class="aspect-w-16 aspect-h-9 overflow-hidden bg-secondary-100"> <img src="/images/2021/03/poloplast_000C.jpg" alt="ท่อ PP-R/PP-RCT POLOPLAST" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อ PP-R/PP-RCT POLOPLAST </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อ PP-R/PP-RCT POLOPLAST คุณภาพเยอรมัน </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/products/ท่อppr-thaippr" class="card group"> <div class="aspect-w-16 aspect-h-9 overflow-hidden bg-secondary-100"> <img src="/images/2021/03/ppr-pipe_000C.jpg" alt="ท่อ PPR Thai PPR" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อ PPR Thai PPR </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อ PPR Thai PPR มาตรฐาน มอก. </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/products/ท่อพีพีอาร์ตราช้าง" class="card group"> <div class="aspect-w-16 aspect-h-9 overflow-hidden bg-secondary-100"> <img src="/images/2021/03/ppr-pipe_000C.jpg" alt="ท่อพีพีอาร์ตราช้าง" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อพีพีอาร์ตราช้าง </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อพีพีอาร์ตราช้าง SCG มาตรฐาน DIN 8077/8078 </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path> </svg> </div> </div> </a><a href="/products/ท่อhdpe" class="card group"> <div class="aspect-w-16 aspect-h-9 overflow-hidden bg-secondary-100"> <img src="/images/2021/03/hdpe-pipe_000C.jpg" alt="ท่อ HDPE" class="object-cover w-full h-48 group-hover:scale-105 transition-transform duration-300" loading="lazy"> </div> <div class="p-6"> <h3 class="text-lg font-bold text-secondary-900 group-hover:text-primary-600 transition-colors"> ท่อ HDPE </h3> <p class="mt-2 text-sm text-secondary-600 line-clamp-2"> ท่อเอชดีพีอี PE80/PE100 มาตรฐาน มอก. </p> <div class="mt-4 flex items-center text-primary-600 font-medium"> <span>ดูรายละเอียด</span> <svg class="w-4 h-4 ml-2 group-hover:translate-x-1 transition-tranLine truncated
@@ -1,52 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อ PP-R/PP-RCT POLOPLAST คุณภาพเยอรมัน"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อ PP-R/PP-RCT POLOPLAST"><meta property="og:description" content="ท่อ PP-R/PP-RCT POLOPLAST คุณภาพเยอรมัน"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อ PP-R/PP-RCT POLOPLAST | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อ PP-R/PP-RCT POLOPLAST </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อพีพีอาร์ POLOPLAST จากเยอรมนี มาตรฐาน DVGW และ SKZ ทนอุณหภูมิ 95°C รับประกัน 10 ปี </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อ-pp-rpp-rct-poloplast">ท่อ PP-R/PP-RCT POLOPLAST</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อพีพีอาร์ <strong>POLOPLAST</strong> เป็นผลิตภัณฑ์ <strong>ระดับพรีเมียมจากเยอรมนี</strong> มีทั้งรุ่น PP-R และ PP-RCT ที่ได้รับการพัฒนาด้วยเทคโนโลยีล้ำสมัย ท่อ POLOPLAST ผ่านมาตรฐาน DVGW และ SKZ ระดับสากล</p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>มีความทนทานสูงสุด <strong>ทนอุณหภูมิได้ถึง 95°C</strong> และ <strong>ทนแรงดันสูงถึง PN25</strong> รับประกันคุณภาพ <strong>10 ปี</strong></p>
<h3 id="ข้อดีของท่อ-poloplast">ข้อดีของท่อ POLOPLAST</h3>
<ol>
<li><strong>ผลิตในเยอรมนี</strong> - คุณภาพระดับพรีเมียม</li>
<li><strong>มาตรฐานสูงสุด</strong> - DVGW และ SKZ</li>
<li><strong>ทนแรงดัน PN25</strong> - สูงที่สุดในตลาด</li>
<li><strong>ฉนวนความร้อนดีเยี่ยม</strong> - ค่าการนำความร้อน 0.15 W/mK</li>
<li><strong>ทนอุณหภูมิ 95°C</strong> - เหมาะกับน้ำร้อนอุณหภูมิสูง</li>
<li><strong>รับประกัน 10 ปี</strong> - มั่นใจในคุณภาพ</li>
<li><strong>อายุการใช้งาน 50 ปี</strong> - ลงทุนครั้งเดียว</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรับ">เหมาะสำหรับ</h3>
<ul>
<li>ระบบประปาน้ำร้อนอุณหภูมิสูง</li>
<li>ระบบทำความร้อน (Heating)</li>
<li>ระบบแอร์แช่ (Chilled Water)</li>
<li><strong>โรงแรม 5 ดาว</strong></li>
<li><strong>โรงพยาบาลและศูนย์การแพทย์</strong></li>
<li><strong>โครงการระดับพรีเมียม</strong></li>
<li>โรงงานอุตสาหกรรม</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อ POLOPLAST ได้รับมาตรฐานสากล:</p>
<ul>
<li>✅ <strong>DIN 8077/8078</strong> - มาตรฐานเยอรมัน</li>
<li>✅ <strong>ISO 15874</strong> - มาตรฐานสากล</li>
<li>✅ <strong>DVGW</strong> - สมาคมเทคนิคและวิทยาศาสตร์ก๊าซและน้ำเยอรมัน</li>
<li>✅ <strong>SKZ</strong> - ศูนย์เซาท์เยอรมันพลาสติก</li>
<li>✅ <strong>Hygienic Certificate</strong> - รับรองความปลอดภัยน้ำดื่ม</li>
</ul>
<h2 id="pp-rct-technology">PP-RCT Technology</h2>
<p><strong>PP-RCT</strong> (Polypropylene Random Copolymer with modified Crystallinity and Temperature resistance) เป็นวัสดุพัฒนาต่อจาก PP-R มีความทนทานต่อแรงดันและอุณหภูมิสูงกว่า สามารถทนแรงดันได้สูงถึง <strong>PN25</strong></p>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อ-poloplast-กับท่อ-ppr-ทั่วไปต่างกันอย่างไร">ท่อ POLOPLAST กับท่อ PPR ทั่วไปต่างกันอย่างไร?</h3>
<p>ท่อ POLOPLAST ผลิตในเยอรมนี มีมาตรฐาน DVGW และ SKZ ทนแรงดันสูงถึง PN25 มีค่านำความร้อนต่ำกว่า และรับประกัน 10 ปี ซึ่งดีกว่าท่อ PPR ทั่วไป</p>
<h3 id="pp-rct-คืออะไร">PP-RCT คืออะไร?</h3>
<p>PP-RCT (Polypropylene Random Copolymer with modified Crystallinity and Temperature resistance) เป็นวัสดุพัฒนาต่อจาก PP-R มีความทนทานต่อแรงดันและอุณหภูมิสูงกว่า สามารถทนแรงดันได้สูงถึง PN25</p>
<h3 id="ท่อ-poloplast-รับประกันกี่ปี">ท่อ POLOPLAST รับประกันกี่ปี?</h3>
<p>ท่อ POLOPLAST มีการรับประกันคุณภาพ <strong>10 ปี</strong> สะท้อนถึงความมั่นใจในคุณภาพของผลิตภัณฑ์</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C%E0%B8%95%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B9%89%E0%B8%B2%E0%B8%87/">ท่อพีพีอาร์ตราช้าง</a></li>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%ADppr-thaippr/">ท่อ PPR Thai PPR</a></li>
<li><a href="/%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C/">เครื่องเชื่อมท่อพีพีอาร์</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PP-R / PP-RCT (Polypropylene Random Copolymer) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> DIN 8077/8078, ISO 15874, DVGW, SKZ </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>แรงดันทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PN10, PN16, PN20, PN25 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>bar</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อุณหภูมิทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> -20 ถึง 95 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>°C</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 20, 25, 32, 40, 50, 63, 75, 90, 110, 125, 160 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ค่าสัมประสิทธิ์การนำความร้อน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 0.15 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>W/mK</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> ขาว, เขียว, ส้ม </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อายุการใช้งาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>รับประกัน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 10 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <ul class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 fleLine truncated
@@ -1,107 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อเอชดีพีอี PE80/PE100 มาตรฐาน มอก."><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อ HDPE"><meta property="og:description" content="ท่อเอชดีพีอี PE80/PE100 มาตรฐาน มอก."><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อ HDPE | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อ HDPE </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อ HDPE PE80/PE100 ทนแรงดัน PN25 อายุการใช้งาน 50 ปี มอก. สำหรับประปาและชลประทาน </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อ-hdpe-high-density-polyethylene">ท่อ HDPE (High Density Polyethylene)</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อ HDPE (High Density Polyethylene) หรือ <strong>ท่อเอชดีพีอี</strong> เป็นท่อพลาสติกคุณภาพสูงที่มีความ <strong>ทนทานและยืดหยุ่นสูง</strong> ผลิตจากเม็ดพลาสติก HDPE เกรด <strong>PE80 และ PE100</strong></p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>ท่อ HDPE สามารถทนแรงดันได้สูงถึง <strong>PN25 บาร์</strong> ทนทานต่อแรงกระแทกและการกัดกร่อน ไม่เกิดสนิม อายุการใช้งานยาวนานกว่า <strong>50 ปี</strong></p>
<h3 id="ข้อดีของท่อ-hdpe">ข้อดีของท่อ HDPE</h3>
<ol>
<li><strong>ทนแรงดันสูง</strong> - สูงถึง PN25 บาร์</li>
<li><strong>ทนแรงกระแทก</strong> - ยืดหยุ่นสูง ทนต่อการเคลื่อนไหวของดิน</li>
<li><strong>ไม่เกิดสนิม</strong> - ทนสารเคมีและกรดด่าง</li>
<li><strong>น้ำหนักเบา</strong> - ขนส่งและติดตั้งง่าย</li>
<li><strong>รอยต่อแน่นหนา</strong> - ระบบ Butt Fusion ไม่รั่วซึม</li>
<li><strong>อายุการใช้งานยาว</strong> - มากกว่า 50 ปี</li>
<li><strong>มาตรฐาน มอก.</strong> - รับรองคุณภาพ</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรับ">เหมาะสำหรับ</h3>
<ul>
<li><strong>ระบบประปา</strong> - งานผลิตน้ำประปา</li>
<li><strong>ระบบชลประทาน</strong> - ส่งน้ำทางการเกษตร</li>
<li><strong>ระบบน้ำเสีย</strong> - ท่อระบายน้ำ</li>
<li><strong>ท่อส่งก๊าซ</strong> - ท่อส่งก๊าซธรรมชาติ</li>
<li><strong>งานอุตสาหกรรม</strong> - ท่อส่งสารเคมี</li>
<li><strong>ระบบระบายน้ำ</strong> - งานเทศบาลและเมือง</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อ HDPE ผ่านมาตรฐาน:</p>
<ul>
<li>✅ <strong>มอก. 827-2547</strong> - มาตรฐานผลิตภัณฑ์อุตสาหกรรม</li>
<li>✅ <strong>ISO 4427</strong> - มาตรฐานสากล</li>
<li>✅ <strong>ISO 9001</strong> - ระบบบริหารคุณภาพ</li>
</ul>
<h2 id="เกรดของท่อ-hdpe">เกรดของท่อ HDPE</h2>
<h3 id="pe80-vs-pe100">PE80 vs PE100</h3>
<table><thead><tr><th>คุณสมบัติ</th><th>PE80</th><th>PE100</th></tr></thead><tbody><tr><td><strong>MRS</strong></td><td>8 MPa</td><td>10 MPa</td></tr><tr><td><strong>ทนแรงดัน</strong></td><td>สูง</td><td>สูงกว่า</td></tr><tr><td><strong>ราคา</strong></td><td>ประหยัด</td><td>สูงกว่า</td></tr><tr><td><strong>การใช้งาน</strong></td><td>ทั่วไป</td><td>แรงดันสูง</td></tr></tbody></table>
<h2 id="sdr-standard-dimension-ratio">SDR (Standard Dimension Ratio)</h2>
<p><strong>SDR</strong> คืออัตราส่วนระหว่างเส้นผ่านศูนย์กลางภายนอกกับความหนาผนังท่อ</p>
<ul>
<li><strong>SDR น้อย</strong> = ผนังหนา = ทนแรงดันสูง</li>
<li><strong>SDR มาก</strong> = ผนังบาง = ทนแรงดันต่ำ</li>
</ul>
<p>ตัวอย่าง:</p>
<ul>
<li>SDR 9 = ทนแรงดันสูงสุด</li>
<li>SDR 11 = ทนแรงดันสูง</li>
<li>SDR 17 = ทนแรงดันปานกลาง</li>
<li>SDR 26 = ทนแรงดันต่ำ</li>
</ul>
<h2 id="การติดตั้ง">การติดตั้ง</h2>
<h3 id="วิธี-butt-fusion">วิธี Butt Fusion</h3>
<ul>
<li>เหมาะสำหรับท่อ <strong>63-1200 mm</strong></li>
<li>ใช้ความร้อนหลอมปลายท่อ</li>
<li>กดต่อกันจนเป็นชิ้นเดียว</li>
</ul>
<h3 id="วิธี-electrofusion">วิธี Electrofusion</h3>
<ul>
<li>เหมาะสำหรับท่อ <strong>20-630 mm</strong></li>
<li>ใช้ข้อต่อที่มีขดลวดความร้อน</li>
<li>สะดวกในพื้นที่จำกัด</li>
</ul>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อ-hdpe-pe80-กับ-pe100-ต่างกันอย่างไร">ท่อ HDPE PE80 กับ PE100 ต่างกันอย่างไร?</h3>
<p>ท่อ HDPE PE100 มีความทนทานต่อแรงดันสูงกว่า PE80 โดย PE100 มี MRS (Minimum Required Strength) 10 MPa ส่วน PE80 มี MRS 8 MPa</p>
<h3 id="ท่อ-hdpe-มีอายุการใช้งานกี่ปี">ท่อ HDPE มีอายุการใช้งานกี่ปี?</h3>
<p>ท่อ HDPE มีอายุการใช้งานยาวนานกว่า <strong>50 ปี</strong> ภายใต้การใช้งานตามมาตรฐาน</p>
<h3 id="วิธีติดตั้งท่อ-hdpe-ทำอย่างไร">วิธีติดตั้งท่อ HDPE ทำอย่างไร?</h3>
<p>ท่อ HDPE ติดตั้งโดยใช้วิธี <strong>Butt Fusion</strong> (เชื่อมปลายต่อ) หรือ <strong>Electrofusion</strong> (เชื่อมด้วยไฟฟ้า)</p>
<h3 id="sdr-ในท่อ-hdpe-คืออะไร">SDR ในท่อ HDPE คืออะไร?</h3>
<p>SDR (Standard Dimension Ratio) คืออัตราส่วนระหว่างเส้นผ่านศูนย์กลางภายนอกกับความหนาผนังท่อ ค่า SDR ที่น้อยกว่าหมายถึงผนังท่อหนากว่า</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1-hdpe/">เครื่องเชื่อม HDPE</a></li>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C%E0%B8%95%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B9%89%E0%B8%B2%E0%B8%87/">ท่อพีพีอาร์ตราช้าง</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> HDPE (High Density Polyethylene) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>เกรด</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PE80, PE100 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> มอก. 827-2547, ISO 4427 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>แรงดันทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PN4 - PN25 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>bar</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>SDR</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> SDR 9, 11, 13.6, 17, 21, 26 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อุณหภูมิทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> -40 ถึง 60 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>°C</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 20, 32, 50, 63, 75, 90, 110, 160, 200, 250, 315, 400, 500, 630 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> ดำ, น้ำเงิน (Blue Stripe) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ความหนาแน่น</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 0.941-0.965 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>g/cm³</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อายุการใช้งาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <uLine truncated
@@ -1,42 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อ PPR Thai PPR มาตรฐาน มอก."><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อ PPR Thai PPR"><meta property="og:description" content="ท่อ PPR Thai PPR มาตรฐาน มอก."><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อ PPR Thai PPR | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อ PPR Thai PPR </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อ PPR Thai PPR คุณภาพสูง มาตรฐาน มอก. เหมาะสำหรับงานประปาและระบบน้ำ </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อ-ppr-thai-ppr">ท่อ PPR Thai PPR</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อ PPR Thai PPR เป็นท่อพลาสติกพีพีอาร์ <strong>ผลิตในประเทศไทย</strong> ผ่านมาตรฐาน มอก. สำหรับใช้ในงานระบบประปาและระบบน้ำ ท่อ Thai PPR มีคุณสมบัติทนทานต่อความร้อนและความดัน เหมาะสำหรับงานประปาน้ำเย็นและน้ำร้อน</p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>ด้วยราคาที่เป็นมิตรกับงบประมาณ ท่อ PPR Thai PPR เป็นทางเลือกที่คุ้มค่าสำหรับโครงการก่อสร้างทุกขนาด</p>
<h3 id="ข้อดีของท่อ-thai-ppr">ข้อดีของท่อ Thai PPR</h3>
<ol>
<li><strong>ผลิตในไทย</strong> - ราคาประหยัด สนับสนุนสินค้าไทย</li>
<li><strong>มาตรฐาน มอก.</strong> - รับรองคุณภาพ ตรวจสอบได้</li>
<li><strong>ทนความร้อน</strong> - ใช้งานได้สูงถึง 70°C</li>
<li><strong>ไม่เกิดสนิม</strong> - ไม่มีการกัดกร่อนจากสารเคมี</li>
<li><strong>ติดตั้งง่าย</strong> - เชื่อมด้วยความร้อน ไม่ต้องใช้กาว</li>
<li><strong>ปลอดภัย</strong> - ใช้กับน้ำดื่มได้</li>
<li><strong>น้ำหนักเบา</strong> - ขนส่งและติดตั้งสะดวก</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรับ">เหมาะสำหรับ</h3>
<ul>
<li>ระบบประปาภายในอาคาร</li>
<li>ระบบน้ำเย็น</li>
<li>งานก่อสร้างที่อยู่อาศัย</li>
<li>โครงการจัดสรร</li>
<li>งานประปาขนาดเล็กและกลาง</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อ PPR Thai PPR ผ่านมาตรฐาน:</p>
<ul>
<li>✅ <strong>มอก. 248-2549</strong> - มาตรฐานผลิตภัณฑ์อุตสาหกรรม</li>
</ul>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อ-thai-ppr-ต่างจากท่อ-ppr-ตราช้างอย่างไร">ท่อ Thai PPR ต่างจากท่อ PPR ตราช้างอย่างไร?</h3>
<p>ท่อ Thai PPR เป็นผลิตภัณฑ์ที่ผลิตในประเทศไทย ราคาประหยัดกว่า ในขณะที่ท่อ PPR ตราช้างเป็นผลิตภัณฑ์จาก SCG มีมาตรฐานสากลที่หลากหลายกว่า</p>
<h3 id="ท่อ-thai-ppr-รับประกันคุณภาพหรือไม่">ท่อ Thai PPR รับประกันคุณภาพหรือไม่?</h3>
<p>ได้ ท่อ Thai PPR ผ่านมาตรฐาน มอก. 248-2549 สามารถตรวจสอบคุณภาพได้</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C%E0%B8%95%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B9%89%E0%B8%B2%E0%B8%87/">ท่อพีพีอาร์ตราช้าง</a></li>
<li><a href="/pp-r-pp-rct-poloplast/">ท่อ PP-R/PP-RCT POLOPLAST</a></li>
<li><a href="/%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C/">เครื่องเชื่อมท่อพีพีอาร์</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PP-R (Polypropylene Random Copolymer) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> มอก. 248-2549 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>แรงดันทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PN10, PN16, PN20 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>bar</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อุณหภูมิทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 0-70 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>°C</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 20, 25, 32, 40, 50, 63, 75, 90, 110 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> ขาว, เขียว, เทา </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อายุการใช้งาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 30-50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <ul class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ผลิตในประเทศไทย ราคาประหยัด</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ผ่านมาตรฐาน มอก. สามารถตรวจสอบได้</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ทนอุณหภูมิสูงสุด 70°C</spaLine truncated
@@ -1,59 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อพีพีอาร์ตราช้าง SCG มาตรฐาน DIN 8077/8078"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อพีพีอาร์ตราช้าง"><meta property="og:description" content="ท่อพีพีอาร์ตราช้าง SCG มาตรฐาน DIN 8077/8078"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อพีพีอาร์ตราช้าง | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อพีพีอาร์ตราช้าง </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อพีพีอาร์ตราช้าง (SCG) คุณภาพระดับสากล ทนอุณหภูมิสูง 95°C ทนความดัน 20 บาร์ อายุการใช้งาน 50 ปี </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อพีพีอาร์ตราช้าง-ppr-elephant-pipe">ท่อพีพีอาร์ตราช้าง (PPR Elephant Pipe)</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อพีพีอาร์ตราช้าง (PPR Elephant) ผลิตโดย SCG บริษัทชั้นนำของไทย เป็นท่อพลาสติกประเภท <strong>Polypropylene Random Copolymer (PP-R)</strong> ที่มีคุณภาพสูง ได้รับมาตรฐาน DIN 8077/8078 จากเยอรมนี และมาตรฐาน ISO 15874 ระดับสากล</p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>ท่อ PPR ตราช้างมีความทนทานต่ออุณหภูมิสูงสุด <strong>95°C</strong> และทนความดันได้ถึง <strong>20 บาร์ (PN20)</strong> เหมาะสำหรับงานระบบประปาน้ำร้อน น้ำเย็น และระบบทำความร้อน</p>
<h3 id="ข้อดีของท่อ-ppr-ตราช้าง">ข้อดีของท่อ PPR ตราช้าง</h3>
<ol>
<li><strong>ทนความร้อนสูง</strong> - ใช้งานกับน้ำร้อนได้ถึง 95°C</li>
<li><strong>ทนแรงดัน</strong> - รับแรงดันได้สูงสุด 20 บาร์</li>
<li><strong>ไม่เกิดสนิม</strong> - ไม่มีการกัดกร่อนจากสารเคมี</li>
<li><strong>ผิวเรียบ</strong> - ลดการสะสมของตะกรันในท่อ</li>
<li><strong>ติดตั้งง่าย</strong> - เชื่อมด้วยความร้อน ไม่ต้องใช้กาว</li>
<li><strong>ปลอดภัย</strong> - ใช้กับน้ำดื่มได้ ไม่ปนเปื้อนสารพิษ</li>
<li><strong>อายุยาวนาน</strong> - ใช้งานได้นาน 50 ปี</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรัก">เหมาะสำหรัก</h3>
<ul>
<li>ระบบประปาน้ำร้อนในโรงแรมและรีสอร์ท</li>
<li>ระบบน้ำเย็นในอาคารพาณิชย์</li>
<li>ระบบทำความร้อน (Heating System)</li>
<li>ระบบน้ำแรงดันสูงในโรงงาน</li>
<li>โรงพยาบาลและสถานพยาบาล</li>
<li>โครงการบ้านจัดสรร</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อพีพีอาร์ตราช้างได้รับมาตรฐานสากล:</p>
<ul>
<li>✅ <strong>DIN 8077/8078</strong> - มาตรฐานเยอรมัน</li>
<li>✅ <strong>ISO 15874</strong> - มาตรฐานสากล</li>
<li>✅ <strong>มอก. 248-2549</strong> - มาตรฐานผลิตภัณฑ์อุตสาหกรรมไทย</li>
<li>✅ <strong>SCG Quality Certified</strong> - รับรองคุณภาพโดย SCG</li>
</ul>
<h2 id="วิธีการติดตั้ง">วิธีการติดตั้ง</h2>
<p>การติดตั้งท่อ PPR ตราช้างใช้ระบบ <strong>เชื่อมความร้อน (Heat Fusion)</strong>:</p>
<ol>
<li>ตั้งเครื่องเชื่อมที่อุณหภูมิ <strong>260°C</strong></li>
<li>เสียบท่อและข้อต่อเข้าในแม่พิมพ์</li>
<li>รอให้พลาสติกหลอมตัว (เวลาตามขนาดท่อ)</li>
<li>ดึงออกและเชื่อมท่อกับข้อต่อทันที</li>
<li>รอให้เย็นตัว (ประมาณ 2-3 นาที)</li>
</ol>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อ-ppr-ตราช้างทนอุณหภูมิสูงสุดเท่าไร">ท่อ PPR ตราช้างทนอุณหภูมิสูงสุดเท่าไร?</h3>
<p>ท่อ PPR ตราช้างทนอุณหภูมิสูงสุด <strong>95°C</strong> ทำให้เหมาะสำหรับใช้กับระบบน้ำร้อนและระบบทำความร้อน</p>
<h3 id="ท่อ-ppr-ตราช้างอายุการใช้งานกี่ปี">ท่อ PPR ตราช้างอายุการใช้งานกี่ปี?</h3>
<p>ท่อ PPR ตราช้างมีอายุการใช้งานยาวนานถึง <strong>50 ปี</strong> ภายใต้การใช้งานตามมาตรฐาน</p>
<h3 id="ท่อ-ppr-แตกต่างจากท่อ-pvc-อย่างไร">ท่อ PPR แตกต่างจากท่อ PVC อย่างไร?</h3>
<p>ท่อ PPR ทนอุณหภูมิสูงกว่า (95°C vs 60°C) ทนแรงดันสูงกว่า ติดตั้งด้วยการเชื่อมความร้อนไม่ต้องใช้กาว และมีอายุการใช้งานยาวนานกว่า</p>
<h3 id="ท่อ-ppr-ตราช้างใช้กับน้ำดื่มได้หรือไม่">ท่อ PPR ตราช้างใช้กับน้ำดื่มได้หรือไม่?</h3>
<p><strong>ได้</strong> ท่อ PPR ตราช้างได้รับมาตรฐานสำหรับน้ำดื่ม ไม่ปล่อยสารพิษ และไม่เปลี่ยนแปลงรสชาติน้ำ</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%ADppr-thaippr/">ท่อ PPR Thai PPR</a></li>
<li><a href="/pp-r-pp-rct-poloplast/">ท่อ PP-R/PP-RCT POLOPLAST</a></li>
<li><a href="/%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%9E%E0%B8%B5%E0%B8%9E%E0%B8%B5%E0%B8%AD%E0%B8%B2%E0%B8%A3%E0%B9%8C/">เครื่องเชื่อมท่อพีพีอาร์</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PP-R (Polypropylene Random Copolymer) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> DIN 8077/8078, ISO 15874 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>แรงดันทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PN10, PN16, PN20 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>bar</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อุณหภูมิทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> -20 ถึง 95 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>°C</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 20, 25, 32, 40, 50, 63, 75, 90, 110 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ความหนาผนัง</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> SDR 7.4, 11, 17.6 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> ขาว, เขียว </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อายุการใช้งาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <ul class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ทนอุณหภูมิสูงสุด 95°C เหมาะกับน้ำร้อน</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ทนความดัน PN20 (20 บาร์)</Line truncated
@@ -1,59 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อระบายน้ำไซเลนท์ 22dB Push Fit"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อระบายน้ำ 3 ชั้น ไซเลนท์"><meta property="og:description" content="ท่อระบายน้ำไซเลนท์ 22dB Push Fit"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อระบายน้ำ 3 ชั้น ไซเลนท์ | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อระบายน้ำ 3 ชั้น ไซเลนท์ </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อระบายน้ำ XYLENT 3 ชั้น ลดเสียง 22dB ระบบ Push Fit ติดตั้งง่าย จาก Poloplast ยุโรป </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อระบายน้ำ-3-ชั้น-xylent-silent-pipe">ท่อระบายน้ำ 3 ชั้น XYLENT (Silent Pipe)</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อระบายน้ำ <strong>XYLENT</strong> เป็นท่อระบายน้ำระดับพรีเมียมจาก <strong>Poloplast ประเทศออสเตรีย</strong> มีโครงสร้าง <strong>3 ชั้น (Triple Layer)</strong> ช่วยลดเสียงรบกวนจากการไหลของน้ำได้ถึง <strong>22 เดซิเบล</strong></p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>ระบบ <strong>Push Fit</strong> ช่วยให้ติดตั้งง่าย ไม่ต้องใช้กาวหรือเครื่องมือพิเศษ ท่อ XYLENT เหมาะสำหรับอาคารที่ต้องการความเงียบ</p>
<h3 id="ข้อดีของท่อ-xylent">ข้อดีของท่อ XYLENT</h3>
<ol>
<li><strong>ลดเสียง 22 dB</strong> - เงียบกว่าท่อทั่วไป</li>
<li><strong>3 ชั้น</strong> - Triple Layer Structure</li>
<li><strong>Push Fit</strong> - ติดตั้งง่าย ไม่ต้องใช้กาว</li>
<li><strong>คุณภาพยุโรป</strong> - ผลิตในออสเตรีย</li>
<li><strong>ทนอุณหภูมิ</strong> - สูงถึง 95°C</li>
<li><strong>ไม่แตกหัก</strong> - PP เกรดสูง</li>
<li><strong>อายุ 50 ปี</strong> - ทนทานยาวนาน</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรับ">เหมาะสำหรับ</h3>
<ul>
<li><strong>ระบบระบายน้ำอาคาร</strong> - ท่อระบายน้ำทิ้ง</li>
<li><strong>โรงแรมและรีสอร์ท</strong> - ต้องการความเงียบ</li>
<li><strong>โรงพยาบาล</strong> - สถานที่ต้องการความสงบ</li>
<li><strong>อาคารพักอาศัยระดับสูง</strong> - คอนโดระดับพรีเมียม</li>
<li><strong>อาคารสำนักงาน</strong> - สำนักงานเกรด A</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อ XYLENT ผ่านมาตรฐาน:</p>
<ul>
<li>✅ <strong>EN 1451</strong> - มาตรฐานยุโรปสำหรับท่อระบายน้ำ</li>
<li>✅ <strong>DIN 19560</strong> - มาตรฐานเยอรมัน</li>
<li>✅ <strong>DIBt Approved</strong> - รับรองโดยสถาบันก่อสร้างเยอรมัน</li>
</ul>
<h2 id="โครงสร้าง-3-ชั้น">โครงสร้าง 3 ชั้น</h2>
<p>ท่อ XYLENT มีโครงสร้าง <strong>Triple Layer</strong>:</p>
<ol>
<li><strong>ชั้นใน</strong> - PP เรียบ ลดแรงเสียดทาน</li>
<li><strong>ชั้นกลาง</strong> - PP แร่ เพิ่มความแข็งแรง</li>
<li><strong>ชั้นนอก</strong> - PP เรียบ ป้องกันรอยขีดข่วน</li>
</ol>
<p>โครงสร้างนี้ช่วย <strong>ลดเสียงรบกวน</strong> ได้ถึง <strong>22 dB</strong></p>
<h2 id="ระบบ-push-fit">ระบบ Push Fit</h2>
<p><strong>Push Fit</strong> คือระบบติดตั้งที่:</p>
<ul>
<li>ไม่ต้องใช้กาว</li>
<li>ไม่ต้องใช้เครื่องมือพิเศษ</li>
<li>แค่ดันท่อเข้ากันก็ติดตั้งเสร็จ</li>
<li>ประหยัดเวลาและค่าแรง</li>
</ul>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อ-xylent-ลดเสียงได้กี่เดซิเบล">ท่อ XYLENT ลดเสียงได้กี่เดซิเบล?</h3>
<p>ท่อ XYLENT สามารถลดเสียงรบกวนจากการไหลของน้ำได้ถึง <strong>22 เดซิเบล</strong> ทำให้เหมาะสำหรับอาคารที่ต้องการความเงียบ</p>
<h3 id="ระบบ-push-fit-คืออะไร">ระบบ Push Fit คืออะไร?</h3>
<p>ระบบ Push Fit เป็นระบบติดตั้งที่ <strong>ไม่ต้องใช้กาวหรือเครื่องมือพิเศษ</strong> เพียงสองท่อเข้าหากันก็ติดตั้งเสร็จ สะดวกและรวดเร็ว</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/pp-r-pp-rct-poloplast/">ท่อ PP-R/PP-RCT POLOPLAST</a></li>
<li><a href="/%E0%B8%97%E0%B9%88%E0%B8%ADupvc/">ท่อ uPVC</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> PP (Polypropylene) 3 ชั้น </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> EN 1451, DIN 19560 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>การลดเสียง</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 22 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>dB</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อุณหภูมิทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> -20 ถึง 95 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>°C</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 32, 40, 50, 75, 90, 110, 125, 160 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ระบบติดตั้ง</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> Push Fit (Push-Fit) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> เทาอ่อน </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>อายุการใช้งาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>ปี</span> </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <ul class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ลดเสียงรบกวน 22 dB</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>โครงสร้าง 3 ชั้น (Triple Layer)</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-sLine truncated
@@ -1,51 +0,0 @@
<!DOCTYPE html><html lang="th"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="Astro v5.18.0"><meta name="description" content="ท่อเหล็กบุ PE BS1387 FM APPROVED"><!-- Favicon --><link rel="icon" type="image/svg+xml" href="/favicon.svg"><!-- Google Fonts: Kanit for Thai --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600;700&display=swap" rel="stylesheet"><!-- SEO --><meta property="og:title" content="ท่อไซเลอร์"><meta property="og:description" content="ท่อเหล็กบุ PE BS1387 FM APPROVED"><meta property="og:image" content="/og-image.jpg"><meta property="og:type" content="website"><meta name="twitter:card" content="summary_large_image"><title>ท่อไซเลอร์ | ดีล พลัส เทค</title><style>html{font-family:Kanit,system-ui,sans-serif}
@media(min-width:1280px){html{font-size:18px}}@media(min-width:1536px){html{font-size:20px}}
</style></head> <body class="flex flex-col min-h-screen"> <main class="py-12" data-astro-cid-o422f4lv> <article class="container mx-auto px-4 max-w-7xl" data-astro-cid-o422f4lv> <!-- Product Header --> <header class="mb-12" data-astro-cid-o422f4lv> <h1 class="text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold text-secondary-900 mb-6" data-astro-cid-o422f4lv> ท่อไซเลอร์ </h1> <p class="text-lg md:text-xl lg:text-2xl xl:text-3xl text-secondary-600 max-w-4xl" data-astro-cid-o422f4lv> ท่อไซเลอร์ ท่อเหล็กบุ PE ทนแรงดัน 50 bar มาตรฐาน BS1387 FM APPROVED สำหรับระบบดับเพลิง </p> </header> <!-- Content from Markdown --> <div class="prose prose-lg md:prose-xl lg:prose-2xl max-w-none mb-12" data-astro-cid-o422f4lv> <h1 id="ท่อไซเลอร์-syler-pipe">ท่อไซเลอร์ (Syler Pipe)</h1>
<h2 id="ภาพรวม">ภาพรวม</h2>
<p>ท่อไซเลอร์ (<strong>Syler Pipe</strong>) เป็นท่อเหล็กบุ PE (Polyethylene) ที่ออกแบบมาเฉพาะสำหรับ <strong>ระบบดับเพลิงและสปริงเกลอร์</strong> ท่อมีความทนทานสูง ทนแรงดันได้ถึง <strong>50 บาร์</strong></p>
<h2 id="คุณสมบัติเด่น">คุณสมบัติเด่น</h2>
<p>ผ่านมาตรฐาน <strong>BS1387</strong> จากอังกฤษและ <strong>FM APPROVED</strong> จาก Factory Mutual ท่อไซเลอร์มีการบุ PE ภายในเพื่อป้องกันการกัดกร่อนและสนิม</p>
<h3 id="ข้อดีของท่อไซเลอร์">ข้อดีของท่อไซเลอร์</h3>
<ol>
<li><strong>ทนแรงดันสูง</strong> - สูงถึง 50 บาร์</li>
<li><strong>มาตรฐานสากล</strong> - BS1387, FM APPROVED, UL Listed</li>
<li><strong>บุ PE</strong> - ป้องกันสนิมและการกัดกร่อน</li>
<li><strong>เหมาะสำหรับดับเพลิง</strong> - ออกแบบมาเฉพาะงานนี้</li>
<li><strong>ติดตั้งง่าย</strong> - ใช้ Groove Coupling</li>
<li><strong>ทนความร้อน</strong> - เหมาะกับระบบสปริงเกลอร์</li>
<li><strong>อายุการใช้งานยาว</strong> - ทนทานในระยะยาว</li>
</ol>
<h2 id="การใช้งาน">การใช้งาน</h2>
<h3 id="เหมาะสำหรับ">เหมาะสำหรับ</h3>
<ul>
<li><strong>ระบบสปริงเกลอร์</strong> - งานดับเพลิงอัตโนมัติ</li>
<li><strong>ระบบดับเพลิง</strong> - งานป้องกันอัคคีภัย</li>
<li><strong>โรงงานอุตสาหกรรม</strong> - ระบบความปลอดภัย</li>
<li><strong>อาคารพาณิชย์สูง</strong> - อาคารสูง คอนโด</li>
<li><strong>โรงแรมและโรงพยาบาล</strong> - สถานที่สาธารณะ</li>
</ul>
<h2 id="มาตรฐานและรับรอง">มาตรฐานและรับรอง</h2>
<p>ท่อไซเลอร์ผ่านมาตรฐาน:</p>
<ul>
<li>✅ <strong>BS1387</strong> - มาตรฐานอังกฤษสำหรับท่อเหล็ก</li>
<li>✅ <strong>FM APPROVED</strong> - Factory Mutual รับรองสำหรับระบบดับเพลิง</li>
<li>✅ <strong>UL Listed</strong> - รับรองความปลอดภัย</li>
</ul>
<h2 id="การติดตั้ง">การติดตั้ง</h2>
<p>ท่อไซเลอร์ติดตั้งโดยใช้ <strong>Groove Coupling</strong> ซึ่งเป็นระบบต่อท่อที่:</p>
<ul>
<li>ติดตั้งรวดเร็ว</li>
<li>ไม่ต้องใช้เครื่องเชื่อม</li>
<li>รองรับแรงดันสูง</li>
<li>ถอดประกอบได้สะดวก</li>
</ul>
<h2 id="คำถามที่พบบ่อย">คำถามที่พบบ่อย</h2>
<h3 id="ท่อไซเลอร์เหมาะกับงานอะไร">ท่อไซเลอร์เหมาะกับงานอะไร?</h3>
<p>ท่อไซเลอร์ออกแบบมาเฉพาะสำหรับ <strong>ระบบดับเพลิงและสปริงเกลอร์</strong> ผ่านมาตรฐาน FM APPROVED จึงมั่นใจได้ในความปลอดภัย</p>
<h3 id="ท่อไซเลอร์ต่างจากท่อเหล็กทั่วไปอย่างไร">ท่อไซเลอร์ต่างจากท่อเหล็กทั่วไปอย่างไร?</h3>
<p>ท่อไซเลอร์มีการ <strong>บุ PE ภายในท่อ</strong> ป้องกันการเกิดสนิมและการกัดกร่อน ทำให้มีอายุการใช้งานยาวนานกว่าท่อเหล็กทั่วไป</p>
<h2 id="สินค้าที่เกี่ยวข้อง">สินค้าที่เกี่ยวข้อง</h2>
<ul>
<li><a href="/realflex/">Realflex</a></li>
<li><a href="/%E0%B8%AD%E0%B8%B8%E0%B8%9B%E0%B8%81%E0%B8%A3%E0%B8%93%E0%B9%8C%E0%B8%97%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%A3%E0%B8%B9%E0%B8%9F/">ท่อและข้อต่อ Groove</a></li>
</ul> </div> <!-- Product Tables Section --> <!-- Specifications --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>ข้อมูลจำเพาะ</h2> <div class="bg-white rounded-2xl border-2 border-secondary-200 p-6 md:p-8 shadow-lg" data-astro-cid-o422f4lv> <dl class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>วัสดุ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> เหล็กบุ PE (Steel with PE lining) </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>มาตรฐาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> BS1387, FM APPROVED </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>แรงดันทนทาน</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 50 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>bar</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ขนาดท่อ</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 25, 32, 40, 50, 65, 80, 100, 150, 200 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>mm</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ความหนาผนัง</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> Schedule 40, 80 </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>ความยาว</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> 6 <span class="text-secondary-500 ml-2" data-astro-cid-o422f4lv>เมตร</span> </dd> </div><div class="flex flex-col md:flex-row md:justify-between border-b border-secondary-100 pb-4" data-astro-cid-o422f4lv> <dt class="text-base md:text-lg lg:text-xl font-semibold text-secondary-700 mb-2 md:mb-0 md:mr-4" data-astro-cid-o422f4lv>สี</dt> <dd class="text-base md:text-lg lg:text-xl text-secondary-900" data-astro-cid-o422f4lv> แดง (Red) - Fire Protection </dd> </div> </dl> </div> </section> <!-- Features --> <section class="mb-12" data-astro-cid-o422f4lv> <h2 class="text-3xl md:text-4xl lg:text-5xl font-bold text-secondary-900 mb-8" data-astro-cid-o422f4lv>คุณสมบัติเด่น</h2> <ul class="grid grid-cols-1 md:grid-cols-2 gap-6" data-astro-cid-o422f4lv> <li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ทนแรงดันสูง 50 บาร์</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>ผ่านมาตรฐาน BS1387 และ FM APPROVED</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o422f4lv> <span class="text-2xl md:text-3xl text-primary-600 flex-shrink-0" data-astro-cid-o422f4lv>✓</span> <span class="text-base md:text-lg lg:text-xl text-secondary-700" data-astro-cid-o422f4lv>บุ PE ป้องกันสนิมและการกัดกร่อน</span> </li><li class="flex items-start gap-4 bg-white p-6 rounded-xl border border-secondary-200 shadow" data-astro-cid-o4Line truncated
+1 -1
View File
@@ -1 +1 @@
[["Map",1,2,9,10],"meta::meta",["Map",3,4,5,6,7,8],"astro-version","5.18.0","content-config-digest","392f3618c90ce109","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"static\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":true,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[],\"actionBodySizeLimit\":1048576},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}","products",["Map",11,12,140,141,279,280,382,383,503,504,664,665],"ท่อไซเลอร์",{"id":11,"data":13,"body":84,"filePath":85,"digest":86,"rendered":87},{"id":14,"name":11,"nameEn":15,"slug":11,"description":16,"shortDescription":17,"keywords":18,"seoContent":27,"image":28,"specifications":29,"features":54,"applications":62,"certifications":68,"faq":70,"relatedProductIds":77,"schemaData":80},"syler","Syler Pipe","ท่อไซเลอร์ ท่อเหล็กบุ PE ทนแรงดัน 50 bar มาตรฐาน BS1387 FM APPROVED สำหรับระบบดับเพลิง","ท่อเหล็กบุ PE BS1387 FM APPROVED",[11,15,19,20,21,22,23,24,25,26],"ท่อเหล็กบุ PE","FM APPROVED","ท่อดับเพลิง","ท่อสปริงเกลอร์","BS1387","ท่อเหล็กชุบ PE","fire protection pipe","ท่อน้ำดับเพลิง","ท่อไซเลอร์ (Syler Pipe) เป็นท่อเหล็กบุ PE (Polyethylene) ที่ออกแบบมาเฉพาะสำหรับระบบดับเพลิงและสปริงเกลอร์ ท่อมีความทนทานสูง ทนแรงดันได้ถึง 50 บาร์ ผ่านมาตรฐาน BS1387 จากอังกฤษและ FM APPROVED จาก Factory Mutual","/images/2021/03/syler_000C.jpg",[30,33,36,40,44,47,51],{"label":31,"value":32},"วัสดุ","เหล็กบุ PE (Steel with PE lining)",{"label":34,"value":35},"มาตรฐาน","BS1387, FM APPROVED",{"label":37,"value":38,"unit":39},"แรงดันทนทาน","50","bar",{"label":41,"value":42,"unit":43},"ขนาดท่อ","25, 32, 40, 50, 65, 80, 100, 150, 200","mm",{"label":45,"value":46},"ความหนาผนัง","Schedule 40, 80",{"label":48,"value":49,"unit":50},"ความยาว","6","เมตร",{"label":52,"value":53},"สี","แดง (Red) - Fire Protection",[55,56,57,58,59,60,61],"ทนแรงดันสูง 50 บาร์","ผ่านมาตรฐาน BS1387 และ FM APPROVED","บุ PE ป้องกันสนิมและการกัดกร่อน","อายุการใช้งานยาวนาน","เหมาะสำหรับระบบดับเพลิง","ติดตั้งด้วย Groove Coupling","ทนทานต่อความร้อน",[63,64,65,66,67],"ระบบสปริงเกลอร์","ระบบดับเพลิง","โรงงานอุตสาหกรรม","อาคารพาณิชย์สูง","โรงแรมและโรงพยาบาล",[23,20,69],"UL Listed",[71,74],{"question":72,"answer":73},"ท่อไซเลอร์เหมาะกับงานอะไร?","ท่อไซเลอร์ออกแบบมาเฉพาะสำหรับระบบดับเพลิงและสปริงเกลอร์ ผ่านมาตรฐาน FM APPROVED จึงมั่นใจได้ในความปลอดภัย",{"question":75,"answer":76},"ท่อไซเลอร์ต่างจากท่อเหล็กทั่วไปอย่างไร?","ทLine truncated
[["Map",1,2,7,8,670,671],"meta::meta",["Map",3,4,5,6],"astro-version","5.18.0","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"static\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":true,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[],\"actionBodySizeLimit\":1048576},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}","products",["Map",9,10,173,174,292,293,398,399,474,475,565,566],"ท่อhdpe",{"id":9,"data":11,"body":114,"filePath":115,"digest":116,"rendered":117,"legacyId":172},{"id":12,"name":13,"nameEn":14,"slug":9,"description":15,"shortDescription":16,"image":17,"keywords":18,"seoContent":33,"specifications":34,"features":70,"applications":81,"certifications":90,"faq":94,"relatedProductIds":107,"schemaData":110},"hdpe","ท่อ HDPE","HDPE Pipe","ท่อ HDPE PE80/PE100 ทนแรงดัน PN25 อายุการใช้งาน 50 ปี มอก. สำหรับประปาและชลประทาน","ท่อเอชดีพีอี PE80/PE100 มาตรฐาน มอก.","/images/2021/03/hdpe-pipe_000C.jpg",[13,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"ท่อเอชดีพีอี","ท่อ PE","ท่อน้ำ HDPE","PE80","PE100","ท่อ PE100","ท่อ PE80","ท่อพีอี","High Density Polyethylene","ท่อชลประทาน","ท่อประปา HDPE","ท่อดำ PE","ท่อน้ำดำ","SDR pipe","ท่อ HDPE (High Density Polyethylene) หรือท่อเอชดีพีอี เป็นท่อพลาสติกคุณภาพสูงที่มีความทนทานและยืดหยุ่นสูง ผลิตจากเม็ดพลาสติก HDPE เกรด PE80 และ PE100 ท่อ HDPE สามารถทนแรงดันได้สูงถึง PN25 บาร์",[35,38,41,44,48,51,55,59,62,66],{"label":36,"value":37},"วัสดุ","HDPE (High Density Polyethylene)",{"label":39,"value":40},"เกรด","PE80, PE100",{"label":42,"value":43},"มาตรฐาน","มอก. 827-2547, ISO 4427",{"label":45,"value":46,"unit":47},"แรงดันทนทาน","PN4 - PN25","bar",{"label":49,"value":50},"SDR","SDR 9, 11, 13.6, 17, 21, 26",{"label":52,"value":53,"unit":54},"อุณหภูมิทนทาน","-40 ถึง 60","°C",{"label":56,"value":57,"unit":58},"ขนาดท่อ","20, 32, 50, 63, 75, 90, 110, 160, 200, 250, 315, 400, 500, 630","mm",{"label":60,"value":61},"สี","ดำ, น้ำเงิน (Blue Stripe)",{"label":63,"value":64,"unit":65},"ความหนาแน่น","0.941-0.965","g/cm³",{"label":67,"value":68,"unit":69},"อายุการใช้งาน","50","ปี",[71,72,73,74,75,76,77,78,79,80],"ทนแรงดันสูงถึง PN25 บาร์","ทนทานต่อแรงกระแทกและการกัดกร่อน","ยืดหยุ่นสูง ทนต่อการเคลื่อนไหวของดิน","ไม่เกิดสนิม ไม่เปรอะเปื้อน","น้ำหนักเบา ขนส่งและติดตั้งง่าย","รอยต่อแน่นหนาด้วย Butt Fusion","ทนทานต่อสารเคมีและกรดด่าง","อายุการใช้งานยาวนาน 50 ปี","ผ่านมาตรฐาน มอก. 827-2547","เหมาะสำหรับงานฝังดิน",[82,83,84,85,86,87,88,89],"ระบบประปา","ระบบชลประทาน","ระบบน้ำเสีย","ท่อส่งก๊าซ","Line truncated
+1
View File
@@ -0,0 +1 @@
../astro-consent/dist/cli.cjs
+555 -3
View File
@@ -137,7 +137,6 @@
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.8.1.tgz",
"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==",
"ideallyInert": true,
"license": "MIT",
"optional": true,
"dependencies": {
@@ -1118,6 +1117,181 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@libsql/client": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.17.0.tgz",
"integrity": "sha512-TLjSU9Otdpq0SpKHl1tD1Nc9MKhrsZbCFGot3EbCxRa8m1E5R1mMwoOjKMMM31IyF7fr+hPNHLpYfwbMKNusmg==",
"license": "MIT",
"dependencies": {
"@libsql/core": "^0.17.0",
"@libsql/hrana-client": "^0.9.0",
"js-base64": "^3.7.5",
"libsql": "^0.5.22",
"promise-limit": "^2.7.0"
}
},
"node_modules/@libsql/core": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/@libsql/core/-/core-0.17.0.tgz",
"integrity": "sha512-hnZRnJHiS+nrhHKLGYPoJbc78FE903MSDrFJTbftxo+e52X+E0Y0fHOCVYsKWcg6XgB7BbJYUrz/xEkVTSaipw==",
"license": "MIT",
"dependencies": {
"js-base64": "^3.7.5"
}
},
"node_modules/@libsql/darwin-arm64": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/darwin-arm64/-/darwin-arm64-0.5.22.tgz",
"integrity": "sha512-4B8ZlX3nIDPndfct7GNe0nI3Yw6ibocEicWdC4fvQbSs/jdq/RC2oCsoJxJ4NzXkvktX70C1J4FcmmoBy069UA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@libsql/darwin-x64": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/darwin-x64/-/darwin-x64-0.5.22.tgz",
"integrity": "sha512-ny2HYWt6lFSIdNFzUFIJ04uiW6finXfMNJ7wypkAD8Pqdm6nAByO+Fdqu8t7sD0sqJGeUCiOg480icjyQ2/8VA==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@libsql/hrana-client": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@libsql/hrana-client/-/hrana-client-0.9.0.tgz",
"integrity": "sha512-pxQ1986AuWfPX4oXzBvLwBnfgKDE5OMhAdR/5cZmRaB4Ygz5MecQybvwZupnRz341r2CtFmbk/BhSu7k2Lm+Jw==",
"license": "MIT",
"dependencies": {
"@libsql/isomorphic-ws": "^0.1.5",
"cross-fetch": "^4.0.0",
"js-base64": "^3.7.5",
"node-fetch": "^3.3.2"
}
},
"node_modules/@libsql/isomorphic-ws": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/@libsql/isomorphic-ws/-/isomorphic-ws-0.1.5.tgz",
"integrity": "sha512-DtLWIH29onUYR00i0GlQ3UdcTRC6EP4u9w/h9LxpUZJWRMARk6dQwZ6Jkd+QdwVpuAOrdxt18v0K2uIYR3fwFg==",
"license": "MIT",
"dependencies": {
"@types/ws": "^8.5.4",
"ws": "^8.13.0"
}
},
"node_modules/@libsql/linux-arm-gnueabihf": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-arm-gnueabihf/-/linux-arm-gnueabihf-0.5.22.tgz",
"integrity": "sha512-3Uo3SoDPJe/zBnyZKosziRGtszXaEtv57raWrZIahtQDsjxBVjuzYQinCm9LRCJCUT5t2r5Z5nLDPJi2CwZVoA==",
"cpu": [
"arm"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/linux-arm-musleabihf": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-arm-musleabihf/-/linux-arm-musleabihf-0.5.22.tgz",
"integrity": "sha512-LCsXh07jvSojTNJptT9CowOzwITznD+YFGGW+1XxUr7fS+7/ydUrpDfsMX7UqTqjm7xG17eq86VkWJgHJfvpNg==",
"cpu": [
"arm"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/linux-arm64-gnu": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-arm64-gnu/-/linux-arm64-gnu-0.5.22.tgz",
"integrity": "sha512-KSdnOMy88c9mpOFKUEzPskSaF3VLflfSUCBwas/pn1/sV3pEhtMF6H8VUCd2rsedwoukeeCSEONqX7LLnQwRMA==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/linux-arm64-musl": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-arm64-musl/-/linux-arm64-musl-0.5.22.tgz",
"integrity": "sha512-mCHSMAsDTLK5YH//lcV3eFEgiR23Ym0U9oEvgZA0667gqRZg/2px+7LshDvErEKv2XZ8ixzw3p1IrBzLQHGSsw==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/linux-x64-gnu": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-x64-gnu/-/linux-x64-gnu-0.5.22.tgz",
"integrity": "sha512-kNBHaIkSg78Y4BqAdgjcR2mBilZXs4HYkAmi58J+4GRwDQZh5fIUWbnQvB9f95DkWUIGVeenqLRFY2pcTmlsew==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/linux-x64-musl": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/linux-x64-musl/-/linux-x64-musl-0.5.22.tgz",
"integrity": "sha512-UZ4Xdxm4pu3pQXjvfJiyCzZop/9j/eA2JjmhMaAhe3EVLH2g11Fy4fwyUp9sT1QJYR1kpc2JLuybPM0kuXv/Tg==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@libsql/win32-x64-msvc": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/@libsql/win32-x64-msvc/-/win32-x64-msvc-0.5.22.tgz",
"integrity": "sha512-Fj0j8RnBpo43tVZUVoNK6BV/9AtDUM5S7DF3LB4qTYg1LMSZqi3yeCneUTLJD6XomQJlZzbI4mst89yspVSAnA==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@neon-rs/load": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.4.tgz",
"integrity": "sha512-kTPhdZyTQxB+2wpiRcFWrDcejc4JI6tkPuS7UZCG4l6Zvc5kU/gGQ/ozvHTh1XR5tS+UlfAfGuPajjzQjCiHCw==",
"license": "MIT"
},
"node_modules/@oslojs/encoding": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@oslojs/encoding/-/encoding-1.1.0.tgz",
@@ -1884,12 +2058,30 @@
"@types/unist": "*"
}
},
"node_modules/@types/node": {
"version": "25.4.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.4.0.tgz",
"integrity": "sha512-9wLpoeWuBlcbBpOY3XmzSTG3oscB6xjBEEtn+pYXTfhyXhIxC5FsBer2KTopBlvKEiW9l13po9fq+SJY/5lkhw==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.18.0"
}
},
"node_modules/@types/unist": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
"license": "MIT"
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -2118,6 +2310,21 @@
"sharp": "^0.34.0"
}
},
"node_modules/astro-consent": {
"version": "1.0.17",
"resolved": "https://registry.npmjs.org/astro-consent/-/astro-consent-1.0.17.tgz",
"integrity": "sha512-CxebtdACUZmYdZcDoe0fEvu8EubEinpEYhI1Dobdeinl5a0exBGw2RSYeH1HM6k54AmS7R7BMwZTBX3oAuzImg==",
"license": "MIT",
"bin": {
"astro-consent": "dist/cli.cjs"
},
"engines": {
"node": ">=18.0.0"
},
"peerDependencies": {
"astro": "^4.0.0 || ^5.0.0"
}
},
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -2330,6 +2537,35 @@
"integrity": "sha512-+W7VmiVINB+ywl1HGXJXmrqkOhpKrIiVZV6tQuV54ZyQC7MMuBt81Vc336GMLoHBq5hV/F9eXgt5Mnx0Rha5Fg==",
"license": "MIT"
},
"node_modules/cross-fetch": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz",
"integrity": "sha512-uKm5PU+MHTootlWEY+mZ4vvXoCn4fLQxT9dSc1sXVMSFkINTJVN8cAQROpwcKm8bJ/c7rgZVIBWzH5T78sNZZw==",
"license": "MIT",
"dependencies": {
"node-fetch": "^2.7.0"
}
},
"node_modules/cross-fetch/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/crossws": {
"version": "0.3.5",
"resolved": "https://registry.npmjs.org/crossws/-/crossws-0.3.5.tgz",
@@ -2425,6 +2661,15 @@
"integrity": "sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==",
"license": "CC0-1.0"
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -2598,6 +2843,131 @@
"url": "https://github.com/fb55/domutils?sponsor=1"
}
},
"node_modules/drizzle-orm": {
"version": "0.45.1",
"resolved": "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.1.tgz",
"integrity": "sha512-Te0FOdKIistGNPMq2jscdqngBRfBpC8uMFVwqjf6gtTVJHIQ/dosgV/CLBU2N4ZJBsXL5savCba9b0YJskKdcA==",
"license": "Apache-2.0",
"peerDependencies": {
"@aws-sdk/client-rds-data": ">=3",
"@cloudflare/workers-types": ">=4",
"@electric-sql/pglite": ">=0.2.0",
"@libsql/client": ">=0.10.0",
"@libsql/client-wasm": ">=0.10.0",
"@neondatabase/serverless": ">=0.10.0",
"@op-engineering/op-sqlite": ">=2",
"@opentelemetry/api": "^1.4.1",
"@planetscale/database": ">=1.13",
"@prisma/client": "*",
"@tidbcloud/serverless": "*",
"@types/better-sqlite3": "*",
"@types/pg": "*",
"@types/sql.js": "*",
"@upstash/redis": ">=1.34.7",
"@vercel/postgres": ">=0.8.0",
"@xata.io/client": "*",
"better-sqlite3": ">=7",
"bun-types": "*",
"expo-sqlite": ">=14.0.0",
"gel": ">=2",
"knex": "*",
"kysely": "*",
"mysql2": ">=2",
"pg": ">=8",
"postgres": ">=3",
"sql.js": ">=1",
"sqlite3": ">=5"
},
"peerDependenciesMeta": {
"@aws-sdk/client-rds-data": {
"optional": true
},
"@cloudflare/workers-types": {
"optional": true
},
"@electric-sql/pglite": {
"optional": true
},
"@libsql/client": {
"optional": true
},
"@libsql/client-wasm": {
"optional": true
},
"@neondatabase/serverless": {
"optional": true
},
"@op-engineering/op-sqlite": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
},
"@planetscale/database": {
"optional": true
},
"@prisma/client": {
"optional": true
},
"@tidbcloud/serverless": {
"optional": true
},
"@types/better-sqlite3": {
"optional": true
},
"@types/pg": {
"optional": true
},
"@types/sql.js": {
"optional": true
},
"@upstash/redis": {
"optional": true
},
"@vercel/postgres": {
"optional": true
},
"@xata.io/client": {
"optional": true
},
"better-sqlite3": {
"optional": true
},
"bun-types": {
"optional": true
},
"expo-sqlite": {
"optional": true
},
"gel": {
"optional": true
},
"knex": {
"optional": true
},
"kysely": {
"optional": true
},
"mysql2": {
"optional": true
},
"pg": {
"optional": true
},
"postgres": {
"optional": true
},
"prisma": {
"optional": true
},
"sql.js": {
"optional": true
},
"sqlite3": {
"optional": true
}
}
},
"node_modules/dset": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/dset/-/dset-3.1.4.tgz",
@@ -2735,6 +3105,29 @@
}
}
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "paypal",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"dependencies": {
"node-domexception": "^1.0.0",
"web-streams-polyfill": "^3.0.3"
},
"engines": {
"node": "^12.20 || >= 14.13"
}
},
"node_modules/flattie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/flattie/-/flattie-1.1.1.tgz",
@@ -2765,12 +3158,23 @@
"node": ">=20"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
"license": "MIT",
"dependencies": {
"fetch-blob": "^3.1.2"
},
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"hasInstallScript": true,
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
@@ -3117,6 +3521,12 @@
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/js-base64": {
"version": "3.7.8",
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.8.tgz",
"integrity": "sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==",
"license": "BSD-3-Clause"
},
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
@@ -3138,6 +3548,47 @@
"node": ">=6"
}
},
"node_modules/libsql": {
"version": "0.5.22",
"resolved": "https://registry.npmjs.org/libsql/-/libsql-0.5.22.tgz",
"integrity": "sha512-NscWthMQt7fpU8lqd7LXMvT9pi+KhhmTHAJWUB/Lj6MWa0MKFv0F2V4C6WKKpjCVZl0VwcDz4nOI3CyaT1DDiA==",
"cpu": [
"x64",
"arm64",
"wasm32",
"arm"
],
"license": "MIT",
"os": [
"darwin",
"linux",
"win32"
],
"dependencies": {
"@neon-rs/load": "^0.0.4",
"detect-libc": "2.0.2"
},
"optionalDependencies": {
"@libsql/darwin-arm64": "0.5.22",
"@libsql/darwin-x64": "0.5.22",
"@libsql/linux-arm-gnueabihf": "0.5.22",
"@libsql/linux-arm-musleabihf": "0.5.22",
"@libsql/linux-arm64-gnu": "0.5.22",
"@libsql/linux-arm64-musl": "0.5.22",
"@libsql/linux-x64-gnu": "0.5.22",
"@libsql/linux-x64-musl": "0.5.22",
"@libsql/win32-x64-msvc": "0.5.22"
}
},
"node_modules/libsql/node_modules/detect-libc": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
"license": "Apache-2.0",
"engines": {
"node": ">=8"
}
},
"node_modules/lightningcss": {
"version": "1.31.1",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz",
@@ -4295,6 +4746,44 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
"deprecated": "Use your platform's native DOMException instead",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "github",
"url": "https://paypal.me/jimmywarting"
}
],
"license": "MIT",
"engines": {
"node": ">=10.5.0"
}
},
"node_modules/node-fetch": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"license": "MIT",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
}
},
"node_modules/node-fetch-native": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz",
@@ -4502,6 +4991,12 @@
"node": ">=6"
}
},
"node_modules/promise-limit": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/promise-limit/-/promise-limit-2.7.0.tgz",
"integrity": "sha512-7nJ6v5lnJsXwGprnGXga4wx6d1POjvi5Qmf1ivTRxTjH4Z/9Czja/UCMLVmB9N93GeWOU93XaFaEt6jbuoagNw==",
"license": "ISC"
},
"node_modules/prompts": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
@@ -5055,6 +5550,12 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/trim-lines": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
@@ -5099,7 +5600,6 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"ideallyInert": true,
"license": "0BSD",
"optional": true
},
@@ -5147,6 +5647,12 @@
"integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==",
"license": "MIT"
},
"node_modules/undici-types": {
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"license": "MIT"
},
"node_modules/unified": {
"version": "11.0.5",
"resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz",
@@ -6023,6 +6529,31 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
"license": "MIT",
"engines": {
"node": ">= 8"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/which-pm-runs": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.1.0.tgz",
@@ -6064,6 +6595,27 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xxhash-wasm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xxhash-wasm/-/xxhash-wasm-1.1.0.tgz",
+6 -6
View File
@@ -1,25 +1,25 @@
{
"hash": "bd82ba1f",
"hash": "f37b1786",
"configHash": "06117f6a",
"lockfileHash": "503a0907",
"browserHash": "4ee2f0da",
"lockfileHash": "746a67c5",
"browserHash": "b218182c",
"optimized": {
"astro > cssesc": {
"src": "../../cssesc/cssesc.js",
"file": "astro___cssesc.js",
"fileHash": "ac027a7e",
"fileHash": "fb1b0483",
"needsInterop": true
},
"astro > aria-query": {
"src": "../../aria-query/lib/index.js",
"file": "astro___aria-query.js",
"fileHash": "e77ce3d0",
"fileHash": "27c7e1dc",
"needsInterop": true
},
"astro > axobject-query": {
"src": "../../axobject-query/lib/index.js",
"file": "astro___axobject-query.js",
"fileHash": "052bb1ed",
"fileHash": "17fab5c8",
"needsInterop": true
}
},
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Toyobayashi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,665 @@
export declare type Ptr = number | bigint
export declare interface IBuffer extends Uint8Array {}
export declare interface BufferCtor {
readonly prototype: IBuffer
/** @deprecated */
new (...args: any[]): IBuffer
from: {
(buffer: ArrayBufferLike): IBuffer
(buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer
}
alloc: (size: number) => IBuffer
isBuffer: (obj: unknown) => obj is IBuffer
}
export declare const enum GlobalHandle {
UNDEFINED = 1,
NULL,
FALSE,
TRUE,
GLOBAL
}
export declare const enum Version {
NODE_API_SUPPORTED_VERSION_MIN = 1,
NODE_API_DEFAULT_MODULE_API_VERSION = 8,
NODE_API_SUPPORTED_VERSION_MAX = 10,
NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type Pointer<T> = number
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type PointerPointer<T> = number
export declare type FunctionPointer<T extends (...args: any[]) => any> = Pointer<T>
export declare type Const<T> = T
export declare type void_p = Pointer<void>
export declare type void_pp = Pointer<void_p>
export declare type bool = number
export declare type char = number
export declare type char_p = Pointer<char>
export declare type unsigned_char = number
export declare type const_char = Const<char>
export declare type const_char_p = Pointer<const_char>
export declare type char16_t_p = number
export declare type const_char16_t_p = number
export declare type short = number
export declare type unsigned_short = number
export declare type int = number
export declare type unsigned_int = number
export declare type long = number
export declare type unsigned_long = number
export declare type long_long = bigint
export declare type unsigned_long_long = bigint
export declare type float = number
export declare type double = number
export declare type long_double = number
export declare type size_t = number
export declare type int8_t = number
export declare type uint8_t = number
export declare type int16_t = number
export declare type uint16_t = number
export declare type int32_t = number
export declare type uint32_t = number
export declare type int64_t = bigint
export declare type uint64_t = bigint
export declare type napi_env = Pointer<unknown>
export declare type napi_value = Pointer<unknown>
export declare type napi_ref = Pointer<unknown>
export declare type napi_deferred = Pointer<unknown>
export declare type napi_handle_scope = Pointer<unknown>
export declare type napi_escapable_handle_scope = Pointer<unknown>
export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value>
export declare type napi_callback_info = Pointer<unknown>
export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value>
export declare interface napi_extended_error_info {
error_message: const_char_p
engine_reserved: void_p
engine_error_code: uint32_t
error_code: napi_status
}
export declare interface napi_property_descriptor {
// One of utf8name or name should be NULL.
utf8name: const_char_p
name: napi_value
method: napi_callback
getter: napi_callback
setter: napi_callback
value: napi_value
/* napi_property_attributes */
attributes: number
data: void_p
}
export declare type napi_finalize = FunctionPointer<(
env: napi_env,
finalize_data: void_p,
finalize_hint: void_p
) => void>
export declare interface node_module {
nm_version: int32_t
nm_flags: uint32_t
nm_filename: Pointer<const_char>
nm_register_func: napi_addon_register_func
nm_modname: Pointer<const_char>
nm_priv: Pointer<void>
reserved: PointerPointer<void>
}
export declare interface napi_node_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
release: const_char_p
}
export declare interface emnapi_emscripten_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
}
export declare const enum napi_status {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, // unused
napi_no_external_buffers_allowed,
napi_cannot_run_js
}
export declare const enum napi_property_attributes {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
/// #ifdef NAPI_EXPERIMENTAL
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable
/// #endif // NAPI_EXPERIMENTAL
}
export declare const enum napi_valuetype {
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint
}
export declare const enum napi_typedarray_type {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
}
export declare const enum napi_key_collection_mode {
napi_key_include_prototypes,
napi_key_own_only
}
export declare const enum napi_key_filter {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
}
export declare const enum napi_key_conversion {
napi_key_keep_numbers,
napi_key_numbers_to_strings
}
export declare const enum emnapi_memory_view_type {
emnapi_int8_array,
emnapi_uint8_array,
emnapi_uint8_clamped_array,
emnapi_int16_array,
emnapi_uint16_array,
emnapi_int32_array,
emnapi_uint32_array,
emnapi_float32_array,
emnapi_float64_array,
emnapi_bigint64_array,
emnapi_biguint64_array,
emnapi_float16_array,
emnapi_data_view = -1,
emnapi_buffer = -2
}
export declare const enum napi_threadsafe_function_call_mode {
napi_tsfn_nonblocking,
napi_tsfn_blocking
}
export declare const enum napi_threadsafe_function_release_mode {
napi_tsfn_release,
napi_tsfn_abort
}
export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
export declare class ConstHandle<S extends undefined | null | boolean | typeof globalThis> extends Handle<S> {
constructor(id: number, value: S);
dispose(): void;
}
export declare class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
envStore: Store<Env>;
scopeStore: ScopeStore;
refStore: Store<Reference>;
deferredStore: Store<Deferred<any>>;
handleStore: HandleStore;
private readonly refCounter?;
private readonly cleanupQueue;
feature: {
supportReflect: boolean;
supportFinalizer: boolean;
supportWeakSymbol: boolean;
supportBigInt: boolean;
supportNewFunction: boolean;
canSetFunctionName: boolean;
setImmediate: (callback: () => void) => void;
Buffer: BufferCtor | undefined;
MessageChannel: {
new (): MessageChannel;
prototype: MessageChannel;
} | undefined;
};
constructor();
/**
* Suppress the destroy on `beforeExit` event in Node.js.
* Call this method if you want to keep the context and
* all associated {@link Env | Env} alive,
* this also means that cleanup hooks will not be called.
* After call this method, you should call
* {@link Context.destroy | `Context.prototype.destroy`} method manually.
*/
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createDeferred<T = any>(value: IDeferrdValue<T>): Deferred<T>;
createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope | null;
addToCurrentScope<V>(value: V): Handle<V>;
openScope(envObject?: Env): HandleScope;
closeScope(envObject?: Env, _scope?: HandleScope): void;
ensureHandle<S>(value: S): Handle<S>;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
/**
* Destroy the context and call cleanup hooks.
* Associated {@link Env | Env} will be destroyed.
*/
destroy(): void;
}
export declare function createContext(): Context;
export declare class Deferred<T = any> implements IStoreValue {
static create<T = any>(ctx: Context, value: IDeferrdValue<T>): Deferred;
id: number;
ctx: Context;
value: IDeferrdValue<T>;
constructor(ctx: Context, value: IDeferrdValue<T>);
resolve(value: T): void;
reject(reason?: any): void;
dispose(): void;
}
export declare class EmnapiError extends Error {
constructor(message?: string);
}
export declare abstract class Env implements IStoreValue {
readonly ctx: Context;
moduleApiVersion: number;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
id: number;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
tryCatch: TryCatch;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
lastError: {
errorCode: napi_status;
engineErrorCode: number;
engineReserved: Ptr;
};
inGcFinalizer: boolean;
constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never);
/** @virtual */
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
ensureHandle<S>(value: S): Handle<S>;
ensureHandleId(value: any): napi_value;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status;
getReturnStatus(): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
/** @virtual */
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
/** @virtual */
enqueueFinalizer(finalizer: RefTracker): void;
/** @virtual */
dequeueFinalizer(finalizer: RefTracker): void;
/** @virtual */
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number;
}
/** @public */
declare interface External_2 extends Record<any, any> {
}
/** @public */
declare const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export declare class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export declare function getDefaultContext(): Context;
/** @public */
export declare function getExternalValue(external: External_2): number | bigint;
export declare class Handle<S> {
id: number;
value: S;
constructor(id: number, value: S);
data(): void_p;
isNumber(): boolean;
isBigInt(): boolean;
isString(): boolean;
isFunction(): boolean;
isExternal(): boolean;
isObject(): boolean;
isArray(): boolean;
isArrayBuffer(): boolean;
isTypedArray(): boolean;
isBuffer(BufferConstructor?: BufferCtor): boolean;
isDataView(): boolean;
isDate(): boolean;
isPromise(): boolean;
isBoolean(): boolean;
isUndefined(): boolean;
isSymbol(): boolean;
isNull(): boolean;
dispose(): void;
}
export declare class HandleScope {
handleStore: HandleStore;
id: number;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number);
add<V>(value: V): Handle<V>;
addExternal(data: void_p): Handle<object>;
dispose(): void;
escape(handle: number): Handle<any> | null;
escapeCalled(): boolean;
}
export declare class HandleStore {
static UNDEFINED: ConstHandle<undefined>;
static NULL: ConstHandle<null>;
static FALSE: ConstHandle<false>;
static TRUE: ConstHandle<true>;
static GLOBAL: ConstHandle<typeof globalThis>;
static MIN_ID: 6;
private readonly _values;
private _next;
push<S>(value: S): Handle<S>;
erase(start: number, end: number): void;
get(id: Ptr): Handle<any> | undefined;
swap(a: number, b: number): void;
dispose(): void;
}
export declare interface ICallbackInfo {
thiz: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export declare interface IDeferrdValue<T = any> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
}
export declare interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
/** @public */
export declare function isExternal(object: unknown): object is External_2;
export declare function isReferenceType(v: any): v is object;
export declare interface IStoreValue {
id: number;
dispose(): void;
[x: string]: any;
}
export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export declare class NodeEnv extends Env {
filename: string;
private readonly nodeBinding?;
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export declare class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class Persistent<T> {
private _ref;
private _param;
private _callback;
private static readonly _registry;
constructor(value: T);
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export declare class Reference extends RefTracker implements IStoreValue {
private static weakCallback;
id: number;
envObject: Env;
private readonly canBeWeak;
private _refcount;
private readonly _ownership;
persistent: Persistent<object>;
static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
ref(): number;
unref(): number;
get(envObject?: Env): napi_value;
/** @virtual */
resetFinalizer(): void;
/** @virtual */
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
/** @virtual */
protected callUserFinalizer(): void;
/** @virtual */
protected invokeFinalizerFromGC(): void;
private _setWeak;
finalize(): void;
dispose(): void;
}
export declare enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export declare class ReferenceWithData extends Reference {
private readonly _data;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
private constructor();
data(): void_p;
}
export declare class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
private constructor();
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export declare class RefTracker {
/** @virtual */
dispose(): void;
/** @virtual */
finalize(): void;
private _next;
private _prev;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export declare class ScopeStore {
private readonly _rootScope;
currentScope: HandleScope;
private readonly _values;
constructor();
get(id: number): HandleScope | undefined;
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
dispose(): void;
}
export declare class Store<V extends IStoreValue> {
protected _values: Array<V | undefined>;
private _freeList;
private _size;
constructor();
add(value: V): void;
get(id: Ptr): V | undefined;
has(id: Ptr): boolean;
remove(id: Ptr): void;
dispose(): void;
}
export declare class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export declare class TryCatch {
private _exception;
private _caught;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export declare const version: string;
export { }
@@ -0,0 +1 @@
const e=new WeakMap;function t(t){return e.has(t)}const i=(()=>{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function s(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const n=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&n)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class o{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const a=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,h=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),u="undefined"!=typeof BigInt;const p=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),f="function"==typeof MessageChannel?MessageChannel:function(){try{return p("worker_threads").MessageChannel}catch(e){}}(),d="function"==typeof setImmediate?setImmediate:function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(f){let t=new f;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},_="function"==typeof Buffer?Buffer:function(){try{return p("buffer").Buffer}catch(e){}}(),v="1.8.1",g=2147483647;class y{constructor(e,t){this.id=e,this.value=t}data(){return s(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=_),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class x extends y{constructor(e,t){super(e,t)}dispose(){}}class z{constructor(){this._values=[void 0,z.UNDEFINED,z.NULL,z.FALSE,z.TRUE,z.GLOBAL],this._next=z.MIN_ID}push(e){let t;const i=this._next,s=this._values;return i<s.length?(t=s[i],t.value=e):(t=new y(i,e),s[i]=t),this._next++,t}erase(e,t){this._next=e;const i=this._values;for(let s=e;s<t;++s)i[s].dispose()}get(e){return this._values[e]}swap(e,t){const i=this._values,s=i[e];i[e]=i[t],i[e].id=Number(e),i[t]=s,s.id=Number(t)}dispose(){this._values.length=z.MIN_ID,this._next=z.MIN_ID}}z.UNDEFINED=new x(1,void 0),z.NULL=new x(2,null),z.FALSE=new x(3,!1),z.TRUE=new x(4,!0),z.GLOBAL=new x(5,r),z.MIN_ID=6;class k{constructor(e,t,i,s,n=s){this.handleStore=e,this.id=t,this.parent=i,this.child=null,null!==i&&(i.child=this),this.start=s,this.end=n,this._escapeCalled=!1,this.callbackInfo={thiz:void 0,data:0,args:void 0,fn:void 0}}add(e){const t=this.handleStore.push(e);return this.end++,t}addExternal(e){return this.add(new i(e))}dispose(){this._escapeCalled&&(this._escapeCalled=!1),this.start!==this.end&&this.handleStore.erase(this.start,this.end)}escape(e){if(this._escapeCalled)return null;if(this._escapeCalled=!0,e<this.start||e>=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class b{constructor(){this._rootScope=new k(null,0,null,1,z.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const s=t.id+1;i=new k(e,s,t,t.end),this._values[s]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScope=e.parent,e.dispose()}dispose(){this.currentScope=this._rootScope,this._values.lengtLine truncated
+665
View File
@@ -0,0 +1,665 @@
export declare type Ptr = number | bigint
export declare interface IBuffer extends Uint8Array {}
export declare interface BufferCtor {
readonly prototype: IBuffer
/** @deprecated */
new (...args: any[]): IBuffer
from: {
(buffer: ArrayBufferLike): IBuffer
(buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer
}
alloc: (size: number) => IBuffer
isBuffer: (obj: unknown) => obj is IBuffer
}
export declare const enum GlobalHandle {
UNDEFINED = 1,
NULL,
FALSE,
TRUE,
GLOBAL
}
export declare const enum Version {
NODE_API_SUPPORTED_VERSION_MIN = 1,
NODE_API_DEFAULT_MODULE_API_VERSION = 8,
NODE_API_SUPPORTED_VERSION_MAX = 10,
NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type Pointer<T> = number
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type PointerPointer<T> = number
export declare type FunctionPointer<T extends (...args: any[]) => any> = Pointer<T>
export declare type Const<T> = T
export declare type void_p = Pointer<void>
export declare type void_pp = Pointer<void_p>
export declare type bool = number
export declare type char = number
export declare type char_p = Pointer<char>
export declare type unsigned_char = number
export declare type const_char = Const<char>
export declare type const_char_p = Pointer<const_char>
export declare type char16_t_p = number
export declare type const_char16_t_p = number
export declare type short = number
export declare type unsigned_short = number
export declare type int = number
export declare type unsigned_int = number
export declare type long = number
export declare type unsigned_long = number
export declare type long_long = bigint
export declare type unsigned_long_long = bigint
export declare type float = number
export declare type double = number
export declare type long_double = number
export declare type size_t = number
export declare type int8_t = number
export declare type uint8_t = number
export declare type int16_t = number
export declare type uint16_t = number
export declare type int32_t = number
export declare type uint32_t = number
export declare type int64_t = bigint
export declare type uint64_t = bigint
export declare type napi_env = Pointer<unknown>
export declare type napi_value = Pointer<unknown>
export declare type napi_ref = Pointer<unknown>
export declare type napi_deferred = Pointer<unknown>
export declare type napi_handle_scope = Pointer<unknown>
export declare type napi_escapable_handle_scope = Pointer<unknown>
export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value>
export declare type napi_callback_info = Pointer<unknown>
export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value>
export declare interface napi_extended_error_info {
error_message: const_char_p
engine_reserved: void_p
engine_error_code: uint32_t
error_code: napi_status
}
export declare interface napi_property_descriptor {
// One of utf8name or name should be NULL.
utf8name: const_char_p
name: napi_value
method: napi_callback
getter: napi_callback
setter: napi_callback
value: napi_value
/* napi_property_attributes */
attributes: number
data: void_p
}
export declare type napi_finalize = FunctionPointer<(
env: napi_env,
finalize_data: void_p,
finalize_hint: void_p
) => void>
export declare interface node_module {
nm_version: int32_t
nm_flags: uint32_t
nm_filename: Pointer<const_char>
nm_register_func: napi_addon_register_func
nm_modname: Pointer<const_char>
nm_priv: Pointer<void>
reserved: PointerPointer<void>
}
export declare interface napi_node_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
release: const_char_p
}
export declare interface emnapi_emscripten_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
}
export declare const enum napi_status {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, // unused
napi_no_external_buffers_allowed,
napi_cannot_run_js
}
export declare const enum napi_property_attributes {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
/// #ifdef NAPI_EXPERIMENTAL
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable
/// #endif // NAPI_EXPERIMENTAL
}
export declare const enum napi_valuetype {
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint
}
export declare const enum napi_typedarray_type {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
}
export declare const enum napi_key_collection_mode {
napi_key_include_prototypes,
napi_key_own_only
}
export declare const enum napi_key_filter {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
}
export declare const enum napi_key_conversion {
napi_key_keep_numbers,
napi_key_numbers_to_strings
}
export declare const enum emnapi_memory_view_type {
emnapi_int8_array,
emnapi_uint8_array,
emnapi_uint8_clamped_array,
emnapi_int16_array,
emnapi_uint16_array,
emnapi_int32_array,
emnapi_uint32_array,
emnapi_float32_array,
emnapi_float64_array,
emnapi_bigint64_array,
emnapi_biguint64_array,
emnapi_float16_array,
emnapi_data_view = -1,
emnapi_buffer = -2
}
export declare const enum napi_threadsafe_function_call_mode {
napi_tsfn_nonblocking,
napi_tsfn_blocking
}
export declare const enum napi_threadsafe_function_release_mode {
napi_tsfn_release,
napi_tsfn_abort
}
export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
export declare class ConstHandle<S extends undefined | null | boolean | typeof globalThis> extends Handle<S> {
constructor(id: number, value: S);
dispose(): void;
}
export declare class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
envStore: Store<Env>;
scopeStore: ScopeStore;
refStore: Store<Reference>;
deferredStore: Store<Deferred<any>>;
handleStore: HandleStore;
private readonly refCounter?;
private readonly cleanupQueue;
feature: {
supportReflect: boolean;
supportFinalizer: boolean;
supportWeakSymbol: boolean;
supportBigInt: boolean;
supportNewFunction: boolean;
canSetFunctionName: boolean;
setImmediate: (callback: () => void) => void;
Buffer: BufferCtor | undefined;
MessageChannel: {
new (): MessageChannel;
prototype: MessageChannel;
} | undefined;
};
constructor();
/**
* Suppress the destroy on `beforeExit` event in Node.js.
* Call this method if you want to keep the context and
* all associated {@link Env | Env} alive,
* this also means that cleanup hooks will not be called.
* After call this method, you should call
* {@link Context.destroy | `Context.prototype.destroy`} method manually.
*/
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createDeferred<T = any>(value: IDeferrdValue<T>): Deferred<T>;
createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope | null;
addToCurrentScope<V>(value: V): Handle<V>;
openScope(envObject?: Env): HandleScope;
closeScope(envObject?: Env, _scope?: HandleScope): void;
ensureHandle<S>(value: S): Handle<S>;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
/**
* Destroy the context and call cleanup hooks.
* Associated {@link Env | Env} will be destroyed.
*/
destroy(): void;
}
export declare function createContext(): Context;
export declare class Deferred<T = any> implements IStoreValue {
static create<T = any>(ctx: Context, value: IDeferrdValue<T>): Deferred;
id: number;
ctx: Context;
value: IDeferrdValue<T>;
constructor(ctx: Context, value: IDeferrdValue<T>);
resolve(value: T): void;
reject(reason?: any): void;
dispose(): void;
}
export declare class EmnapiError extends Error {
constructor(message?: string);
}
export declare abstract class Env implements IStoreValue {
readonly ctx: Context;
moduleApiVersion: number;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
id: number;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
tryCatch: TryCatch;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
lastError: {
errorCode: napi_status;
engineErrorCode: number;
engineReserved: Ptr;
};
inGcFinalizer: boolean;
constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never);
/** @virtual */
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
ensureHandle<S>(value: S): Handle<S>;
ensureHandleId(value: any): napi_value;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status;
getReturnStatus(): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
/** @virtual */
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
/** @virtual */
enqueueFinalizer(finalizer: RefTracker): void;
/** @virtual */
dequeueFinalizer(finalizer: RefTracker): void;
/** @virtual */
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number;
}
/** @public */
declare interface External_2 extends Record<any, any> {
}
/** @public */
declare const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export declare class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export declare function getDefaultContext(): Context;
/** @public */
export declare function getExternalValue(external: External_2): number | bigint;
export declare class Handle<S> {
id: number;
value: S;
constructor(id: number, value: S);
data(): void_p;
isNumber(): boolean;
isBigInt(): boolean;
isString(): boolean;
isFunction(): boolean;
isExternal(): boolean;
isObject(): boolean;
isArray(): boolean;
isArrayBuffer(): boolean;
isTypedArray(): boolean;
isBuffer(BufferConstructor?: BufferCtor): boolean;
isDataView(): boolean;
isDate(): boolean;
isPromise(): boolean;
isBoolean(): boolean;
isUndefined(): boolean;
isSymbol(): boolean;
isNull(): boolean;
dispose(): void;
}
export declare class HandleScope {
handleStore: HandleStore;
id: number;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number);
add<V>(value: V): Handle<V>;
addExternal(data: void_p): Handle<object>;
dispose(): void;
escape(handle: number): Handle<any> | null;
escapeCalled(): boolean;
}
export declare class HandleStore {
static UNDEFINED: ConstHandle<undefined>;
static NULL: ConstHandle<null>;
static FALSE: ConstHandle<false>;
static TRUE: ConstHandle<true>;
static GLOBAL: ConstHandle<typeof globalThis>;
static MIN_ID: 6;
private readonly _values;
private _next;
push<S>(value: S): Handle<S>;
erase(start: number, end: number): void;
get(id: Ptr): Handle<any> | undefined;
swap(a: number, b: number): void;
dispose(): void;
}
export declare interface ICallbackInfo {
thiz: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export declare interface IDeferrdValue<T = any> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
}
export declare interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
/** @public */
export declare function isExternal(object: unknown): object is External_2;
export declare function isReferenceType(v: any): v is object;
export declare interface IStoreValue {
id: number;
dispose(): void;
[x: string]: any;
}
export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export declare class NodeEnv extends Env {
filename: string;
private readonly nodeBinding?;
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export declare class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class Persistent<T> {
private _ref;
private _param;
private _callback;
private static readonly _registry;
constructor(value: T);
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export declare class Reference extends RefTracker implements IStoreValue {
private static weakCallback;
id: number;
envObject: Env;
private readonly canBeWeak;
private _refcount;
private readonly _ownership;
persistent: Persistent<object>;
static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
ref(): number;
unref(): number;
get(envObject?: Env): napi_value;
/** @virtual */
resetFinalizer(): void;
/** @virtual */
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
/** @virtual */
protected callUserFinalizer(): void;
/** @virtual */
protected invokeFinalizerFromGC(): void;
private _setWeak;
finalize(): void;
dispose(): void;
}
export declare enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export declare class ReferenceWithData extends Reference {
private readonly _data;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
private constructor();
data(): void_p;
}
export declare class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
private constructor();
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export declare class RefTracker {
/** @virtual */
dispose(): void;
/** @virtual */
finalize(): void;
private _next;
private _prev;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export declare class ScopeStore {
private readonly _rootScope;
currentScope: HandleScope;
private readonly _values;
constructor();
get(id: number): HandleScope | undefined;
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
dispose(): void;
}
export declare class Store<V extends IStoreValue> {
protected _values: Array<V | undefined>;
private _freeList;
private _size;
constructor();
add(value: V): void;
get(id: Ptr): V | undefined;
has(id: Ptr): boolean;
remove(id: Ptr): void;
dispose(): void;
}
export declare class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export declare class TryCatch {
private _exception;
private _caught;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export declare const version: string;
export { }
+667
View File
@@ -0,0 +1,667 @@
export declare type Ptr = number | bigint
export declare interface IBuffer extends Uint8Array {}
export declare interface BufferCtor {
readonly prototype: IBuffer
/** @deprecated */
new (...args: any[]): IBuffer
from: {
(buffer: ArrayBufferLike): IBuffer
(buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer
}
alloc: (size: number) => IBuffer
isBuffer: (obj: unknown) => obj is IBuffer
}
export declare const enum GlobalHandle {
UNDEFINED = 1,
NULL,
FALSE,
TRUE,
GLOBAL
}
export declare const enum Version {
NODE_API_SUPPORTED_VERSION_MIN = 1,
NODE_API_DEFAULT_MODULE_API_VERSION = 8,
NODE_API_SUPPORTED_VERSION_MAX = 10,
NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type Pointer<T> = number
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type PointerPointer<T> = number
export declare type FunctionPointer<T extends (...args: any[]) => any> = Pointer<T>
export declare type Const<T> = T
export declare type void_p = Pointer<void>
export declare type void_pp = Pointer<void_p>
export declare type bool = number
export declare type char = number
export declare type char_p = Pointer<char>
export declare type unsigned_char = number
export declare type const_char = Const<char>
export declare type const_char_p = Pointer<const_char>
export declare type char16_t_p = number
export declare type const_char16_t_p = number
export declare type short = number
export declare type unsigned_short = number
export declare type int = number
export declare type unsigned_int = number
export declare type long = number
export declare type unsigned_long = number
export declare type long_long = bigint
export declare type unsigned_long_long = bigint
export declare type float = number
export declare type double = number
export declare type long_double = number
export declare type size_t = number
export declare type int8_t = number
export declare type uint8_t = number
export declare type int16_t = number
export declare type uint16_t = number
export declare type int32_t = number
export declare type uint32_t = number
export declare type int64_t = bigint
export declare type uint64_t = bigint
export declare type napi_env = Pointer<unknown>
export declare type napi_value = Pointer<unknown>
export declare type napi_ref = Pointer<unknown>
export declare type napi_deferred = Pointer<unknown>
export declare type napi_handle_scope = Pointer<unknown>
export declare type napi_escapable_handle_scope = Pointer<unknown>
export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value>
export declare type napi_callback_info = Pointer<unknown>
export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value>
export declare interface napi_extended_error_info {
error_message: const_char_p
engine_reserved: void_p
engine_error_code: uint32_t
error_code: napi_status
}
export declare interface napi_property_descriptor {
// One of utf8name or name should be NULL.
utf8name: const_char_p
name: napi_value
method: napi_callback
getter: napi_callback
setter: napi_callback
value: napi_value
/* napi_property_attributes */
attributes: number
data: void_p
}
export declare type napi_finalize = FunctionPointer<(
env: napi_env,
finalize_data: void_p,
finalize_hint: void_p
) => void>
export declare interface node_module {
nm_version: int32_t
nm_flags: uint32_t
nm_filename: Pointer<const_char>
nm_register_func: napi_addon_register_func
nm_modname: Pointer<const_char>
nm_priv: Pointer<void>
reserved: PointerPointer<void>
}
export declare interface napi_node_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
release: const_char_p
}
export declare interface emnapi_emscripten_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
}
export declare const enum napi_status {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, // unused
napi_no_external_buffers_allowed,
napi_cannot_run_js
}
export declare const enum napi_property_attributes {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
/// #ifdef NAPI_EXPERIMENTAL
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable
/// #endif // NAPI_EXPERIMENTAL
}
export declare const enum napi_valuetype {
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint
}
export declare const enum napi_typedarray_type {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
}
export declare const enum napi_key_collection_mode {
napi_key_include_prototypes,
napi_key_own_only
}
export declare const enum napi_key_filter {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
}
export declare const enum napi_key_conversion {
napi_key_keep_numbers,
napi_key_numbers_to_strings
}
export declare const enum emnapi_memory_view_type {
emnapi_int8_array,
emnapi_uint8_array,
emnapi_uint8_clamped_array,
emnapi_int16_array,
emnapi_uint16_array,
emnapi_int32_array,
emnapi_uint32_array,
emnapi_float32_array,
emnapi_float64_array,
emnapi_bigint64_array,
emnapi_biguint64_array,
emnapi_float16_array,
emnapi_data_view = -1,
emnapi_buffer = -2
}
export declare const enum napi_threadsafe_function_call_mode {
napi_tsfn_nonblocking,
napi_tsfn_blocking
}
export declare const enum napi_threadsafe_function_release_mode {
napi_tsfn_release,
napi_tsfn_abort
}
export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
export declare class ConstHandle<S extends undefined | null | boolean | typeof globalThis> extends Handle<S> {
constructor(id: number, value: S);
dispose(): void;
}
export declare class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
envStore: Store<Env>;
scopeStore: ScopeStore;
refStore: Store<Reference>;
deferredStore: Store<Deferred<any>>;
handleStore: HandleStore;
private readonly refCounter?;
private readonly cleanupQueue;
feature: {
supportReflect: boolean;
supportFinalizer: boolean;
supportWeakSymbol: boolean;
supportBigInt: boolean;
supportNewFunction: boolean;
canSetFunctionName: boolean;
setImmediate: (callback: () => void) => void;
Buffer: BufferCtor | undefined;
MessageChannel: {
new (): MessageChannel;
prototype: MessageChannel;
} | undefined;
};
constructor();
/**
* Suppress the destroy on `beforeExit` event in Node.js.
* Call this method if you want to keep the context and
* all associated {@link Env | Env} alive,
* this also means that cleanup hooks will not be called.
* After call this method, you should call
* {@link Context.destroy | `Context.prototype.destroy`} method manually.
*/
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createDeferred<T = any>(value: IDeferrdValue<T>): Deferred<T>;
createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope | null;
addToCurrentScope<V>(value: V): Handle<V>;
openScope(envObject?: Env): HandleScope;
closeScope(envObject?: Env, _scope?: HandleScope): void;
ensureHandle<S>(value: S): Handle<S>;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
/**
* Destroy the context and call cleanup hooks.
* Associated {@link Env | Env} will be destroyed.
*/
destroy(): void;
}
export declare function createContext(): Context;
export declare class Deferred<T = any> implements IStoreValue {
static create<T = any>(ctx: Context, value: IDeferrdValue<T>): Deferred;
id: number;
ctx: Context;
value: IDeferrdValue<T>;
constructor(ctx: Context, value: IDeferrdValue<T>);
resolve(value: T): void;
reject(reason?: any): void;
dispose(): void;
}
export declare class EmnapiError extends Error {
constructor(message?: string);
}
export declare abstract class Env implements IStoreValue {
readonly ctx: Context;
moduleApiVersion: number;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
id: number;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
tryCatch: TryCatch;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
lastError: {
errorCode: napi_status;
engineErrorCode: number;
engineReserved: Ptr;
};
inGcFinalizer: boolean;
constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never);
/** @virtual */
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
ensureHandle<S>(value: S): Handle<S>;
ensureHandleId(value: any): napi_value;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status;
getReturnStatus(): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
/** @virtual */
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
/** @virtual */
enqueueFinalizer(finalizer: RefTracker): void;
/** @virtual */
dequeueFinalizer(finalizer: RefTracker): void;
/** @virtual */
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number;
}
/** @public */
declare interface External_2 extends Record<any, any> {
}
/** @public */
declare const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export declare class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export declare function getDefaultContext(): Context;
/** @public */
export declare function getExternalValue(external: External_2): number | bigint;
export declare class Handle<S> {
id: number;
value: S;
constructor(id: number, value: S);
data(): void_p;
isNumber(): boolean;
isBigInt(): boolean;
isString(): boolean;
isFunction(): boolean;
isExternal(): boolean;
isObject(): boolean;
isArray(): boolean;
isArrayBuffer(): boolean;
isTypedArray(): boolean;
isBuffer(BufferConstructor?: BufferCtor): boolean;
isDataView(): boolean;
isDate(): boolean;
isPromise(): boolean;
isBoolean(): boolean;
isUndefined(): boolean;
isSymbol(): boolean;
isNull(): boolean;
dispose(): void;
}
export declare class HandleScope {
handleStore: HandleStore;
id: number;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number);
add<V>(value: V): Handle<V>;
addExternal(data: void_p): Handle<object>;
dispose(): void;
escape(handle: number): Handle<any> | null;
escapeCalled(): boolean;
}
export declare class HandleStore {
static UNDEFINED: ConstHandle<undefined>;
static NULL: ConstHandle<null>;
static FALSE: ConstHandle<false>;
static TRUE: ConstHandle<true>;
static GLOBAL: ConstHandle<typeof globalThis>;
static MIN_ID: 6;
private readonly _values;
private _next;
push<S>(value: S): Handle<S>;
erase(start: number, end: number): void;
get(id: Ptr): Handle<any> | undefined;
swap(a: number, b: number): void;
dispose(): void;
}
export declare interface ICallbackInfo {
thiz: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export declare interface IDeferrdValue<T = any> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
}
export declare interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
/** @public */
export declare function isExternal(object: unknown): object is External_2;
export declare function isReferenceType(v: any): v is object;
export declare interface IStoreValue {
id: number;
dispose(): void;
[x: string]: any;
}
export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export declare class NodeEnv extends Env {
filename: string;
private readonly nodeBinding?;
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export declare class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class Persistent<T> {
private _ref;
private _param;
private _callback;
private static readonly _registry;
constructor(value: T);
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export declare class Reference extends RefTracker implements IStoreValue {
private static weakCallback;
id: number;
envObject: Env;
private readonly canBeWeak;
private _refcount;
private readonly _ownership;
persistent: Persistent<object>;
static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
ref(): number;
unref(): number;
get(envObject?: Env): napi_value;
/** @virtual */
resetFinalizer(): void;
/** @virtual */
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
/** @virtual */
protected callUserFinalizer(): void;
/** @virtual */
protected invokeFinalizerFromGC(): void;
private _setWeak;
finalize(): void;
dispose(): void;
}
export declare enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export declare class ReferenceWithData extends Reference {
private readonly _data;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
private constructor();
data(): void_p;
}
export declare class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
private constructor();
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export declare class RefTracker {
/** @virtual */
dispose(): void;
/** @virtual */
finalize(): void;
private _next;
private _prev;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export declare class ScopeStore {
private readonly _rootScope;
currentScope: HandleScope;
private readonly _values;
constructor();
get(id: number): HandleScope | undefined;
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
dispose(): void;
}
export declare class Store<V extends IStoreValue> {
protected _values: Array<V | undefined>;
private _freeList;
private _size;
constructor();
add(value: V): void;
get(id: Ptr): V | undefined;
has(id: Ptr): boolean;
remove(id: Ptr): void;
dispose(): void;
}
export declare class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export declare class TryCatch {
private _exception;
private _caught;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export declare const version: string;
export { }
export as namespace emnapi;
File diff suppressed because it is too large. Load diff
+420
View File
@@ -0,0 +1,420 @@
declare namespace emnapi {
export type CleanupHookCallbackFunction = number | ((arg: number) => void);
export class ConstHandle<S extends undefined | null | boolean | typeof globalThis> extends Handle<S> {
constructor(id: number, value: S);
dispose(): void;
}
export class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
envStore: Store<Env>;
scopeStore: ScopeStore;
refStore: Store<Reference>;
deferredStore: Store<Deferred<any>>;
handleStore: HandleStore;
private readonly refCounter?;
private readonly cleanupQueue;
feature: {
supportReflect: boolean;
supportFinalizer: boolean;
supportWeakSymbol: boolean;
supportBigInt: boolean;
supportNewFunction: boolean;
canSetFunctionName: boolean;
setImmediate: (callback: () => void) => void;
Buffer: BufferCtor | undefined;
MessageChannel: {
new (): MessageChannel;
prototype: MessageChannel;
} | undefined;
};
constructor();
/**
* Suppress the destroy on `beforeExit` event in Node.js.
* Call this method if you want to keep the context and
* all associated {@link Env | Env} alive,
* this also means that cleanup hooks will not be called.
* After call this method, you should call
* {@link Context.destroy | `Context.prototype.destroy`} method manually.
*/
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createDeferred<T = any>(value: IDeferrdValue<T>): Deferred<T>;
createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope | null;
addToCurrentScope<V>(value: V): Handle<V>;
openScope(envObject?: Env): HandleScope;
closeScope(envObject?: Env, _scope?: HandleScope): void;
ensureHandle<S>(value: S): Handle<S>;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
/**
* Destroy the context and call cleanup hooks.
* Associated {@link Env | Env} will be destroyed.
*/
destroy(): void;
}
export function createContext(): Context;
export class Deferred<T = any> implements IStoreValue {
static create<T = any>(ctx: Context, value: IDeferrdValue<T>): Deferred;
id: number;
ctx: Context;
value: IDeferrdValue<T>;
constructor(ctx: Context, value: IDeferrdValue<T>);
resolve(value: T): void;
reject(reason?: any): void;
dispose(): void;
}
export class EmnapiError extends Error {
constructor(message?: string);
}
export abstract class Env implements IStoreValue {
readonly ctx: Context;
moduleApiVersion: number;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
id: number;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
tryCatch: TryCatch;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
lastError: {
errorCode: napi_status;
engineErrorCode: number;
engineReserved: Ptr;
};
inGcFinalizer: boolean;
constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never);
/** @virtual */
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
ensureHandle<S>(value: S): Handle<S>;
ensureHandleId(value: any): napi_value;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status;
getReturnStatus(): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
/** @virtual */
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
/** @virtual */
enqueueFinalizer(finalizer: RefTracker): void;
/** @virtual */
dequeueFinalizer(finalizer: RefTracker): void;
/** @virtual */
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number;
}
/** @public */
interface External_2 extends Record<any, any> {
}
/** @public */
const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export function getDefaultContext(): Context;
/** @public */
export function getExternalValue(external: External_2): number | bigint;
export class Handle<S> {
id: number;
value: S;
constructor(id: number, value: S);
data(): void_p;
isNumber(): boolean;
isBigInt(): boolean;
isString(): boolean;
isFunction(): boolean;
isExternal(): boolean;
isObject(): boolean;
isArray(): boolean;
isArrayBuffer(): boolean;
isTypedArray(): boolean;
isBuffer(BufferConstructor?: BufferCtor): boolean;
isDataView(): boolean;
isDate(): boolean;
isPromise(): boolean;
isBoolean(): boolean;
isUndefined(): boolean;
isSymbol(): boolean;
isNull(): boolean;
dispose(): void;
}
export class HandleScope {
handleStore: HandleStore;
id: number;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number);
add<V>(value: V): Handle<V>;
addExternal(data: void_p): Handle<object>;
dispose(): void;
escape(handle: number): Handle<any> | null;
escapeCalled(): boolean;
}
export class HandleStore {
static UNDEFINED: ConstHandle<undefined>;
static NULL: ConstHandle<null>;
static FALSE: ConstHandle<false>;
static TRUE: ConstHandle<true>;
static GLOBAL: ConstHandle<typeof globalThis>;
static MIN_ID: 6;
private readonly _values;
private _next;
push<S>(value: S): Handle<S>;
erase(start: number, end: number): void;
get(id: Ptr): Handle<any> | undefined;
swap(a: number, b: number): void;
dispose(): void;
}
export interface ICallbackInfo {
thiz: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export interface IDeferrdValue<T = any> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
}
export interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
/** @public */
export function isExternal(object: unknown): object is External_2;
export function isReferenceType(v: any): v is object;
export interface IStoreValue {
id: number;
dispose(): void;
[x: string]: any;
}
export const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export class NodeEnv extends Env {
filename: string;
private readonly nodeBinding?;
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export class Persistent<T> {
private _ref;
private _param;
private _callback;
private static readonly _registry;
constructor(value: T);
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export class Reference extends RefTracker implements IStoreValue {
private static weakCallback;
id: number;
envObject: Env;
private readonly canBeWeak;
private _refcount;
private readonly _ownership;
persistent: Persistent<object>;
static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
ref(): number;
unref(): number;
get(envObject?: Env): napi_value;
/** @virtual */
resetFinalizer(): void;
/** @virtual */
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
/** @virtual */
protected callUserFinalizer(): void;
/** @virtual */
protected invokeFinalizerFromGC(): void;
private _setWeak;
finalize(): void;
dispose(): void;
}
export enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export class ReferenceWithData extends Reference {
private readonly _data;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
private constructor();
data(): void_p;
}
export class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
private constructor();
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export class RefTracker {
/** @virtual */
dispose(): void;
/** @virtual */
finalize(): void;
private _next;
private _prev;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export class ScopeStore {
private readonly _rootScope;
currentScope: HandleScope;
private readonly _values;
constructor();
get(id: number): HandleScope | undefined;
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
dispose(): void;
}
export class Store<V extends IStoreValue> {
protected _values: Array<V | undefined>;
private _freeList;
private _size;
constructor();
add(value: V): void;
get(id: Ptr): V | undefined;
has(id: Ptr): boolean;
remove(id: Ptr): void;
dispose(): void;
}
export class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export class TryCatch {
private _exception;
private _caught;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export const version: string;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+665
View File
@@ -0,0 +1,665 @@
export declare type Ptr = number | bigint
export declare interface IBuffer extends Uint8Array {}
export declare interface BufferCtor {
readonly prototype: IBuffer
/** @deprecated */
new (...args: any[]): IBuffer
from: {
(buffer: ArrayBufferLike): IBuffer
(buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer
}
alloc: (size: number) => IBuffer
isBuffer: (obj: unknown) => obj is IBuffer
}
export declare const enum GlobalHandle {
UNDEFINED = 1,
NULL,
FALSE,
TRUE,
GLOBAL
}
export declare const enum Version {
NODE_API_SUPPORTED_VERSION_MIN = 1,
NODE_API_DEFAULT_MODULE_API_VERSION = 8,
NODE_API_SUPPORTED_VERSION_MAX = 10,
NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type Pointer<T> = number
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export declare type PointerPointer<T> = number
export declare type FunctionPointer<T extends (...args: any[]) => any> = Pointer<T>
export declare type Const<T> = T
export declare type void_p = Pointer<void>
export declare type void_pp = Pointer<void_p>
export declare type bool = number
export declare type char = number
export declare type char_p = Pointer<char>
export declare type unsigned_char = number
export declare type const_char = Const<char>
export declare type const_char_p = Pointer<const_char>
export declare type char16_t_p = number
export declare type const_char16_t_p = number
export declare type short = number
export declare type unsigned_short = number
export declare type int = number
export declare type unsigned_int = number
export declare type long = number
export declare type unsigned_long = number
export declare type long_long = bigint
export declare type unsigned_long_long = bigint
export declare type float = number
export declare type double = number
export declare type long_double = number
export declare type size_t = number
export declare type int8_t = number
export declare type uint8_t = number
export declare type int16_t = number
export declare type uint16_t = number
export declare type int32_t = number
export declare type uint32_t = number
export declare type int64_t = bigint
export declare type uint64_t = bigint
export declare type napi_env = Pointer<unknown>
export declare type napi_value = Pointer<unknown>
export declare type napi_ref = Pointer<unknown>
export declare type napi_deferred = Pointer<unknown>
export declare type napi_handle_scope = Pointer<unknown>
export declare type napi_escapable_handle_scope = Pointer<unknown>
export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value>
export declare type napi_callback_info = Pointer<unknown>
export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value>
export declare interface napi_extended_error_info {
error_message: const_char_p
engine_reserved: void_p
engine_error_code: uint32_t
error_code: napi_status
}
export declare interface napi_property_descriptor {
// One of utf8name or name should be NULL.
utf8name: const_char_p
name: napi_value
method: napi_callback
getter: napi_callback
setter: napi_callback
value: napi_value
/* napi_property_attributes */
attributes: number
data: void_p
}
export declare type napi_finalize = FunctionPointer<(
env: napi_env,
finalize_data: void_p,
finalize_hint: void_p
) => void>
export declare interface node_module {
nm_version: int32_t
nm_flags: uint32_t
nm_filename: Pointer<const_char>
nm_register_func: napi_addon_register_func
nm_modname: Pointer<const_char>
nm_priv: Pointer<void>
reserved: PointerPointer<void>
}
export declare interface napi_node_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
release: const_char_p
}
export declare interface emnapi_emscripten_version {
major: uint32_t
minor: uint32_t
patch: uint32_t
}
export declare const enum napi_status {
napi_ok,
napi_invalid_arg,
napi_object_expected,
napi_string_expected,
napi_name_expected,
napi_function_expected,
napi_number_expected,
napi_boolean_expected,
napi_array_expected,
napi_generic_failure,
napi_pending_exception,
napi_cancelled,
napi_escape_called_twice,
napi_handle_scope_mismatch,
napi_callback_scope_mismatch,
napi_queue_full,
napi_closing,
napi_bigint_expected,
napi_date_expected,
napi_arraybuffer_expected,
napi_detachable_arraybuffer_expected,
napi_would_deadlock, // unused
napi_no_external_buffers_allowed,
napi_cannot_run_js
}
export declare const enum napi_property_attributes {
napi_default = 0,
napi_writable = 1 << 0,
napi_enumerable = 1 << 1,
napi_configurable = 1 << 2,
// Used with napi_define_class to distinguish static properties
// from instance properties. Ignored by napi_define_properties.
napi_static = 1 << 10,
/// #ifdef NAPI_EXPERIMENTAL
// Default for class methods.
napi_default_method = napi_writable | napi_configurable,
// Default for object properties, like in JS obj[prop].
napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable
/// #endif // NAPI_EXPERIMENTAL
}
export declare const enum napi_valuetype {
napi_undefined,
napi_null,
napi_boolean,
napi_number,
napi_string,
napi_symbol,
napi_object,
napi_function,
napi_external,
napi_bigint
}
export declare const enum napi_typedarray_type {
napi_int8_array,
napi_uint8_array,
napi_uint8_clamped_array,
napi_int16_array,
napi_uint16_array,
napi_int32_array,
napi_uint32_array,
napi_float32_array,
napi_float64_array,
napi_bigint64_array,
napi_biguint64_array,
napi_float16_array,
}
export declare const enum napi_key_collection_mode {
napi_key_include_prototypes,
napi_key_own_only
}
export declare const enum napi_key_filter {
napi_key_all_properties = 0,
napi_key_writable = 1,
napi_key_enumerable = 1 << 1,
napi_key_configurable = 1 << 2,
napi_key_skip_strings = 1 << 3,
napi_key_skip_symbols = 1 << 4
}
export declare const enum napi_key_conversion {
napi_key_keep_numbers,
napi_key_numbers_to_strings
}
export declare const enum emnapi_memory_view_type {
emnapi_int8_array,
emnapi_uint8_array,
emnapi_uint8_clamped_array,
emnapi_int16_array,
emnapi_uint16_array,
emnapi_int32_array,
emnapi_uint32_array,
emnapi_float32_array,
emnapi_float64_array,
emnapi_bigint64_array,
emnapi_biguint64_array,
emnapi_float16_array,
emnapi_data_view = -1,
emnapi_buffer = -2
}
export declare const enum napi_threadsafe_function_call_mode {
napi_tsfn_nonblocking,
napi_tsfn_blocking
}
export declare const enum napi_threadsafe_function_release_mode {
napi_tsfn_release,
napi_tsfn_abort
}
export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
export declare class ConstHandle<S extends undefined | null | boolean | typeof globalThis> extends Handle<S> {
constructor(id: number, value: S);
dispose(): void;
}
export declare class Context {
private _isStopping;
private _canCallIntoJs;
private _suppressDestroy;
envStore: Store<Env>;
scopeStore: ScopeStore;
refStore: Store<Reference>;
deferredStore: Store<Deferred<any>>;
handleStore: HandleStore;
private readonly refCounter?;
private readonly cleanupQueue;
feature: {
supportReflect: boolean;
supportFinalizer: boolean;
supportWeakSymbol: boolean;
supportBigInt: boolean;
supportNewFunction: boolean;
canSetFunctionName: boolean;
setImmediate: (callback: () => void) => void;
Buffer: BufferCtor | undefined;
MessageChannel: {
new (): MessageChannel;
prototype: MessageChannel;
} | undefined;
};
constructor();
/**
* Suppress the destroy on `beforeExit` event in Node.js.
* Call this method if you want to keep the context and
* all associated {@link Env | Env} alive,
* this also means that cleanup hooks will not be called.
* After call this method, you should call
* {@link Context.destroy | `Context.prototype.destroy`} method manually.
*/
suppressDestroy(): void;
getRuntimeVersions(): {
version: string;
NODE_API_SUPPORTED_VERSION_MAX: Version;
NAPI_VERSION_EXPERIMENTAL: Version;
NODE_API_DEFAULT_MODULE_API_VERSION: Version;
};
createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError;
createNotSupportBufferError(api: string, message: string): NotSupportBufferError;
createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference;
createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference;
createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference;
createDeferred<T = any>(value: IDeferrdValue<T>): Deferred<T>;
createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env;
createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
getCurrentScope(): HandleScope | null;
addToCurrentScope<V>(value: V): Handle<V>;
openScope(envObject?: Env): HandleScope;
closeScope(envObject?: Env, _scope?: HandleScope): void;
ensureHandle<S>(value: S): Handle<S>;
addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void;
runCleanup(): void;
increaseWaitingRequestCounter(): void;
decreaseWaitingRequestCounter(): void;
setCanCallIntoJs(value: boolean): void;
setStopping(value: boolean): void;
canCallIntoJs(): boolean;
/**
* Destroy the context and call cleanup hooks.
* Associated {@link Env | Env} will be destroyed.
*/
destroy(): void;
}
export declare function createContext(): Context;
export declare class Deferred<T = any> implements IStoreValue {
static create<T = any>(ctx: Context, value: IDeferrdValue<T>): Deferred;
id: number;
ctx: Context;
value: IDeferrdValue<T>;
constructor(ctx: Context, value: IDeferrdValue<T>);
resolve(value: T): void;
reject(reason?: any): void;
dispose(): void;
}
export declare class EmnapiError extends Error {
constructor(message?: string);
}
export declare abstract class Env implements IStoreValue {
readonly ctx: Context;
moduleApiVersion: number;
makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void;
makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void;
abort: (msg?: string) => never;
id: number;
openHandleScopes: number;
instanceData: TrackedFinalizer | null;
tryCatch: TryCatch;
refs: number;
reflist: RefTracker;
finalizing_reflist: RefTracker;
pendingFinalizers: RefTracker[];
lastError: {
errorCode: napi_status;
engineErrorCode: number;
engineReserved: Ptr;
};
inGcFinalizer: boolean;
constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never);
/** @virtual */
canCallIntoJs(): boolean;
terminatedOrTerminating(): boolean;
ref(): void;
unref(): void;
ensureHandle<S>(value: S): Handle<S>;
ensureHandleId(value: any): napi_value;
clearLastError(): napi_status;
setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status;
getReturnStatus(): napi_status;
callIntoModule<T>(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T;
/** @virtual */
abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
invokeFinalizerFromGC(finalizer: RefTracker): void;
checkGCAccess(): void;
/** @virtual */
enqueueFinalizer(finalizer: RefTracker): void;
/** @virtual */
dequeueFinalizer(finalizer: RefTracker): void;
/** @virtual */
deleteMe(): void;
dispose(): void;
private readonly _bindingMap;
initObjectBinding<S extends object>(value: S): IReferenceBinding;
getObjectBinding<S extends object>(value: S): IReferenceBinding;
setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void;
getInstanceData(): number;
}
/** @public */
declare interface External_2 extends Record<any, any> {
}
/** @public */
declare const External_2: {
new (value: number | bigint): External_2;
prototype: null;
};
export { External_2 as External }
export declare class Finalizer {
envObject: Env;
private _finalizeCallback;
private _finalizeData;
private _finalizeHint;
private _makeDynCall_vppp;
constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
callback(): napi_finalize;
data(): void_p;
hint(): void_p;
resetEnv(): void;
resetFinalizer(): void;
callFinalizer(): void;
dispose(): void;
}
export declare function getDefaultContext(): Context;
/** @public */
export declare function getExternalValue(external: External_2): number | bigint;
export declare class Handle<S> {
id: number;
value: S;
constructor(id: number, value: S);
data(): void_p;
isNumber(): boolean;
isBigInt(): boolean;
isString(): boolean;
isFunction(): boolean;
isExternal(): boolean;
isObject(): boolean;
isArray(): boolean;
isArrayBuffer(): boolean;
isTypedArray(): boolean;
isBuffer(BufferConstructor?: BufferCtor): boolean;
isDataView(): boolean;
isDate(): boolean;
isPromise(): boolean;
isBoolean(): boolean;
isUndefined(): boolean;
isSymbol(): boolean;
isNull(): boolean;
dispose(): void;
}
export declare class HandleScope {
handleStore: HandleStore;
id: number;
parent: HandleScope | null;
child: HandleScope | null;
start: number;
end: number;
private _escapeCalled;
callbackInfo: ICallbackInfo;
constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number);
add<V>(value: V): Handle<V>;
addExternal(data: void_p): Handle<object>;
dispose(): void;
escape(handle: number): Handle<any> | null;
escapeCalled(): boolean;
}
export declare class HandleStore {
static UNDEFINED: ConstHandle<undefined>;
static NULL: ConstHandle<null>;
static FALSE: ConstHandle<false>;
static TRUE: ConstHandle<true>;
static GLOBAL: ConstHandle<typeof globalThis>;
static MIN_ID: 6;
private readonly _values;
private _next;
push<S>(value: S): Handle<S>;
erase(start: number, end: number): void;
get(id: Ptr): Handle<any> | undefined;
swap(a: number, b: number): void;
dispose(): void;
}
export declare interface ICallbackInfo {
thiz: any;
data: void_p;
args: ArrayLike<any>;
fn: Function;
}
export declare interface IDeferrdValue<T = any> {
resolve: (value: T) => void;
reject: (reason?: any) => void;
}
export declare interface IReferenceBinding {
wrapped: number;
tag: Uint32Array | null;
}
/** @public */
export declare function isExternal(object: unknown): object is External_2;
export declare function isReferenceType(v: any): v is object;
export declare interface IStoreValue {
id: number;
dispose(): void;
[x: string]: any;
}
export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL;
export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION;
export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX;
export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN;
export declare class NodeEnv extends Env {
filename: string;
private readonly nodeBinding?;
destructing: boolean;
finalizationScheduled: boolean;
constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any);
deleteMe(): void;
canCallIntoJs(): boolean;
triggerFatalException(err: any): void;
callbackIntoModule<T>(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T;
callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void;
callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void;
enqueueFinalizer(finalizer: RefTracker): void;
drainFinalizerQueue(): void;
}
export declare class NotSupportBufferError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class NotSupportWeakRefError extends EmnapiError {
constructor(api: string, message: string);
}
export declare class Persistent<T> {
private _ref;
private _param;
private _callback;
private static readonly _registry;
constructor(value: T);
setWeak<P>(param: P, callback: (param: P) => void): void;
clearWeak(): void;
reset(): void;
isEmpty(): boolean;
deref(): T | undefined;
}
export declare class Reference extends RefTracker implements IStoreValue {
private static weakCallback;
id: number;
envObject: Env;
private readonly canBeWeak;
private _refcount;
private readonly _ownership;
persistent: Persistent<object>;
static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference;
protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership);
ref(): number;
unref(): number;
get(envObject?: Env): napi_value;
/** @virtual */
resetFinalizer(): void;
/** @virtual */
data(): void_p;
refcount(): number;
ownership(): ReferenceOwnership;
/** @virtual */
protected callUserFinalizer(): void;
/** @virtual */
protected invokeFinalizerFromGC(): void;
private _setWeak;
finalize(): void;
dispose(): void;
}
export declare enum ReferenceOwnership {
kRuntime = 0,
kUserland = 1
}
export declare class ReferenceWithData extends Reference {
private readonly _data;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData;
private constructor();
data(): void_p;
}
export declare class ReferenceWithFinalizer extends Reference {
private _finalizer;
static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer;
private constructor();
resetFinalizer(): void;
data(): void_p;
protected callUserFinalizer(): void;
protected invokeFinalizerFromGC(): void;
dispose(): void;
}
export declare class RefTracker {
/** @virtual */
dispose(): void;
/** @virtual */
finalize(): void;
private _next;
private _prev;
link(list: RefTracker): void;
unlink(): void;
static finalizeAll(list: RefTracker): void;
}
export declare class ScopeStore {
private readonly _rootScope;
currentScope: HandleScope;
private readonly _values;
constructor();
get(id: number): HandleScope | undefined;
openScope(handleStore: HandleStore): HandleScope;
closeScope(): void;
dispose(): void;
}
export declare class Store<V extends IStoreValue> {
protected _values: Array<V | undefined>;
private _freeList;
private _size;
constructor();
add(value: V): void;
get(id: Ptr): V | undefined;
has(id: Ptr): boolean;
remove(id: Ptr): void;
dispose(): void;
}
export declare class TrackedFinalizer extends RefTracker {
private _finalizer;
static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer;
private constructor();
data(): void_p;
dispose(): void;
finalize(): void;
}
export declare class TryCatch {
private _exception;
private _caught;
isEmpty(): boolean;
hasCaught(): boolean;
exception(): any;
setError(err: any): void;
reset(): void;
extractException(): any;
}
export declare const version: string;
export { }
+1
View File
@@ -0,0 +1 @@
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).emnapi={})}(this,function(t){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}"function"==typeof SuppressedError&&SuppressedError;var i=new WeakMap;function r(t){return i.has(t)}var o=function(){function t(t){Object.setPrototypeOf(this,null),i.set(this,t)}return t.prototype=null,t}();function s(t){if(!r(t))throw new TypeError("not external");return i.get(t)}var a=function(){var t;try{t=new Function}catch(t){return!1}return"function"==typeof t}(),u=function(){if("undefined"!=typeof globalThis)return globalThis;var t=function(){return this}();if(!t&&a)try{t=new Function("return this")()}catch(t){}if(!t){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return t}(),c=function(){function t(){this._exception=void 0,this._caught=!1}return t.prototype.isEmpty=function(){return!this._caught},t.prototype.hasCaught=function(){return this._caught},t.prototype.exception=function(){return this._exception},t.prototype.setError=function(t){this._caught=!0,this._exception=t},t.prototype.reset=function(){this._caught=!1,this._exception=void 0},t.prototype.extractException=function(){var t=this._exception;return this.reset(),t},t}(),p=function(){var t;try{return Boolean(null===(t=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===t?void 0:t.configurable)}catch(t){return!1}}(),f="object"==typeof Reflect,l="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,h=function(){try{var t=Symbol();new WeakRef(t),(new WeakMap).set(t,void 0)}catch(t){return!1}return!0}(),d="undefined"!=typeof BigInt;var y=function(){return"undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0}(),_="function"==typeof MessageChannel?MessageChannel:function(){try{return y("worker_threads").MessageChannel}catch(t){}}(),v="function"==typeof setImmediate?setImmediate:function(t){if("function"!=typeof t)throw new TypeError('The "callback" argument must be of type function');if(_){var e=new _;e.port1.onmessage=function(){e.port1.onmessage=null,e=void 0,t()},e.port2.postMessage(null)}else setTimeout(t,0)},g="function"==typeof Buffer?Buffer:function(){try{return y("buffer").Buffer}catch(t){}}(),z="1.8.1",b=2147483647,k=function(){function t(t,e){this.id=t,this.value=e}return t.prototype.data=function(){return s(this.value)},t.prototype.isNumber=function(){return"number"==typeof this.value},t.prototype.isBigInt=function(){return"bigint"==typeof this.value},t.prototype.isString=function(){return"string"==typeof this.value},t.prototype.isFunction=function(){return"function"==typeof this.value},t.prototype.isExternal=function(){return r(this.value)},t.prototype.isObject=function(){return"object"==typeof this.value&&null!==this.value},t.prototype.isArray=function(){return Array.isArray(this.value)},t.prototype.isArrayBuffer=function(){return this.value instanceof ArrayBuffer},t.prototype.isTypedArray=function(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)},t.prototype.isBuffer=function(t){return!!ArrayBuffer.isView(this.value)||(null!=t||(t=g),"function"==typeof t&&t.isBuffer(this.value))},t.prototype.isDataView=function(){return this.value instanceof DataView},t.prototype.isDate=function(){return this.value instanceof Date},t.prototype.isPromise=function(){return this.value instanceof Promise},t.prototype.isBoolean=function(){return"boolean"==typeof this.value},t.prototype.isUndefined=function(){return void 0===this.value},t.prototype.isSymbol=function(){return"symbol"==typeof this.value},t.prototype.isNull=function(){return null===this.value},t.prototype.dispose=function(){this.value=void 0},t}(),w=function(t){function e(e,n){return t.call(this,e,n)||this}return n(e,t),e.prototype.dispose=function(){},e}(k),S=function(){function t(){this._values=[void 0,t.UNDEFINED,t.NULL,t.FALSE,t.TRUE,t.GLOBAL],this._next=t.MIN_ID}return t.prototype.push=function(t){var e,n=this._next,i=this._values;return n<i.length?(e=i[n]).value=t:(e=new k(n,t),i[n]=e),this._next++,e},t.prototype.erase=function(t,e){this._next=t;for(var n=this._values,i=t;i<e;++i)n[i].dispose()},t.prototype.get=function(t){return this._values[t]},t.prototype.swap=function(t,e){var n=this._vaLine truncated
+1
View File
@@ -0,0 +1 @@
const e=new WeakMap;function t(t){return e.has(t)}const i=(()=>{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function s(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const n=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&n)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class a{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const o=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,h=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),u="undefined"!=typeof BigInt;function p(e){return"object"==typeof e&&null!==e||"function"==typeof e}const f=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),d="function"==typeof MessageChannel?MessageChannel:function(){try{return f("worker_threads").MessageChannel}catch(e){}}(),_="function"==typeof setImmediate?setImmediate:function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(d){let t=new d;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},v="function"==typeof Buffer?Buffer:function(){try{return f("buffer").Buffer}catch(e){}}(),g="1.8.1",y=1,z=10,b=2147483647,k=8;class w{constructor(e,t){this.id=e,this.value=t}data(){return s(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=v),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class m extends w{constructor(e,t){super(e,t)}dispose(){}}class C{constructor(){this._values=[void 0,C.UNDEFINED,C.NULL,C.FALSE,C.TRUE,C.GLOBAL],this._next=C.MIN_ID}push(e){let t;const i=this._next,s=this._values;return i<s.length?(t=s[i],t.value=e):(t=new w(i,e),s[i]=t),this._next++,t}erase(e,t){this._next=e;const i=this._values;for(let s=e;s<t;++s)i[s].dispose()}get(e){return this._values[e]}swap(e,t){const i=this._values,s=i[e];i[e]=i[t],i[e].id=Number(e),i[t]=s,s.id=Number(t)}dispose(){this._values.length=C.MIN_ID,this._next=C.MIN_ID}}C.UNDEFINED=new m(1,void 0),C.NULL=new m(2,null),C.FALSE=new m(3,!1),C.TRUE=new m(4,!0),C.GLOBAL=new m(5,r),C.MIN_ID=6;class S{constructor(e,t,i,s,n=s){this.handleStore=e,this.id=t,this.parent=i,this.child=null,null!==i&&(i.child=this),this.start=s,this.end=n,this._escapeCalled=!1,this.callbackInfo={thiz:void 0,data:0,args:void 0,fn:void 0}}add(e){const t=this.handleStore.push(e);return this.end++,t}addExternal(e){return this.add(new i(e))}dispose(){this._escapeCalled&&(this._escapeCalled=!1),this.start!==this.end&&this.handleStore.erase(this.start,this.end)}escape(e){if(this._escapeCalled)return null;if(this._escapeCalled=!0,e<this.start||e>=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class x{constructor(){this._rootScope=new S(null,0,null,1,C.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const s=t.id+1;i=new S(e,s,t,t.end),this._values[s]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScopeLine truncated
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') {
module.exports = require('./dist/emnapi.cjs.min.js')
} else {
module.exports = require('./dist/emnapi.cjs.js')
}
+48
View File
@@ -0,0 +1,48 @@
{
"name": "@emnapi/runtime",
"version": "1.8.1",
"description": "emnapi runtime",
"main": "index.js",
"module": "./dist/emnapi.esm-bundler.js",
"types": "./dist/emnapi.d.ts",
"sideEffects": false,
"exports": {
".": {
"types": {
"module": "./dist/emnapi.d.ts",
"import": "./dist/emnapi.d.mts",
"default": "./dist/emnapi.d.ts"
},
"module": "./dist/emnapi.esm-bundler.js",
"import": "./dist/emnapi.mjs",
"default": "./index.js"
},
"./dist/emnapi.cjs.min": {
"types": "./dist/emnapi.d.ts",
"default": "./dist/emnapi.cjs.min.js"
},
"./dist/emnapi.min.mjs": {
"types": "./dist/emnapi.d.mts",
"default": "./dist/emnapi.min.mjs"
}
},
"dependencies": {
"tslib": "^2.4.0"
},
"scripts": {
"build": "node ./script/build.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/toyobayashi/emnapi.git"
},
"author": "toyobayashi",
"license": "MIT",
"bugs": {
"url": "https://github.com/toyobayashi/emnapi/issues"
},
"homepage": "https://github.com/toyobayashi/emnapi#readme",
"publishConfig": {
"access": "public"
}
}
+126
View File
@@ -0,0 +1,126 @@
<p align="center">
<a href="https://tur.so/turso-ts">
<picture>
<img src="/.github/cover.png" alt="libSQL TypeScript" />
</picture>
</a>
<h1 align="center">libSQL TypeScript</h1>
</p>
<p align="center">
Databases for all TypeScript and JS multi-tenant apps.
</p>
<p align="center">
<a href="https://tur.so/turso-ts"><strong>Turso</strong></a> ·
<a href="https://docs.turso.tech"><strong>Docs</strong></a> ·
<a href="https://docs.turso.tech/sdk/ts/quickstart"><strong>Quickstart</strong></a> ·
<a href="https://docs.turso.tech/sdk/ts/reference"><strong>SDK Reference</strong></a> ·
<a href="https://turso.tech/blog"><strong>Blog &amp; Tutorials</strong></a>
</p>
<p align="center">
<a href="LICENSE">
<picture>
<img src="https://img.shields.io/github/license/tursodatabase/libsql-client-ts?color=0F624B" alt="MIT License" />
</picture>
</a>
<a href="https://tur.so/discord-ts">
<picture>
<img src="https://img.shields.io/discord/933071162680958986?color=0F624B" alt="Discord" />
</picture>
</a>
<a href="#contributors">
<picture>
<img src="https://img.shields.io/github/contributors/tursodatabase/libsql-client-ts?color=0F624B" alt="Contributors" />
</picture>
</a>
<a href="https://www.npmjs.com/package/@libsql/client">
<picture>
<img src="https://img.shields.io/npm/dw/%40libsql%2Fclient?color=0F624B" alt="Weekly downloads" />
</picture>
</a>
<a href="/examples">
<picture>
<img src="https://img.shields.io/badge/browse-examples-0F624B" alt="Examples" />
</picture>
</a>
</p>
## Features
- 🔌 Works offline with [Embedded Replicas](https://docs.turso.tech/features/embedded-replicas/introduction)
- 🌎 Works with remote Turso databases
- ✨ Works with Turso [AI & Vector Search](https://docs.turso.tech/features/ai-and-embeddings)
- 🔐 Supports [encryption at rest](https://docs.turso.tech/libsql#encryption-at-rest)
## Install
```bash
npm install @libsql/client
```
## Quickstart
The example below uses Embedded Replicas and syncs every minute from Turso.
```ts
import { createClient } from "@libsql/client";
export const turso = createClient({
url: "file:local.db",
syncUrl: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
syncInterval: 60000,
});
await turso.batch(
[
"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
{
sql: "INSERT INTO users(name) VALUES (?)",
args: ["Iku"],
},
],
"write",
);
await turso.execute({
sql: "SELECT * FROM users WHERE id = ?",
args: [1],
});
```
## Examples
| Example | Description |
| ------------------------------------- | --------------------------------------------------------------------------------------- |
| [local](examples/local) | Uses libsql with a local SQLite file. Creates database, inserts data, and queries. |
| [remote](examples/remote) | Connects to a remote database. Requires environment variables for URL and auth token. |
| [sync](examples/sync) | Demonstrates synchronization between local and remote databases. |
| [batch](examples/batch) | Executes multiple SQL statements in a single batch operation. |
| [transactions](examples/transactions) | Shows transaction usage: starting, performing operations, and committing/rolling back. |
| [memory](examples/memory) | Uses an in-memory SQLite database for temporary storage or fast access. |
| [vector](examples/vector) | Works with vector embeddings, storing and querying for similarity search. |
| [encryption](examples/encryption) | Creates and uses an encrypted SQLite database, demonstrating setup and data operations. |
| [ollama](examples/ollama) | Similarity search with Ollama and Mistral. |
## Documentation
Visit our [official documentation](https://docs.turso.tech/sdk/ts).
## Support
Join us [on Discord](https://tur.so/discord-ts) to get help using this SDK. Report security issues [via email](mailto:[email protected]).
## Contributors
See the [contributing guide](CONTRIBUTING.md) to learn how to get involved.
![Contributors](https://contrib.nn.ci/api?repo=tursodatabase/libsql-client-ts)
<a href="https://github.com/tursodatabase/libsql-client-ts/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22">
<picture>
<img src="https://img.shields.io/github/issues-search/tursodatabase/libsql-client-ts?label=good%20first%20issue&query=label%3A%22good%20first%20issue%22%20&color=0F624B" alt="good first issue" />
</picture>
</a>
+372
View File
@@ -0,0 +1,372 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapHranaError = exports.resultSetFromHrana = exports.stmtToHrana = exports.executeHranaBatch = exports.HranaTransaction = void 0;
const hrana = __importStar(require("@libsql/hrana-client"));
const api_1 = require("@libsql/core/api");
const util_1 = require("@libsql/core/util");
class HranaTransaction {
#mode;
#version;
// Promise that is resolved when the BEGIN statement completes, or `undefined` if we haven't executed the
// BEGIN statement yet.
#started;
/** @private */
constructor(mode, version) {
this.#mode = mode;
this.#version = version;
this.#started = undefined;
}
execute(stmt) {
return this.batch([stmt]).then((results) => results[0]);
}
async batch(stmts) {
const stream = this._getStream();
if (stream.closed) {
throw new api_1.LibsqlError("Cannot execute statements because the transaction is closed", "TRANSACTION_CLOSED");
}
try {
const hranaStmts = stmts.map(stmtToHrana);
let rowsPromises;
if (this.#started === undefined) {
// The transaction hasn't started yet, so we need to send the BEGIN statement in a batch with
// `hranaStmts`.
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
const beginStep = batch.step();
const beginPromise = beginStep.run((0, util_1.transactionModeToBegin)(this.#mode));
// Execute the `hranaStmts` only if the BEGIN succeeded, to make sure that we don't execute it
// outside of a transaction.
let lastStep = beginStep;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch
.step()
.condition(hrana.BatchCond.ok(lastStep));
if (this.#version >= 3) {
// If the Hrana version supports it, make sure that we are still in a transaction
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
// `this.#started` is resolved successfully only if the batch and the BEGIN statement inside
// of the batch are both successful.
this.#started = batch
.execute()
.then(() => beginPromise)
.then(() => undefined);
try {
await this.#started;
}
catch (e) {
// If the BEGIN failed, the transaction is unusable and we must close it. However, if the
// BEGIN suceeds and `hranaStmts` fail, the transaction is _not_ closed.
this.close();
throw e;
}
}
else {
if (this.#version < 3) {
// The transaction has started, so we must wait until the BEGIN statement completed to make
// sure that we don't execute `hranaStmts` outside of a transaction.
await this.#started;
}
else {
// The transaction has started, but we will use `hrana.BatchCond.isAutocommit()` to make
// sure that we don't execute `hranaStmts` outside of a transaction, so we don't have to
// wait for `this.#started`
}
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
let lastStep = undefined;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step();
if (lastStep !== undefined) {
stmtStep.condition(hrana.BatchCond.ok(lastStep));
}
if (this.#version >= 3) {
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
await batch.execute();
}
const resultSets = [];
for (let i = 0; i < rowsPromises.length; i++) {
try {
const rows = await rowsPromises[i];
if (rows === undefined) {
throw new api_1.LibsqlBatchError("Statement in a transaction was not executed, " +
"probably because the transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(resultSetFromHrana(rows));
}
catch (e) {
if (e instanceof api_1.LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof api_1.LibsqlError) {
throw new api_1.LibsqlBatchError(mappedError.message, i, mappedError.code, mappedError.extendedCode, mappedError.rawCode, mappedError.cause instanceof Error
? mappedError.cause
: undefined);
}
throw mappedError;
}
}
return resultSets;
}
catch (e) {
throw mapHranaError(e);
}
}
async executeMultiple(sql) {
const stream = this._getStream();
if (stream.closed) {
throw new api_1.LibsqlError("Cannot execute statements because the transaction is closed", "TRANSACTION_CLOSED");
}
try {
if (this.#started === undefined) {
// If the transaction hasn't started yet, start it now
this.#started = stream
.run((0, util_1.transactionModeToBegin)(this.#mode))
.then(() => undefined);
try {
await this.#started;
}
catch (e) {
this.close();
throw e;
}
}
else {
// Wait until the transaction has started
await this.#started;
}
await stream.sequence(sql);
}
catch (e) {
throw mapHranaError(e);
}
}
async rollback() {
try {
const stream = this._getStream();
if (stream.closed) {
return;
}
if (this.#started !== undefined) {
// We don't have to wait for the BEGIN statement to complete. If the BEGIN fails, we will
// execute a ROLLBACK outside of an active transaction, which should be harmless.
}
else {
// We did nothing in the transaction, so there is nothing to rollback.
return;
}
// Pipeline the ROLLBACK statement and the stream close.
const promise = stream.run("ROLLBACK").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
}
catch (e) {
throw mapHranaError(e);
}
finally {
// `this.close()` may close the `hrana.Client`, which aborts all pending stream requests, so we
// must call it _after_ we receive the ROLLBACK response.
// Also note that the current stream should already be closed, but we need to call `this.close()`
// anyway, because it may need to do more cleanup.
this.close();
}
}
async commit() {
// (this method is analogous to `rollback()`)
try {
const stream = this._getStream();
if (stream.closed) {
throw new api_1.LibsqlError("Cannot commit the transaction because it is already closed", "TRANSACTION_CLOSED");
}
if (this.#started !== undefined) {
// Make sure to execute the COMMIT only if the BEGIN was successful.
await this.#started;
}
else {
return;
}
const promise = stream.run("COMMIT").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
}
catch (e) {
throw mapHranaError(e);
}
finally {
this.close();
}
}
}
exports.HranaTransaction = HranaTransaction;
async function executeHranaBatch(mode, version, batch, hranaStmts, disableForeignKeys = false) {
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=off");
}
const beginStep = batch.step();
const beginPromise = beginStep.run((0, util_1.transactionModeToBegin)(mode));
let lastStep = beginStep;
const stmtPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const stmtPromise = stmtStep.query(hranaStmt);
lastStep = stmtStep;
return stmtPromise;
});
const commitStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
commitStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const commitPromise = commitStep.run("COMMIT");
const rollbackStep = batch
.step()
.condition(hrana.BatchCond.not(hrana.BatchCond.ok(commitStep)));
rollbackStep.run("ROLLBACK").catch((_) => undefined);
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=on");
}
await batch.execute();
const resultSets = [];
await beginPromise;
for (let i = 0; i < stmtPromises.length; i++) {
try {
const hranaRows = await stmtPromises[i];
if (hranaRows === undefined) {
throw new api_1.LibsqlBatchError("Statement in a batch was not executed, probably because the transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(resultSetFromHrana(hranaRows));
}
catch (e) {
if (e instanceof api_1.LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof api_1.LibsqlError) {
throw new api_1.LibsqlBatchError(mappedError.message, i, mappedError.code, mappedError.extendedCode, mappedError.rawCode, mappedError.cause instanceof Error
? mappedError.cause
: undefined);
}
throw mappedError;
}
}
await commitPromise;
return resultSets;
}
exports.executeHranaBatch = executeHranaBatch;
function stmtToHrana(stmt) {
let sql;
let args;
if (Array.isArray(stmt)) {
[sql, args] = stmt;
}
else if (typeof stmt === "string") {
sql = stmt;
}
else {
sql = stmt.sql;
args = stmt.args;
}
const hranaStmt = new hrana.Stmt(sql);
if (args) {
if (Array.isArray(args)) {
hranaStmt.bindIndexes(args);
}
else {
for (const [key, value] of Object.entries(args)) {
hranaStmt.bindName(key, value);
}
}
}
return hranaStmt;
}
exports.stmtToHrana = stmtToHrana;
function resultSetFromHrana(hranaRows) {
const columns = hranaRows.columnNames.map((c) => c ?? "");
const columnTypes = hranaRows.columnDecltypes.map((c) => c ?? "");
const rows = hranaRows.rows;
const rowsAffected = hranaRows.affectedRowCount;
const lastInsertRowid = hranaRows.lastInsertRowid !== undefined
? hranaRows.lastInsertRowid
: undefined;
return new util_1.ResultSetImpl(columns, columnTypes, rows, rowsAffected, lastInsertRowid);
}
exports.resultSetFromHrana = resultSetFromHrana;
function mapHranaError(e) {
if (e instanceof hrana.ClientError) {
const code = mapHranaErrorCode(e);
// TODO: Parse extendedCode once the SQL over HTTP protocol supports it
return new api_1.LibsqlError(e.message, code, undefined, undefined, e);
}
return e;
}
exports.mapHranaError = mapHranaError;
function mapHranaErrorCode(e) {
if (e instanceof hrana.ResponseError && e.code !== undefined) {
return e.code;
}
else if (e instanceof hrana.ProtoError) {
return "HRANA_PROTO_ERROR";
}
else if (e instanceof hrana.ClosedError) {
return e.cause instanceof hrana.ClientError
? mapHranaErrorCode(e.cause)
: "HRANA_CLOSED_ERROR";
}
else if (e instanceof hrana.WebSocketError) {
return "HRANA_WEBSOCKET_ERROR";
}
else if (e instanceof hrana.HttpServerError) {
return "SERVER_ERROR";
}
else if (e instanceof hrana.ProtocolVersionError) {
return "PROTOCOL_VERSION_ERROR";
}
else if (e instanceof hrana.InternalError) {
return "INTERNAL_ERROR";
}
else {
return "UNKNOWN";
}
}
+268
View File
@@ -0,0 +1,268 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpTransaction = exports.HttpClient = exports._createClient = exports.createClient = void 0;
const hrana = __importStar(require("@libsql/hrana-client"));
const api_1 = require("@libsql/core/api");
const config_1 = require("@libsql/core/config");
const hrana_js_1 = require("./hrana.js");
const sql_cache_js_1 = require("./sql_cache.js");
const uri_1 = require("@libsql/core/uri");
const util_1 = require("@libsql/core/util");
const promise_limit_1 = __importDefault(require("promise-limit"));
__exportStar(require("@libsql/core/api"), exports);
function createClient(config) {
return _createClient((0, config_1.expandConfig)(config, true));
}
exports.createClient = createClient;
/** @private */
function _createClient(config) {
if (config.scheme !== "https" && config.scheme !== "http") {
throw new api_1.LibsqlError('The HTTP client supports only "libsql:", "https:" and "http:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${util_1.supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (config.encryptionKey !== undefined) {
throw new api_1.LibsqlError("Encryption key is not supported by the remote client.", "ENCRYPTION_KEY_NOT_SUPPORTED");
}
if (config.scheme === "http" && config.tls) {
throw new api_1.LibsqlError(`A "http:" URL cannot opt into TLS by using ?tls=1`, "URL_INVALID");
}
else if (config.scheme === "https" && !config.tls) {
throw new api_1.LibsqlError(`A "https:" URL cannot opt out of TLS by using ?tls=0`, "URL_INVALID");
}
const url = (0, uri_1.encodeBaseUrl)(config.scheme, config.authority, config.path);
return new HttpClient(url, config.authToken, config.intMode, config.fetch, config.concurrency, config.remoteEncryptionKey);
}
exports._createClient = _createClient;
const sqlCacheCapacity = 30;
class HttpClient {
#client;
protocol;
#url;
#intMode;
#customFetch;
#concurrency;
#authToken;
#remoteEncryptionKey;
#promiseLimitFunction;
/** @private */
constructor(url, authToken, intMode, customFetch, concurrency, remoteEncryptionKey) {
this.#url = url;
this.#authToken = authToken;
this.#intMode = intMode;
this.#customFetch = customFetch;
this.#concurrency = concurrency;
this.#remoteEncryptionKey = remoteEncryptionKey;
this.#client = hrana.openHttp(this.#url, this.#authToken, this.#customFetch, remoteEncryptionKey);
this.#client.intMode = this.#intMode;
this.protocol = "http";
this.#promiseLimitFunction = (0, promise_limit_1.default)(this.#concurrency);
}
async limit(fn) {
return this.#promiseLimitFunction(fn);
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
return this.limit(async () => {
try {
const hranaStmt = (0, hrana_js_1.stmtToHrana)(stmt);
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the statement and
// close the stream in a single HTTP request.
let rowsPromise;
const stream = this.#client.openStream();
try {
rowsPromise = stream.query(hranaStmt);
}
finally {
stream.closeGracefully();
}
const rowsResult = await rowsPromise;
return (0, hrana_js_1.resultSetFromHrana)(rowsResult);
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
async batch(stmts, mode = "deferred") {
return this.limit(async () => {
try {
const normalizedStmts = stmts.map((stmt) => {
if (Array.isArray(stmt)) {
return {
sql: stmt[0],
args: stmt[1] || [],
};
}
return stmt;
});
const hranaStmts = normalizedStmts.map(hrana_js_1.stmtToHrana);
const version = await this.#client.getVersion();
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the batch and
// close the stream in a single HTTP request.
let resultsPromise;
const stream = this.#client.openStream();
try {
// It makes sense to use a SQL cache even for a single batch, because it may contain the same
// statement repeated multiple times.
const sqlCache = new sql_cache_js_1.SqlCache(stream, sqlCacheCapacity);
sqlCache.apply(hranaStmts);
// TODO: we do not use a cursor here, because it would cause three roundtrips:
// 1. pipeline request to store SQL texts
// 2. cursor request
// 3. pipeline request to close the stream
const batch = stream.batch(false);
resultsPromise = (0, hrana_js_1.executeHranaBatch)(mode, version, batch, hranaStmts);
}
finally {
stream.closeGracefully();
}
const results = await resultsPromise;
return results;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
async migrate(stmts) {
return this.limit(async () => {
try {
const hranaStmts = stmts.map(hrana_js_1.stmtToHrana);
const version = await this.#client.getVersion();
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the batch and
// close the stream in a single HTTP request.
let resultsPromise;
const stream = this.#client.openStream();
try {
const batch = stream.batch(false);
resultsPromise = (0, hrana_js_1.executeHranaBatch)("deferred", version, batch, hranaStmts, true);
}
finally {
stream.closeGracefully();
}
const results = await resultsPromise;
return results;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
async transaction(mode = "write") {
return this.limit(async () => {
try {
const version = await this.#client.getVersion();
return new HttpTransaction(this.#client.openStream(), mode, version);
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
async executeMultiple(sql) {
return this.limit(async () => {
try {
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the sequence and
// close the stream in a single HTTP request.
let promise;
const stream = this.#client.openStream();
try {
promise = stream.sequence(sql);
}
finally {
stream.closeGracefully();
}
await promise;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
sync() {
throw new api_1.LibsqlError("sync not supported in http mode", "SYNC_NOT_SUPPORTED");
}
close() {
this.#client.close();
}
async reconnect() {
try {
if (!this.closed) {
// Abort in-flight ops and free resources
this.#client.close();
}
}
finally {
// Recreate the underlying hrana client
this.#client = hrana.openHttp(this.#url, this.#authToken, this.#customFetch, this.#remoteEncryptionKey);
this.#client.intMode = this.#intMode;
}
}
get closed() {
return this.#client.closed;
}
}
exports.HttpClient = HttpClient;
class HttpTransaction extends hrana_js_1.HranaTransaction {
#stream;
#sqlCache;
/** @private */
constructor(stream, mode, version) {
super(mode, version);
this.#stream = stream;
this.#sqlCache = new sql_cache_js_1.SqlCache(stream, sqlCacheCapacity);
}
/** @private */
_getStream() {
return this.#stream;
}
/** @private */
_getSqlCache() {
return this.#sqlCache;
}
close() {
this.#stream.close();
}
get closed() {
return this.#stream.closed;
}
}
exports.HttpTransaction = HttpTransaction;
+41
View File
@@ -0,0 +1,41 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClient = void 0;
const config_1 = require("@libsql/core/config");
const sqlite3_js_1 = require("./sqlite3.js");
const ws_js_1 = require("./ws.js");
const http_js_1 = require("./http.js");
__exportStar(require("@libsql/core/api"), exports);
/** Creates a {@link Client} object.
*
* You must pass at least an `url` in the {@link Config} object.
*/
function createClient(config) {
return _createClient((0, config_1.expandConfig)(config, true));
}
exports.createClient = createClient;
function _createClient(config) {
if (config.scheme === "wss" || config.scheme === "ws") {
return (0, ws_js_1._createClient)(config);
}
else if (config.scheme === "https" || config.scheme === "http") {
return (0, http_js_1._createClient)(config);
}
else {
return (0, sqlite3_js_1._createClient)(config);
}
}
+3
View File
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
+91
View File
@@ -0,0 +1,91 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqlCache = void 0;
class SqlCache {
#owner;
#sqls;
capacity;
constructor(owner, capacity) {
this.#owner = owner;
this.#sqls = new Lru();
this.capacity = capacity;
}
// Replaces SQL strings with cached `hrana.Sql` objects in the statements in `hranaStmts`. After this
// function returns, we guarantee that all `hranaStmts` refer to valid (not closed) `hrana.Sql` objects,
// but _we may invalidate any other `hrana.Sql` objects_ (by closing them, thus removing them from the
// server).
//
// In practice, this means that after calling this function, you can use the statements only up to the
// first `await`, because concurrent code may also use the cache and invalidate those statements.
apply(hranaStmts) {
if (this.capacity <= 0) {
return;
}
const usedSqlObjs = new Set();
for (const hranaStmt of hranaStmts) {
if (typeof hranaStmt.sql !== "string") {
continue;
}
const sqlText = hranaStmt.sql;
// Stored SQL cannot exceed 5kb.
// https://github.com/tursodatabase/libsql/blob/e9d637e051685f92b0da43849507b5ef4232fbeb/libsql-server/src/hrana/http/request.rs#L10
if (sqlText.length >= 5000) {
continue;
}
let sqlObj = this.#sqls.get(sqlText);
if (sqlObj === undefined) {
while (this.#sqls.size + 1 > this.capacity) {
const [evictSqlText, evictSqlObj] = this.#sqls.peekLru();
if (usedSqlObjs.has(evictSqlObj)) {
// The SQL object that we are trying to evict is already in use in this batch, so we
// must not evict and close it.
break;
}
evictSqlObj.close();
this.#sqls.delete(evictSqlText);
}
if (this.#sqls.size + 1 <= this.capacity) {
sqlObj = this.#owner.storeSql(sqlText);
this.#sqls.set(sqlText, sqlObj);
}
}
if (sqlObj !== undefined) {
hranaStmt.sql = sqlObj;
usedSqlObjs.add(sqlObj);
}
}
}
}
exports.SqlCache = SqlCache;
class Lru {
// This maps keys to the cache values. The entries are ordered by their last use (entires that were used
// most recently are at the end).
#cache;
constructor() {
this.#cache = new Map();
}
get(key) {
const value = this.#cache.get(key);
if (value !== undefined) {
// move the entry to the back of the Map
this.#cache.delete(key);
this.#cache.set(key, value);
}
return value;
}
set(key, value) {
this.#cache.set(key, value);
}
peekLru() {
for (const entry of this.#cache.entries()) {
return entry;
}
return undefined;
}
delete(key) {
this.#cache.delete(key);
}
get size() {
return this.#cache.size;
}
}
+500
View File
@@ -0,0 +1,500 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Sqlite3Transaction = exports.Sqlite3Client = exports._createClient = exports.createClient = void 0;
const libsql_1 = __importDefault(require("libsql"));
const node_buffer_1 = require("node:buffer");
const api_1 = require("@libsql/core/api");
const config_1 = require("@libsql/core/config");
const util_1 = require("@libsql/core/util");
__exportStar(require("@libsql/core/api"), exports);
function createClient(config) {
return _createClient((0, config_1.expandConfig)(config, true));
}
exports.createClient = createClient;
/** @private */
function _createClient(config) {
if (config.scheme !== "file") {
throw new api_1.LibsqlError(`URL scheme ${JSON.stringify(config.scheme + ":")} is not supported by the local sqlite3 client. ` +
`For more information, please read ${util_1.supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
const authority = config.authority;
if (authority !== undefined) {
const host = authority.host.toLowerCase();
if (host !== "" && host !== "localhost") {
throw new api_1.LibsqlError(`Invalid host in file URL: ${JSON.stringify(authority.host)}. ` +
'A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") ' +
'or with three slashes ("file:///absolute/path.db"). ' +
`For more information, please read ${util_1.supportedUrlLink}`, "URL_INVALID");
}
if (authority.port !== undefined) {
throw new api_1.LibsqlError("File URL cannot have a port", "URL_INVALID");
}
if (authority.userinfo !== undefined) {
throw new api_1.LibsqlError("File URL cannot have username and password", "URL_INVALID");
}
}
let isInMemory = (0, config_1.isInMemoryConfig)(config);
if (isInMemory && config.syncUrl) {
throw new api_1.LibsqlError(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${config.path}`, "URL_INVALID");
}
let path = config.path;
if (isInMemory) {
// note: we should prepend file scheme in order for SQLite3 to recognize :memory: connection query parameters
path = `${config.scheme}:${config.path}`;
}
const options = {
authToken: config.authToken,
encryptionKey: config.encryptionKey,
remoteEncryptionKey: config.remoteEncryptionKey,
syncUrl: config.syncUrl,
syncPeriod: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
};
const db = new libsql_1.default(path, options);
executeStmt(db, "SELECT 1 AS checkThatTheDatabaseCanBeOpened", config.intMode);
return new Sqlite3Client(path, options, db, config.intMode);
}
exports._createClient = _createClient;
class Sqlite3Client {
#path;
#options;
#db;
#intMode;
closed;
protocol;
/** @private */
constructor(path, options, db, intMode) {
this.#path = path;
this.#options = options;
this.#db = db;
this.#intMode = intMode;
this.closed = false;
this.protocol = "file";
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
this.#checkNotClosed();
return executeStmt(this.#getDb(), stmt, this.#intMode);
}
async batch(stmts, mode = "deferred") {
this.#checkNotClosed();
const db = this.#getDb();
try {
executeStmt(db, (0, util_1.transactionModeToBegin)(mode), this.#intMode);
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
if (!db.inTransaction) {
throw new api_1.LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
const stmt = stmts[i];
const normalizedStmt = Array.isArray(stmt)
? { sql: stmt[0], args: stmt[1] || [] }
: stmt;
resultSets.push(executeStmt(db, normalizedStmt, this.#intMode));
}
catch (e) {
if (e instanceof api_1.LibsqlBatchError) {
throw e;
}
if (e instanceof api_1.LibsqlError) {
throw new api_1.LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
executeStmt(db, "COMMIT", this.#intMode);
return resultSets;
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
}
}
async migrate(stmts) {
this.#checkNotClosed();
const db = this.#getDb();
try {
executeStmt(db, "PRAGMA foreign_keys=off", this.#intMode);
executeStmt(db, (0, util_1.transactionModeToBegin)("deferred"), this.#intMode);
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
if (!db.inTransaction) {
throw new api_1.LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(executeStmt(db, stmts[i], this.#intMode));
}
catch (e) {
if (e instanceof api_1.LibsqlBatchError) {
throw e;
}
if (e instanceof api_1.LibsqlError) {
throw new api_1.LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
executeStmt(db, "COMMIT", this.#intMode);
return resultSets;
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
executeStmt(db, "PRAGMA foreign_keys=on", this.#intMode);
}
}
async transaction(mode = "write") {
const db = this.#getDb();
executeStmt(db, (0, util_1.transactionModeToBegin)(mode), this.#intMode);
this.#db = null; // A new connection will be lazily created on next use
return new Sqlite3Transaction(db, this.#intMode);
}
async executeMultiple(sql) {
this.#checkNotClosed();
const db = this.#getDb();
try {
return executeMultiple(db, sql);
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
}
}
async sync() {
this.#checkNotClosed();
const rep = await this.#getDb().sync();
return {
frames_synced: rep.frames_synced,
frame_no: rep.frame_no,
};
}
async reconnect() {
try {
if (!this.closed && this.#db !== null) {
this.#db.close();
}
}
finally {
this.#db = new libsql_1.default(this.#path, this.#options);
this.closed = false;
}
}
close() {
this.closed = true;
if (this.#db !== null) {
this.#db.close();
this.#db = null;
}
}
#checkNotClosed() {
if (this.closed) {
throw new api_1.LibsqlError("The client is closed", "CLIENT_CLOSED");
}
}
// Lazily creates the database connection and returns it
#getDb() {
if (this.#db === null) {
this.#db = new libsql_1.default(this.#path, this.#options);
}
return this.#db;
}
}
exports.Sqlite3Client = Sqlite3Client;
class Sqlite3Transaction {
#database;
#intMode;
/** @private */
constructor(database, intMode) {
this.#database = database;
this.#intMode = intMode;
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
this.#checkNotClosed();
return executeStmt(this.#database, stmt, this.#intMode);
}
async batch(stmts) {
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
this.#checkNotClosed();
const stmt = stmts[i];
const normalizedStmt = Array.isArray(stmt)
? { sql: stmt[0], args: stmt[1] || [] }
: stmt;
resultSets.push(executeStmt(this.#database, normalizedStmt, this.#intMode));
}
catch (e) {
if (e instanceof api_1.LibsqlBatchError) {
throw e;
}
if (e instanceof api_1.LibsqlError) {
throw new api_1.LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
return resultSets;
}
async executeMultiple(sql) {
this.#checkNotClosed();
return executeMultiple(this.#database, sql);
}
async rollback() {
if (!this.#database.open) {
return;
}
this.#checkNotClosed();
executeStmt(this.#database, "ROLLBACK", this.#intMode);
}
async commit() {
this.#checkNotClosed();
executeStmt(this.#database, "COMMIT", this.#intMode);
}
close() {
if (this.#database.inTransaction) {
executeStmt(this.#database, "ROLLBACK", this.#intMode);
}
}
get closed() {
return !this.#database.inTransaction;
}
#checkNotClosed() {
if (this.closed) {
throw new api_1.LibsqlError("The transaction is closed", "TRANSACTION_CLOSED");
}
}
}
exports.Sqlite3Transaction = Sqlite3Transaction;
function executeStmt(db, stmt, intMode) {
let sql;
let args;
if (typeof stmt === "string") {
sql = stmt;
args = [];
}
else {
sql = stmt.sql;
if (Array.isArray(stmt.args)) {
args = stmt.args.map((value) => valueToSql(value, intMode));
}
else {
args = {};
for (const name in stmt.args) {
const argName = name[0] === "@" || name[0] === "$" || name[0] === ":"
? name.substring(1)
: name;
args[argName] = valueToSql(stmt.args[name], intMode);
}
}
}
try {
const sqlStmt = db.prepare(sql);
sqlStmt.safeIntegers(true);
let returnsData = true;
try {
sqlStmt.raw(true);
}
catch {
// raw() throws an exception if the statement does not return data
returnsData = false;
}
if (returnsData) {
const columns = Array.from(sqlStmt.columns().map((col) => col.name));
const columnTypes = Array.from(sqlStmt.columns().map((col) => col.type ?? ""));
const rows = sqlStmt.all(args).map((sqlRow) => {
return rowFromSql(sqlRow, columns, intMode);
});
// TODO: can we get this info from better-sqlite3?
const rowsAffected = 0;
const lastInsertRowid = undefined;
return new util_1.ResultSetImpl(columns, columnTypes, rows, rowsAffected, lastInsertRowid);
}
else {
const info = sqlStmt.run(args);
const rowsAffected = info.changes;
const lastInsertRowid = BigInt(info.lastInsertRowid);
return new util_1.ResultSetImpl([], [], [], rowsAffected, lastInsertRowid);
}
}
catch (e) {
throw mapSqliteError(e);
}
}
function rowFromSql(sqlRow, columns, intMode) {
const row = {};
// make sure that the "length" property is not enumerable
Object.defineProperty(row, "length", { value: sqlRow.length });
for (let i = 0; i < sqlRow.length; ++i) {
const value = valueFromSql(sqlRow[i], intMode);
Object.defineProperty(row, i, { value });
const column = columns[i];
if (!Object.hasOwn(row, column)) {
Object.defineProperty(row, column, {
value,
enumerable: true,
configurable: true,
writable: true,
});
}
}
return row;
}
function valueFromSql(sqlValue, intMode) {
if (typeof sqlValue === "bigint") {
if (intMode === "number") {
if (sqlValue < minSafeBigint || sqlValue > maxSafeBigint) {
throw new RangeError("Received integer which cannot be safely represented as a JavaScript number");
}
return Number(sqlValue);
}
else if (intMode === "bigint") {
return sqlValue;
}
else if (intMode === "string") {
return "" + sqlValue;
}
else {
throw new Error("Invalid value for IntMode");
}
}
else if (sqlValue instanceof node_buffer_1.Buffer) {
return sqlValue.buffer;
}
return sqlValue;
}
const minSafeBigint = -9007199254740991n;
const maxSafeBigint = 9007199254740991n;
function valueToSql(value, intMode) {
if (typeof value === "number") {
if (!Number.isFinite(value)) {
throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");
}
return value;
}
else if (typeof value === "bigint") {
if (value < minInteger || value > maxInteger) {
throw new RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");
}
return value;
}
else if (typeof value === "boolean") {
switch (intMode) {
case "bigint":
return value ? 1n : 0n;
case "string":
return value ? "1" : "0";
default:
return value ? 1 : 0;
}
}
else if (value instanceof ArrayBuffer) {
return node_buffer_1.Buffer.from(value);
}
else if (value instanceof Date) {
return value.valueOf();
}
else if (value === undefined) {
throw new TypeError("undefined cannot be passed as argument to the database");
}
else {
return value;
}
}
const minInteger = -9223372036854775808n;
const maxInteger = 9223372036854775807n;
function executeMultiple(db, sql) {
try {
db.exec(sql);
}
catch (e) {
throw mapSqliteError(e);
}
}
function mapSqliteError(e) {
if (e instanceof libsql_1.default.SqliteError) {
const extendedCode = e.code;
const code = mapToBaseCode(e.rawCode);
return new api_1.LibsqlError(e.message, code, extendedCode, e.rawCode, e);
}
return e;
}
// Map SQLite raw error code to base error code string.
// Extended error codes are (base | (extended << 8)), so base = rawCode & 0xFF
function mapToBaseCode(rawCode) {
if (rawCode === undefined) {
return "SQLITE_UNKNOWN";
}
const baseCode = rawCode & 0xff;
return (sqliteErrorCodes[baseCode] ?? `SQLITE_UNKNOWN_${baseCode.toString()}`);
}
const sqliteErrorCodes = {
1: "SQLITE_ERROR",
2: "SQLITE_INTERNAL",
3: "SQLITE_PERM",
4: "SQLITE_ABORT",
5: "SQLITE_BUSY",
6: "SQLITE_LOCKED",
7: "SQLITE_NOMEM",
8: "SQLITE_READONLY",
9: "SQLITE_INTERRUPT",
10: "SQLITE_IOERR",
11: "SQLITE_CORRUPT",
12: "SQLITE_NOTFOUND",
13: "SQLITE_FULL",
14: "SQLITE_CANTOPEN",
15: "SQLITE_PROTOCOL",
16: "SQLITE_EMPTY",
17: "SQLITE_SCHEMA",
18: "SQLITE_TOOBIG",
19: "SQLITE_CONSTRAINT",
20: "SQLITE_MISMATCH",
21: "SQLITE_MISUSE",
22: "SQLITE_NOLFS",
23: "SQLITE_AUTH",
24: "SQLITE_FORMAT",
25: "SQLITE_RANGE",
26: "SQLITE_NOTADB",
27: "SQLITE_NOTICE",
28: "SQLITE_WARNING",
};
+41
View File
@@ -0,0 +1,41 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports._createClient = exports.createClient = void 0;
const api_1 = require("@libsql/core/api");
const config_1 = require("@libsql/core/config");
const util_1 = require("@libsql/core/util");
const ws_js_1 = require("./ws.js");
const http_js_1 = require("./http.js");
__exportStar(require("@libsql/core/api"), exports);
function createClient(config) {
return _createClient((0, config_1.expandConfig)(config, true));
}
exports.createClient = createClient;
/** @private */
function _createClient(config) {
if (config.scheme === "ws" || config.scheme === "wss") {
return (0, ws_js_1._createClient)(config);
}
else if (config.scheme === "http" || config.scheme === "https") {
return (0, http_js_1._createClient)(config);
}
else {
throw new api_1.LibsqlError('The client that uses Web standard APIs supports only "libsql:", "wss:", "ws:", "https:" and "http:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${util_1.supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
}
exports._createClient = _createClient;
+395
View File
@@ -0,0 +1,395 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WsTransaction = exports.WsClient = exports._createClient = exports.createClient = void 0;
const hrana = __importStar(require("@libsql/hrana-client"));
const api_1 = require("@libsql/core/api");
const config_1 = require("@libsql/core/config");
const hrana_js_1 = require("./hrana.js");
const sql_cache_js_1 = require("./sql_cache.js");
const uri_1 = require("@libsql/core/uri");
const util_1 = require("@libsql/core/util");
const promise_limit_1 = __importDefault(require("promise-limit"));
__exportStar(require("@libsql/core/api"), exports);
function createClient(config) {
return _createClient((0, config_1.expandConfig)(config, false));
}
exports.createClient = createClient;
/** @private */
function _createClient(config) {
if (config.scheme !== "wss" && config.scheme !== "ws") {
throw new api_1.LibsqlError('The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${util_1.supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (config.encryptionKey !== undefined) {
throw new api_1.LibsqlError("Encryption key is not supported by the remote client.", "ENCRYPTION_KEY_NOT_SUPPORTED");
}
if (config.scheme === "ws" && config.tls) {
throw new api_1.LibsqlError(`A "ws:" URL cannot opt into TLS by using ?tls=1`, "URL_INVALID");
}
else if (config.scheme === "wss" && !config.tls) {
throw new api_1.LibsqlError(`A "wss:" URL cannot opt out of TLS by using ?tls=0`, "URL_INVALID");
}
const url = (0, uri_1.encodeBaseUrl)(config.scheme, config.authority, config.path);
let client;
try {
client = hrana.openWs(url, config.authToken);
}
catch (e) {
if (e instanceof hrana.WebSocketUnsupportedError) {
const suggestedScheme = config.scheme === "wss" ? "https" : "http";
const suggestedUrl = (0, uri_1.encodeBaseUrl)(suggestedScheme, config.authority, config.path);
throw new api_1.LibsqlError("This environment does not support WebSockets, please switch to the HTTP client by using " +
`a "${suggestedScheme}:" URL (${JSON.stringify(suggestedUrl)}). ` +
`For more information, please read ${util_1.supportedUrlLink}`, "WEBSOCKETS_NOT_SUPPORTED");
}
throw (0, hrana_js_1.mapHranaError)(e);
}
return new WsClient(client, url, config.authToken, config.intMode, config.concurrency);
}
exports._createClient = _createClient;
const maxConnAgeMillis = 60 * 1000;
const sqlCacheCapacity = 100;
class WsClient {
#url;
#authToken;
#intMode;
// State of the current connection. The `hrana.WsClient` inside may be closed at any moment due to an
// asynchronous error.
#connState;
// If defined, this is a connection that will be used in the future, once it is ready.
#futureConnState;
closed;
protocol;
#isSchemaDatabase;
#promiseLimitFunction;
/** @private */
constructor(client, url, authToken, intMode, concurrency) {
this.#url = url;
this.#authToken = authToken;
this.#intMode = intMode;
this.#connState = this.#openConn(client);
this.#futureConnState = undefined;
this.closed = false;
this.protocol = "ws";
this.#promiseLimitFunction = (0, promise_limit_1.default)(concurrency);
}
async limit(fn) {
return this.#promiseLimitFunction(fn);
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const hranaStmt = (0, hrana_js_1.stmtToHrana)(stmt);
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
streamState.conn.sqlCache.apply([hranaStmt]);
const hranaRowsPromise = streamState.stream.query(hranaStmt);
streamState.stream.closeGracefully();
const hranaRowsResult = await hranaRowsPromise;
return (0, hrana_js_1.resultSetFromHrana)(hranaRowsResult);
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
finally {
this._closeStream(streamState);
}
});
}
async batch(stmts, mode = "deferred") {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const normalizedStmts = stmts.map((stmt) => {
if (Array.isArray(stmt)) {
return {
sql: stmt[0],
args: stmt[1] || [],
};
}
return stmt;
});
const hranaStmts = normalizedStmts.map(hrana_js_1.stmtToHrana);
const version = await streamState.conn.client.getVersion();
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
streamState.conn.sqlCache.apply(hranaStmts);
const batch = streamState.stream.batch(version >= 3);
const resultsPromise = (0, hrana_js_1.executeHranaBatch)(mode, version, batch, hranaStmts);
const results = await resultsPromise;
return results;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
finally {
this._closeStream(streamState);
}
});
}
async migrate(stmts) {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const hranaStmts = stmts.map(hrana_js_1.stmtToHrana);
const version = await streamState.conn.client.getVersion();
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
const batch = streamState.stream.batch(version >= 3);
const resultsPromise = (0, hrana_js_1.executeHranaBatch)("deferred", version, batch, hranaStmts, true);
const results = await resultsPromise;
return results;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
finally {
this._closeStream(streamState);
}
});
}
async transaction(mode = "write") {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const version = await streamState.conn.client.getVersion();
// the BEGIN statement will be batched with the first statement on the transaction to save a
// network roundtrip
return new WsTransaction(this, streamState, mode, version);
}
catch (e) {
this._closeStream(streamState);
throw (0, hrana_js_1.mapHranaError)(e);
}
});
}
async executeMultiple(sql) {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
const promise = streamState.stream.sequence(sql);
streamState.stream.closeGracefully();
await promise;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
finally {
this._closeStream(streamState);
}
});
}
sync() {
throw new api_1.LibsqlError("sync not supported in ws mode", "SYNC_NOT_SUPPORTED");
}
async #openStream() {
if (this.closed) {
throw new api_1.LibsqlError("The client is closed", "CLIENT_CLOSED");
}
const now = new Date();
const ageMillis = now.valueOf() - this.#connState.openTime.valueOf();
if (ageMillis > maxConnAgeMillis &&
this.#futureConnState === undefined) {
// The existing connection is too old, let's open a new one.
const futureConnState = this.#openConn();
this.#futureConnState = futureConnState;
// However, if we used `futureConnState` immediately, we would introduce additional latency,
// because we would have to wait for the WebSocket handshake to complete, even though we may a
// have perfectly good existing connection in `this.#connState`!
//
// So we wait until the `hrana.Client.getVersion()` operation completes (which happens when the
// WebSocket hanshake completes), and only then we replace `this.#connState` with
// `futureConnState`, which is stored in `this.#futureConnState` in the meantime.
futureConnState.client.getVersion().then((_version) => {
if (this.#connState !== futureConnState) {
// We need to close `this.#connState` before we replace it. However, it is possible
// that `this.#connState` has already been replaced: see the code below.
if (this.#connState.streamStates.size === 0) {
this.#connState.client.close();
}
else {
// If there are existing streams on the connection, we must not close it, because
// these streams would be broken. The last stream to be closed will also close the
// connection in `_closeStream()`.
}
}
this.#connState = futureConnState;
this.#futureConnState = undefined;
}, (_e) => {
// If the new connection could not be established, let's just ignore the error and keep
// using the existing connection.
this.#futureConnState = undefined;
});
}
if (this.#connState.client.closed) {
// An error happened on this connection and it has been closed. Let's try to seamlessly reconnect.
try {
if (this.#futureConnState !== undefined) {
// We are already in the process of opening a new connection, so let's just use it
// immediately.
this.#connState = this.#futureConnState;
}
else {
this.#connState = this.#openConn();
}
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
}
const connState = this.#connState;
try {
// Now we wait for the WebSocket handshake to complete (if it hasn't completed yet). Note that
// this does not increase latency, because any messages that we would send on the WebSocket before
// the handshake would be queued until the handshake is completed anyway.
if (connState.useSqlCache === undefined) {
connState.useSqlCache =
(await connState.client.getVersion()) >= 2;
if (connState.useSqlCache) {
connState.sqlCache.capacity = sqlCacheCapacity;
}
}
const stream = connState.client.openStream();
stream.intMode = this.#intMode;
const streamState = { conn: connState, stream };
connState.streamStates.add(streamState);
return streamState;
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
}
#openConn(client) {
try {
client ??= hrana.openWs(this.#url, this.#authToken);
return {
client,
useSqlCache: undefined,
sqlCache: new sql_cache_js_1.SqlCache(client, 0),
openTime: new Date(),
streamStates: new Set(),
};
}
catch (e) {
throw (0, hrana_js_1.mapHranaError)(e);
}
}
async reconnect() {
try {
for (const st of Array.from(this.#connState.streamStates)) {
try {
st.stream.close();
}
catch { }
}
this.#connState.client.close();
}
catch { }
if (this.#futureConnState) {
try {
this.#futureConnState.client.close();
}
catch { }
this.#futureConnState = undefined;
}
const next = this.#openConn();
const version = await next.client.getVersion();
next.useSqlCache = version >= 2;
if (next.useSqlCache) {
next.sqlCache.capacity = sqlCacheCapacity;
}
this.#connState = next;
this.closed = false;
}
_closeStream(streamState) {
streamState.stream.close();
const connState = streamState.conn;
connState.streamStates.delete(streamState);
if (connState.streamStates.size === 0 &&
connState !== this.#connState) {
// We are not using this connection anymore and this is the last stream that was using it, so we
// must close it now.
connState.client.close();
}
}
close() {
this.#connState.client.close();
this.closed = true;
if (this.#futureConnState) {
try {
this.#futureConnState.client.close();
}
catch { }
this.#futureConnState = undefined;
}
this.closed = true;
}
}
exports.WsClient = WsClient;
class WsTransaction extends hrana_js_1.HranaTransaction {
#client;
#streamState;
/** @private */
constructor(client, state, mode, version) {
super(mode, version);
this.#client = client;
this.#streamState = state;
}
/** @private */
_getStream() {
return this.#streamState.stream;
}
/** @private */
_getSqlCache() {
return this.#streamState.conn.sqlCache;
}
close() {
this.#client._closeStream(this.#streamState);
}
get closed() {
return this.#streamState.stream.closed;
}
}
exports.WsTransaction = WsTransaction;
+23
View File
@@ -0,0 +1,23 @@
import * as hrana from "@libsql/hrana-client";
import type { InStatement, ResultSet, Transaction, TransactionMode, InArgs } from "@libsql/core/api";
import type { SqlCache } from "./sql_cache.js";
export declare abstract class HranaTransaction implements Transaction {
#private;
/** @private */
constructor(mode: TransactionMode, version: hrana.ProtocolVersion);
/** @private */
abstract _getStream(): hrana.Stream;
/** @private */
abstract _getSqlCache(): SqlCache;
abstract close(): void;
abstract get closed(): boolean;
execute(stmt: InStatement): Promise<ResultSet>;
batch(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
executeMultiple(sql: string): Promise<void>;
rollback(): Promise<void>;
commit(): Promise<void>;
}
export declare function executeHranaBatch(mode: TransactionMode, version: hrana.ProtocolVersion, batch: hrana.Batch, hranaStmts: Array<hrana.Stmt>, disableForeignKeys?: boolean): Promise<Array<ResultSet>>;
export declare function stmtToHrana(stmt: InStatement | [string, InArgs?]): hrana.Stmt;
export declare function resultSetFromHrana(hranaRows: hrana.RowsResult): ResultSet;
export declare function mapHranaError(e: unknown): unknown;
+341
View File
@@ -0,0 +1,341 @@
import * as hrana from "@libsql/hrana-client";
import { LibsqlError, LibsqlBatchError } from "@libsql/core/api";
import { transactionModeToBegin, ResultSetImpl } from "@libsql/core/util";
export class HranaTransaction {
#mode;
#version;
// Promise that is resolved when the BEGIN statement completes, or `undefined` if we haven't executed the
// BEGIN statement yet.
#started;
/** @private */
constructor(mode, version) {
this.#mode = mode;
this.#version = version;
this.#started = undefined;
}
execute(stmt) {
return this.batch([stmt]).then((results) => results[0]);
}
async batch(stmts) {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError("Cannot execute statements because the transaction is closed", "TRANSACTION_CLOSED");
}
try {
const hranaStmts = stmts.map(stmtToHrana);
let rowsPromises;
if (this.#started === undefined) {
// The transaction hasn't started yet, so we need to send the BEGIN statement in a batch with
// `hranaStmts`.
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
const beginStep = batch.step();
const beginPromise = beginStep.run(transactionModeToBegin(this.#mode));
// Execute the `hranaStmts` only if the BEGIN succeeded, to make sure that we don't execute it
// outside of a transaction.
let lastStep = beginStep;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch
.step()
.condition(hrana.BatchCond.ok(lastStep));
if (this.#version >= 3) {
// If the Hrana version supports it, make sure that we are still in a transaction
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
// `this.#started` is resolved successfully only if the batch and the BEGIN statement inside
// of the batch are both successful.
this.#started = batch
.execute()
.then(() => beginPromise)
.then(() => undefined);
try {
await this.#started;
}
catch (e) {
// If the BEGIN failed, the transaction is unusable and we must close it. However, if the
// BEGIN suceeds and `hranaStmts` fail, the transaction is _not_ closed.
this.close();
throw e;
}
}
else {
if (this.#version < 3) {
// The transaction has started, so we must wait until the BEGIN statement completed to make
// sure that we don't execute `hranaStmts` outside of a transaction.
await this.#started;
}
else {
// The transaction has started, but we will use `hrana.BatchCond.isAutocommit()` to make
// sure that we don't execute `hranaStmts` outside of a transaction, so we don't have to
// wait for `this.#started`
}
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
let lastStep = undefined;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step();
if (lastStep !== undefined) {
stmtStep.condition(hrana.BatchCond.ok(lastStep));
}
if (this.#version >= 3) {
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
await batch.execute();
}
const resultSets = [];
for (let i = 0; i < rowsPromises.length; i++) {
try {
const rows = await rowsPromises[i];
if (rows === undefined) {
throw new LibsqlBatchError("Statement in a transaction was not executed, " +
"probably because the transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(resultSetFromHrana(rows));
}
catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof LibsqlError) {
throw new LibsqlBatchError(mappedError.message, i, mappedError.code, mappedError.extendedCode, mappedError.rawCode, mappedError.cause instanceof Error
? mappedError.cause
: undefined);
}
throw mappedError;
}
}
return resultSets;
}
catch (e) {
throw mapHranaError(e);
}
}
async executeMultiple(sql) {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError("Cannot execute statements because the transaction is closed", "TRANSACTION_CLOSED");
}
try {
if (this.#started === undefined) {
// If the transaction hasn't started yet, start it now
this.#started = stream
.run(transactionModeToBegin(this.#mode))
.then(() => undefined);
try {
await this.#started;
}
catch (e) {
this.close();
throw e;
}
}
else {
// Wait until the transaction has started
await this.#started;
}
await stream.sequence(sql);
}
catch (e) {
throw mapHranaError(e);
}
}
async rollback() {
try {
const stream = this._getStream();
if (stream.closed) {
return;
}
if (this.#started !== undefined) {
// We don't have to wait for the BEGIN statement to complete. If the BEGIN fails, we will
// execute a ROLLBACK outside of an active transaction, which should be harmless.
}
else {
// We did nothing in the transaction, so there is nothing to rollback.
return;
}
// Pipeline the ROLLBACK statement and the stream close.
const promise = stream.run("ROLLBACK").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
}
catch (e) {
throw mapHranaError(e);
}
finally {
// `this.close()` may close the `hrana.Client`, which aborts all pending stream requests, so we
// must call it _after_ we receive the ROLLBACK response.
// Also note that the current stream should already be closed, but we need to call `this.close()`
// anyway, because it may need to do more cleanup.
this.close();
}
}
async commit() {
// (this method is analogous to `rollback()`)
try {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError("Cannot commit the transaction because it is already closed", "TRANSACTION_CLOSED");
}
if (this.#started !== undefined) {
// Make sure to execute the COMMIT only if the BEGIN was successful.
await this.#started;
}
else {
return;
}
const promise = stream.run("COMMIT").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
}
catch (e) {
throw mapHranaError(e);
}
finally {
this.close();
}
}
}
export async function executeHranaBatch(mode, version, batch, hranaStmts, disableForeignKeys = false) {
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=off");
}
const beginStep = batch.step();
const beginPromise = beginStep.run(transactionModeToBegin(mode));
let lastStep = beginStep;
const stmtPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
stmtStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const stmtPromise = stmtStep.query(hranaStmt);
lastStep = stmtStep;
return stmtPromise;
});
const commitStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
commitStep.condition(hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)));
}
const commitPromise = commitStep.run("COMMIT");
const rollbackStep = batch
.step()
.condition(hrana.BatchCond.not(hrana.BatchCond.ok(commitStep)));
rollbackStep.run("ROLLBACK").catch((_) => undefined);
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=on");
}
await batch.execute();
const resultSets = [];
await beginPromise;
for (let i = 0; i < stmtPromises.length; i++) {
try {
const hranaRows = await stmtPromises[i];
if (hranaRows === undefined) {
throw new LibsqlBatchError("Statement in a batch was not executed, probably because the transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(resultSetFromHrana(hranaRows));
}
catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof LibsqlError) {
throw new LibsqlBatchError(mappedError.message, i, mappedError.code, mappedError.extendedCode, mappedError.rawCode, mappedError.cause instanceof Error
? mappedError.cause
: undefined);
}
throw mappedError;
}
}
await commitPromise;
return resultSets;
}
export function stmtToHrana(stmt) {
let sql;
let args;
if (Array.isArray(stmt)) {
[sql, args] = stmt;
}
else if (typeof stmt === "string") {
sql = stmt;
}
else {
sql = stmt.sql;
args = stmt.args;
}
const hranaStmt = new hrana.Stmt(sql);
if (args) {
if (Array.isArray(args)) {
hranaStmt.bindIndexes(args);
}
else {
for (const [key, value] of Object.entries(args)) {
hranaStmt.bindName(key, value);
}
}
}
return hranaStmt;
}
export function resultSetFromHrana(hranaRows) {
const columns = hranaRows.columnNames.map((c) => c ?? "");
const columnTypes = hranaRows.columnDecltypes.map((c) => c ?? "");
const rows = hranaRows.rows;
const rowsAffected = hranaRows.affectedRowCount;
const lastInsertRowid = hranaRows.lastInsertRowid !== undefined
? hranaRows.lastInsertRowid
: undefined;
return new ResultSetImpl(columns, columnTypes, rows, rowsAffected, lastInsertRowid);
}
export function mapHranaError(e) {
if (e instanceof hrana.ClientError) {
const code = mapHranaErrorCode(e);
// TODO: Parse extendedCode once the SQL over HTTP protocol supports it
return new LibsqlError(e.message, code, undefined, undefined, e);
}
return e;
}
function mapHranaErrorCode(e) {
if (e instanceof hrana.ResponseError && e.code !== undefined) {
return e.code;
}
else if (e instanceof hrana.ProtoError) {
return "HRANA_PROTO_ERROR";
}
else if (e instanceof hrana.ClosedError) {
return e.cause instanceof hrana.ClientError
? mapHranaErrorCode(e.cause)
: "HRANA_CLOSED_ERROR";
}
else if (e instanceof hrana.WebSocketError) {
return "HRANA_WEBSOCKET_ERROR";
}
else if (e instanceof hrana.HttpServerError) {
return "SERVER_ERROR";
}
else if (e instanceof hrana.ProtocolVersionError) {
return "PROTOCOL_VERSION_ERROR";
}
else if (e instanceof hrana.InternalError) {
return "INTERNAL_ERROR";
}
else {
return "UNKNOWN";
}
}
+38
View File
@@ -0,0 +1,38 @@
import * as hrana from "@libsql/hrana-client";
import type { Config, Client } from "@libsql/core/api";
import type { InStatement, ResultSet, Transaction, IntMode, InArgs, Replicated } from "@libsql/core/api";
import { TransactionMode } from "@libsql/core/api";
import type { ExpandedConfig } from "@libsql/core/config";
import { HranaTransaction } from "./hrana.js";
import { SqlCache } from "./sql_cache.js";
export * from "@libsql/core/api";
export declare function createClient(config: Config): Client;
/** @private */
export declare function _createClient(config: ExpandedConfig): Client;
export declare class HttpClient implements Client {
#private;
protocol: "http";
/** @private */
constructor(url: URL, authToken: string | undefined, intMode: IntMode, customFetch: Function | undefined, concurrency: number, remoteEncryptionKey: string | undefined);
private limit;
execute(stmtOrSql: InStatement | string, args?: InArgs): Promise<ResultSet>;
batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;
migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
transaction(mode?: TransactionMode): Promise<HttpTransaction>;
executeMultiple(sql: string): Promise<void>;
sync(): Promise<Replicated>;
close(): void;
reconnect(): Promise<void>;
get closed(): boolean;
}
export declare class HttpTransaction extends HranaTransaction implements Transaction {
#private;
/** @private */
constructor(stream: hrana.HttpStream, mode: TransactionMode, version: hrana.ProtocolVersion);
/** @private */
_getStream(): hrana.Stream;
/** @private */
_getSqlCache(): SqlCache;
close(): void;
get closed(): boolean;
}
+232
View File
@@ -0,0 +1,232 @@
import * as hrana from "@libsql/hrana-client";
import { LibsqlError } from "@libsql/core/api";
import { expandConfig } from "@libsql/core/config";
import { HranaTransaction, executeHranaBatch, stmtToHrana, resultSetFromHrana, mapHranaError, } from "./hrana.js";
import { SqlCache } from "./sql_cache.js";
import { encodeBaseUrl } from "@libsql/core/uri";
import { supportedUrlLink } from "@libsql/core/util";
import promiseLimit from "promise-limit";
export * from "@libsql/core/api";
export function createClient(config) {
return _createClient(expandConfig(config, true));
}
/** @private */
export function _createClient(config) {
if (config.scheme !== "https" && config.scheme !== "http") {
throw new LibsqlError('The HTTP client supports only "libsql:", "https:" and "http:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (config.encryptionKey !== undefined) {
throw new LibsqlError("Encryption key is not supported by the remote client.", "ENCRYPTION_KEY_NOT_SUPPORTED");
}
if (config.scheme === "http" && config.tls) {
throw new LibsqlError(`A "http:" URL cannot opt into TLS by using ?tls=1`, "URL_INVALID");
}
else if (config.scheme === "https" && !config.tls) {
throw new LibsqlError(`A "https:" URL cannot opt out of TLS by using ?tls=0`, "URL_INVALID");
}
const url = encodeBaseUrl(config.scheme, config.authority, config.path);
return new HttpClient(url, config.authToken, config.intMode, config.fetch, config.concurrency, config.remoteEncryptionKey);
}
const sqlCacheCapacity = 30;
export class HttpClient {
#client;
protocol;
#url;
#intMode;
#customFetch;
#concurrency;
#authToken;
#remoteEncryptionKey;
#promiseLimitFunction;
/** @private */
constructor(url, authToken, intMode, customFetch, concurrency, remoteEncryptionKey) {
this.#url = url;
this.#authToken = authToken;
this.#intMode = intMode;
this.#customFetch = customFetch;
this.#concurrency = concurrency;
this.#remoteEncryptionKey = remoteEncryptionKey;
this.#client = hrana.openHttp(this.#url, this.#authToken, this.#customFetch, remoteEncryptionKey);
this.#client.intMode = this.#intMode;
this.protocol = "http";
this.#promiseLimitFunction = promiseLimit(this.#concurrency);
}
async limit(fn) {
return this.#promiseLimitFunction(fn);
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
return this.limit(async () => {
try {
const hranaStmt = stmtToHrana(stmt);
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the statement and
// close the stream in a single HTTP request.
let rowsPromise;
const stream = this.#client.openStream();
try {
rowsPromise = stream.query(hranaStmt);
}
finally {
stream.closeGracefully();
}
const rowsResult = await rowsPromise;
return resultSetFromHrana(rowsResult);
}
catch (e) {
throw mapHranaError(e);
}
});
}
async batch(stmts, mode = "deferred") {
return this.limit(async () => {
try {
const normalizedStmts = stmts.map((stmt) => {
if (Array.isArray(stmt)) {
return {
sql: stmt[0],
args: stmt[1] || [],
};
}
return stmt;
});
const hranaStmts = normalizedStmts.map(stmtToHrana);
const version = await this.#client.getVersion();
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the batch and
// close the stream in a single HTTP request.
let resultsPromise;
const stream = this.#client.openStream();
try {
// It makes sense to use a SQL cache even for a single batch, because it may contain the same
// statement repeated multiple times.
const sqlCache = new SqlCache(stream, sqlCacheCapacity);
sqlCache.apply(hranaStmts);
// TODO: we do not use a cursor here, because it would cause three roundtrips:
// 1. pipeline request to store SQL texts
// 2. cursor request
// 3. pipeline request to close the stream
const batch = stream.batch(false);
resultsPromise = executeHranaBatch(mode, version, batch, hranaStmts);
}
finally {
stream.closeGracefully();
}
const results = await resultsPromise;
return results;
}
catch (e) {
throw mapHranaError(e);
}
});
}
async migrate(stmts) {
return this.limit(async () => {
try {
const hranaStmts = stmts.map(stmtToHrana);
const version = await this.#client.getVersion();
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the batch and
// close the stream in a single HTTP request.
let resultsPromise;
const stream = this.#client.openStream();
try {
const batch = stream.batch(false);
resultsPromise = executeHranaBatch("deferred", version, batch, hranaStmts, true);
}
finally {
stream.closeGracefully();
}
const results = await resultsPromise;
return results;
}
catch (e) {
throw mapHranaError(e);
}
});
}
async transaction(mode = "write") {
return this.limit(async () => {
try {
const version = await this.#client.getVersion();
return new HttpTransaction(this.#client.openStream(), mode, version);
}
catch (e) {
throw mapHranaError(e);
}
});
}
async executeMultiple(sql) {
return this.limit(async () => {
try {
// Pipeline all operations, so `hrana.HttpClient` can open the stream, execute the sequence and
// close the stream in a single HTTP request.
let promise;
const stream = this.#client.openStream();
try {
promise = stream.sequence(sql);
}
finally {
stream.closeGracefully();
}
await promise;
}
catch (e) {
throw mapHranaError(e);
}
});
}
sync() {
throw new LibsqlError("sync not supported in http mode", "SYNC_NOT_SUPPORTED");
}
close() {
this.#client.close();
}
async reconnect() {
try {
if (!this.closed) {
// Abort in-flight ops and free resources
this.#client.close();
}
}
finally {
// Recreate the underlying hrana client
this.#client = hrana.openHttp(this.#url, this.#authToken, this.#customFetch, this.#remoteEncryptionKey);
this.#client.intMode = this.#intMode;
}
}
get closed() {
return this.#client.closed;
}
}
export class HttpTransaction extends HranaTransaction {
#stream;
#sqlCache;
/** @private */
constructor(stream, mode, version) {
super(mode, version);
this.#stream = stream;
this.#sqlCache = new SqlCache(stream, sqlCacheCapacity);
}
/** @private */
_getStream() {
return this.#stream;
}
/** @private */
_getSqlCache() {
return this.#sqlCache;
}
close() {
this.#stream.close();
}
get closed() {
return this.#stream.closed;
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { Config, Client } from "@libsql/core/api";
export * from "@libsql/core/api";
/** Creates a {@link Client} object.
*
* You must pass at least an `url` in the {@link Config} object.
*/
export declare function createClient(config: Config): Client;
+23
View File
@@ -0,0 +1,23 @@
import { expandConfig } from "@libsql/core/config";
import { _createClient as _createSqlite3Client } from "./sqlite3.js";
import { _createClient as _createWsClient } from "./ws.js";
import { _createClient as _createHttpClient } from "./http.js";
export * from "@libsql/core/api";
/** Creates a {@link Client} object.
*
* You must pass at least an `url` in the {@link Config} object.
*/
export function createClient(config) {
return _createClient(expandConfig(config, true));
}
function _createClient(config) {
if (config.scheme === "wss" || config.scheme === "ws") {
return _createWsClient(config);
}
else if (config.scheme === "https" || config.scheme === "http") {
return _createHttpClient(config);
}
else {
return _createSqlite3Client(config);
}
}
@@ -0,0 +1,7 @@
import type * as hrana from "@libsql/hrana-client";
export declare class SqlCache {
#private;
capacity: number;
constructor(owner: hrana.SqlOwner, capacity: number);
apply(hranaStmts: Array<hrana.Stmt>): void;
}
+87
View File
@@ -0,0 +1,87 @@
export class SqlCache {
#owner;
#sqls;
capacity;
constructor(owner, capacity) {
this.#owner = owner;
this.#sqls = new Lru();
this.capacity = capacity;
}
// Replaces SQL strings with cached `hrana.Sql` objects in the statements in `hranaStmts`. After this
// function returns, we guarantee that all `hranaStmts` refer to valid (not closed) `hrana.Sql` objects,
// but _we may invalidate any other `hrana.Sql` objects_ (by closing them, thus removing them from the
// server).
//
// In practice, this means that after calling this function, you can use the statements only up to the
// first `await`, because concurrent code may also use the cache and invalidate those statements.
apply(hranaStmts) {
if (this.capacity <= 0) {
return;
}
const usedSqlObjs = new Set();
for (const hranaStmt of hranaStmts) {
if (typeof hranaStmt.sql !== "string") {
continue;
}
const sqlText = hranaStmt.sql;
// Stored SQL cannot exceed 5kb.
// https://github.com/tursodatabase/libsql/blob/e9d637e051685f92b0da43849507b5ef4232fbeb/libsql-server/src/hrana/http/request.rs#L10
if (sqlText.length >= 5000) {
continue;
}
let sqlObj = this.#sqls.get(sqlText);
if (sqlObj === undefined) {
while (this.#sqls.size + 1 > this.capacity) {
const [evictSqlText, evictSqlObj] = this.#sqls.peekLru();
if (usedSqlObjs.has(evictSqlObj)) {
// The SQL object that we are trying to evict is already in use in this batch, so we
// must not evict and close it.
break;
}
evictSqlObj.close();
this.#sqls.delete(evictSqlText);
}
if (this.#sqls.size + 1 <= this.capacity) {
sqlObj = this.#owner.storeSql(sqlText);
this.#sqls.set(sqlText, sqlObj);
}
}
if (sqlObj !== undefined) {
hranaStmt.sql = sqlObj;
usedSqlObjs.add(sqlObj);
}
}
}
}
class Lru {
// This maps keys to the cache values. The entries are ordered by their last use (entires that were used
// most recently are at the end).
#cache;
constructor() {
this.#cache = new Map();
}
get(key) {
const value = this.#cache.get(key);
if (value !== undefined) {
// move the entry to the back of the Map
this.#cache.delete(key);
this.#cache.set(key, value);
}
return value;
}
set(key, value) {
this.#cache.set(key, value);
}
peekLru() {
for (const entry of this.#cache.entries()) {
return entry;
}
return undefined;
}
delete(key) {
this.#cache.delete(key);
}
get size() {
return this.#cache.size;
}
}
+35
View File
@@ -0,0 +1,35 @@
import Database from "libsql";
import type { Config, IntMode, Client, Transaction, TransactionMode, ResultSet, InStatement, InArgs, Replicated } from "@libsql/core/api";
import type { ExpandedConfig } from "@libsql/core/config";
export * from "@libsql/core/api";
export declare function createClient(config: Config): Client;
/** @private */
export declare function _createClient(config: ExpandedConfig): Client;
export declare class Sqlite3Client implements Client {
#private;
closed: boolean;
protocol: "file";
/** @private */
constructor(path: string, options: Database.Options, db: Database.Database, intMode: IntMode);
execute(stmtOrSql: InStatement | string, args?: InArgs): Promise<ResultSet>;
batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;
migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
transaction(mode?: TransactionMode): Promise<Transaction>;
executeMultiple(sql: string): Promise<void>;
sync(): Promise<Replicated>;
reconnect(): Promise<void>;
close(): void;
}
export declare class Sqlite3Transaction implements Transaction {
#private;
/** @private */
constructor(database: Database.Database, intMode: IntMode);
execute(stmt: InStatement): Promise<ResultSet>;
execute(sql: string, args?: InArgs): Promise<ResultSet>;
batch(stmts: Array<InStatement | [string, InArgs?]>): Promise<Array<ResultSet>>;
executeMultiple(sql: string): Promise<void>;
rollback(): Promise<void>;
commit(): Promise<void>;
close(): void;
get closed(): boolean;
}
+476
View File
@@ -0,0 +1,476 @@
import Database from "libsql";
import { Buffer } from "node:buffer";
import { LibsqlError, LibsqlBatchError } from "@libsql/core/api";
import { expandConfig, isInMemoryConfig } from "@libsql/core/config";
import { supportedUrlLink, transactionModeToBegin, ResultSetImpl, } from "@libsql/core/util";
export * from "@libsql/core/api";
export function createClient(config) {
return _createClient(expandConfig(config, true));
}
/** @private */
export function _createClient(config) {
if (config.scheme !== "file") {
throw new LibsqlError(`URL scheme ${JSON.stringify(config.scheme + ":")} is not supported by the local sqlite3 client. ` +
`For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
const authority = config.authority;
if (authority !== undefined) {
const host = authority.host.toLowerCase();
if (host !== "" && host !== "localhost") {
throw new LibsqlError(`Invalid host in file URL: ${JSON.stringify(authority.host)}. ` +
'A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") ' +
'or with three slashes ("file:///absolute/path.db"). ' +
`For more information, please read ${supportedUrlLink}`, "URL_INVALID");
}
if (authority.port !== undefined) {
throw new LibsqlError("File URL cannot have a port", "URL_INVALID");
}
if (authority.userinfo !== undefined) {
throw new LibsqlError("File URL cannot have username and password", "URL_INVALID");
}
}
let isInMemory = isInMemoryConfig(config);
if (isInMemory && config.syncUrl) {
throw new LibsqlError(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${config.path}`, "URL_INVALID");
}
let path = config.path;
if (isInMemory) {
// note: we should prepend file scheme in order for SQLite3 to recognize :memory: connection query parameters
path = `${config.scheme}:${config.path}`;
}
const options = {
authToken: config.authToken,
encryptionKey: config.encryptionKey,
remoteEncryptionKey: config.remoteEncryptionKey,
syncUrl: config.syncUrl,
syncPeriod: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
};
const db = new Database(path, options);
executeStmt(db, "SELECT 1 AS checkThatTheDatabaseCanBeOpened", config.intMode);
return new Sqlite3Client(path, options, db, config.intMode);
}
export class Sqlite3Client {
#path;
#options;
#db;
#intMode;
closed;
protocol;
/** @private */
constructor(path, options, db, intMode) {
this.#path = path;
this.#options = options;
this.#db = db;
this.#intMode = intMode;
this.closed = false;
this.protocol = "file";
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
this.#checkNotClosed();
return executeStmt(this.#getDb(), stmt, this.#intMode);
}
async batch(stmts, mode = "deferred") {
this.#checkNotClosed();
const db = this.#getDb();
try {
executeStmt(db, transactionModeToBegin(mode), this.#intMode);
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
if (!db.inTransaction) {
throw new LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
const stmt = stmts[i];
const normalizedStmt = Array.isArray(stmt)
? { sql: stmt[0], args: stmt[1] || [] }
: stmt;
resultSets.push(executeStmt(db, normalizedStmt, this.#intMode));
}
catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
if (e instanceof LibsqlError) {
throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
executeStmt(db, "COMMIT", this.#intMode);
return resultSets;
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
}
}
async migrate(stmts) {
this.#checkNotClosed();
const db = this.#getDb();
try {
executeStmt(db, "PRAGMA foreign_keys=off", this.#intMode);
executeStmt(db, transactionModeToBegin("deferred"), this.#intMode);
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
if (!db.inTransaction) {
throw new LibsqlBatchError("The transaction has been rolled back", i, "TRANSACTION_CLOSED");
}
resultSets.push(executeStmt(db, stmts[i], this.#intMode));
}
catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
if (e instanceof LibsqlError) {
throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
executeStmt(db, "COMMIT", this.#intMode);
return resultSets;
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
executeStmt(db, "PRAGMA foreign_keys=on", this.#intMode);
}
}
async transaction(mode = "write") {
const db = this.#getDb();
executeStmt(db, transactionModeToBegin(mode), this.#intMode);
this.#db = null; // A new connection will be lazily created on next use
return new Sqlite3Transaction(db, this.#intMode);
}
async executeMultiple(sql) {
this.#checkNotClosed();
const db = this.#getDb();
try {
return executeMultiple(db, sql);
}
finally {
if (db.inTransaction) {
executeStmt(db, "ROLLBACK", this.#intMode);
}
}
}
async sync() {
this.#checkNotClosed();
const rep = await this.#getDb().sync();
return {
frames_synced: rep.frames_synced,
frame_no: rep.frame_no,
};
}
async reconnect() {
try {
if (!this.closed && this.#db !== null) {
this.#db.close();
}
}
finally {
this.#db = new Database(this.#path, this.#options);
this.closed = false;
}
}
close() {
this.closed = true;
if (this.#db !== null) {
this.#db.close();
this.#db = null;
}
}
#checkNotClosed() {
if (this.closed) {
throw new LibsqlError("The client is closed", "CLIENT_CLOSED");
}
}
// Lazily creates the database connection and returns it
#getDb() {
if (this.#db === null) {
this.#db = new Database(this.#path, this.#options);
}
return this.#db;
}
}
export class Sqlite3Transaction {
#database;
#intMode;
/** @private */
constructor(database, intMode) {
this.#database = database;
this.#intMode = intMode;
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
this.#checkNotClosed();
return executeStmt(this.#database, stmt, this.#intMode);
}
async batch(stmts) {
const resultSets = [];
for (let i = 0; i < stmts.length; i++) {
try {
this.#checkNotClosed();
const stmt = stmts[i];
const normalizedStmt = Array.isArray(stmt)
? { sql: stmt[0], args: stmt[1] || [] }
: stmt;
resultSets.push(executeStmt(this.#database, normalizedStmt, this.#intMode));
}
catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
if (e instanceof LibsqlError) {
throw new LibsqlBatchError(e.message, i, e.code, e.extendedCode, e.rawCode, e.cause instanceof Error ? e.cause : undefined);
}
throw e;
}
}
return resultSets;
}
async executeMultiple(sql) {
this.#checkNotClosed();
return executeMultiple(this.#database, sql);
}
async rollback() {
if (!this.#database.open) {
return;
}
this.#checkNotClosed();
executeStmt(this.#database, "ROLLBACK", this.#intMode);
}
async commit() {
this.#checkNotClosed();
executeStmt(this.#database, "COMMIT", this.#intMode);
}
close() {
if (this.#database.inTransaction) {
executeStmt(this.#database, "ROLLBACK", this.#intMode);
}
}
get closed() {
return !this.#database.inTransaction;
}
#checkNotClosed() {
if (this.closed) {
throw new LibsqlError("The transaction is closed", "TRANSACTION_CLOSED");
}
}
}
function executeStmt(db, stmt, intMode) {
let sql;
let args;
if (typeof stmt === "string") {
sql = stmt;
args = [];
}
else {
sql = stmt.sql;
if (Array.isArray(stmt.args)) {
args = stmt.args.map((value) => valueToSql(value, intMode));
}
else {
args = {};
for (const name in stmt.args) {
const argName = name[0] === "@" || name[0] === "$" || name[0] === ":"
? name.substring(1)
: name;
args[argName] = valueToSql(stmt.args[name], intMode);
}
}
}
try {
const sqlStmt = db.prepare(sql);
sqlStmt.safeIntegers(true);
let returnsData = true;
try {
sqlStmt.raw(true);
}
catch {
// raw() throws an exception if the statement does not return data
returnsData = false;
}
if (returnsData) {
const columns = Array.from(sqlStmt.columns().map((col) => col.name));
const columnTypes = Array.from(sqlStmt.columns().map((col) => col.type ?? ""));
const rows = sqlStmt.all(args).map((sqlRow) => {
return rowFromSql(sqlRow, columns, intMode);
});
// TODO: can we get this info from better-sqlite3?
const rowsAffected = 0;
const lastInsertRowid = undefined;
return new ResultSetImpl(columns, columnTypes, rows, rowsAffected, lastInsertRowid);
}
else {
const info = sqlStmt.run(args);
const rowsAffected = info.changes;
const lastInsertRowid = BigInt(info.lastInsertRowid);
return new ResultSetImpl([], [], [], rowsAffected, lastInsertRowid);
}
}
catch (e) {
throw mapSqliteError(e);
}
}
function rowFromSql(sqlRow, columns, intMode) {
const row = {};
// make sure that the "length" property is not enumerable
Object.defineProperty(row, "length", { value: sqlRow.length });
for (let i = 0; i < sqlRow.length; ++i) {
const value = valueFromSql(sqlRow[i], intMode);
Object.defineProperty(row, i, { value });
const column = columns[i];
if (!Object.hasOwn(row, column)) {
Object.defineProperty(row, column, {
value,
enumerable: true,
configurable: true,
writable: true,
});
}
}
return row;
}
function valueFromSql(sqlValue, intMode) {
if (typeof sqlValue === "bigint") {
if (intMode === "number") {
if (sqlValue < minSafeBigint || sqlValue > maxSafeBigint) {
throw new RangeError("Received integer which cannot be safely represented as a JavaScript number");
}
return Number(sqlValue);
}
else if (intMode === "bigint") {
return sqlValue;
}
else if (intMode === "string") {
return "" + sqlValue;
}
else {
throw new Error("Invalid value for IntMode");
}
}
else if (sqlValue instanceof Buffer) {
return sqlValue.buffer;
}
return sqlValue;
}
const minSafeBigint = -9007199254740991n;
const maxSafeBigint = 9007199254740991n;
function valueToSql(value, intMode) {
if (typeof value === "number") {
if (!Number.isFinite(value)) {
throw new RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");
}
return value;
}
else if (typeof value === "bigint") {
if (value < minInteger || value > maxInteger) {
throw new RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");
}
return value;
}
else if (typeof value === "boolean") {
switch (intMode) {
case "bigint":
return value ? 1n : 0n;
case "string":
return value ? "1" : "0";
default:
return value ? 1 : 0;
}
}
else if (value instanceof ArrayBuffer) {
return Buffer.from(value);
}
else if (value instanceof Date) {
return value.valueOf();
}
else if (value === undefined) {
throw new TypeError("undefined cannot be passed as argument to the database");
}
else {
return value;
}
}
const minInteger = -9223372036854775808n;
const maxInteger = 9223372036854775807n;
function executeMultiple(db, sql) {
try {
db.exec(sql);
}
catch (e) {
throw mapSqliteError(e);
}
}
function mapSqliteError(e) {
if (e instanceof Database.SqliteError) {
const extendedCode = e.code;
const code = mapToBaseCode(e.rawCode);
return new LibsqlError(e.message, code, extendedCode, e.rawCode, e);
}
return e;
}
// Map SQLite raw error code to base error code string.
// Extended error codes are (base | (extended << 8)), so base = rawCode & 0xFF
function mapToBaseCode(rawCode) {
if (rawCode === undefined) {
return "SQLITE_UNKNOWN";
}
const baseCode = rawCode & 0xff;
return (sqliteErrorCodes[baseCode] ?? `SQLITE_UNKNOWN_${baseCode.toString()}`);
}
const sqliteErrorCodes = {
1: "SQLITE_ERROR",
2: "SQLITE_INTERNAL",
3: "SQLITE_PERM",
4: "SQLITE_ABORT",
5: "SQLITE_BUSY",
6: "SQLITE_LOCKED",
7: "SQLITE_NOMEM",
8: "SQLITE_READONLY",
9: "SQLITE_INTERRUPT",
10: "SQLITE_IOERR",
11: "SQLITE_CORRUPT",
12: "SQLITE_NOTFOUND",
13: "SQLITE_FULL",
14: "SQLITE_CANTOPEN",
15: "SQLITE_PROTOCOL",
16: "SQLITE_EMPTY",
17: "SQLITE_SCHEMA",
18: "SQLITE_TOOBIG",
19: "SQLITE_CONSTRAINT",
20: "SQLITE_MISMATCH",
21: "SQLITE_MISUSE",
22: "SQLITE_NOLFS",
23: "SQLITE_AUTH",
24: "SQLITE_FORMAT",
25: "SQLITE_RANGE",
26: "SQLITE_NOTADB",
27: "SQLITE_NOTICE",
28: "SQLITE_WARNING",
};
+6
View File
@@ -0,0 +1,6 @@
import type { Config, Client } from "@libsql/core/api";
import type { ExpandedConfig } from "@libsql/core/config";
export * from "@libsql/core/api";
export declare function createClient(config: Config): Client;
/** @private */
export declare function _createClient(config: ExpandedConfig): Client;
+22
View File
@@ -0,0 +1,22 @@
import { LibsqlError } from "@libsql/core/api";
import { expandConfig } from "@libsql/core/config";
import { supportedUrlLink } from "@libsql/core/util";
import { _createClient as _createWsClient } from "./ws.js";
import { _createClient as _createHttpClient } from "./http.js";
export * from "@libsql/core/api";
export function createClient(config) {
return _createClient(expandConfig(config, true));
}
/** @private */
export function _createClient(config) {
if (config.scheme === "ws" || config.scheme === "wss") {
return _createWsClient(config);
}
else if (config.scheme === "http" || config.scheme === "https") {
return _createHttpClient(config);
}
else {
throw new LibsqlError('The client that uses Web standard APIs supports only "libsql:", "wss:", "ws:", "https:" and "http:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
}
+49
View File
@@ -0,0 +1,49 @@
import * as hrana from "@libsql/hrana-client";
import type { Config, IntMode, Client, Transaction, ResultSet, InStatement, InArgs, Replicated } from "@libsql/core/api";
import { TransactionMode } from "@libsql/core/api";
import type { ExpandedConfig } from "@libsql/core/config";
import { HranaTransaction } from "./hrana.js";
import { SqlCache } from "./sql_cache.js";
export * from "@libsql/core/api";
export declare function createClient(config: Config): WsClient;
/** @private */
export declare function _createClient(config: ExpandedConfig): WsClient;
interface ConnState {
client: hrana.WsClient;
useSqlCache: boolean | undefined;
sqlCache: SqlCache;
openTime: Date;
streamStates: Set<StreamState>;
}
interface StreamState {
conn: ConnState;
stream: hrana.WsStream;
}
export declare class WsClient implements Client {
#private;
closed: boolean;
protocol: "ws";
/** @private */
constructor(client: hrana.WsClient, url: URL, authToken: string | undefined, intMode: IntMode, concurrency: number | undefined);
private limit;
execute(stmtOrSql: InStatement | string, args?: InArgs): Promise<ResultSet>;
batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;
migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
transaction(mode?: TransactionMode): Promise<WsTransaction>;
executeMultiple(sql: string): Promise<void>;
sync(): Promise<Replicated>;
reconnect(): Promise<void>;
_closeStream(streamState: StreamState): void;
close(): void;
}
export declare class WsTransaction extends HranaTransaction implements Transaction {
#private;
/** @private */
constructor(client: WsClient, state: StreamState, mode: TransactionMode, version: hrana.ProtocolVersion);
/** @private */
_getStream(): hrana.Stream;
/** @private */
_getSqlCache(): SqlCache;
close(): void;
get closed(): boolean;
}
+359
View File
@@ -0,0 +1,359 @@
import * as hrana from "@libsql/hrana-client";
import { LibsqlError } from "@libsql/core/api";
import { expandConfig } from "@libsql/core/config";
import { HranaTransaction, executeHranaBatch, stmtToHrana, resultSetFromHrana, mapHranaError, } from "./hrana.js";
import { SqlCache } from "./sql_cache.js";
import { encodeBaseUrl } from "@libsql/core/uri";
import { supportedUrlLink } from "@libsql/core/util";
import promiseLimit from "promise-limit";
export * from "@libsql/core/api";
export function createClient(config) {
return _createClient(expandConfig(config, false));
}
/** @private */
export function _createClient(config) {
if (config.scheme !== "wss" && config.scheme !== "ws") {
throw new LibsqlError('The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, ' +
`got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (config.encryptionKey !== undefined) {
throw new LibsqlError("Encryption key is not supported by the remote client.", "ENCRYPTION_KEY_NOT_SUPPORTED");
}
if (config.scheme === "ws" && config.tls) {
throw new LibsqlError(`A "ws:" URL cannot opt into TLS by using ?tls=1`, "URL_INVALID");
}
else if (config.scheme === "wss" && !config.tls) {
throw new LibsqlError(`A "wss:" URL cannot opt out of TLS by using ?tls=0`, "URL_INVALID");
}
const url = encodeBaseUrl(config.scheme, config.authority, config.path);
let client;
try {
client = hrana.openWs(url, config.authToken);
}
catch (e) {
if (e instanceof hrana.WebSocketUnsupportedError) {
const suggestedScheme = config.scheme === "wss" ? "https" : "http";
const suggestedUrl = encodeBaseUrl(suggestedScheme, config.authority, config.path);
throw new LibsqlError("This environment does not support WebSockets, please switch to the HTTP client by using " +
`a "${suggestedScheme}:" URL (${JSON.stringify(suggestedUrl)}). ` +
`For more information, please read ${supportedUrlLink}`, "WEBSOCKETS_NOT_SUPPORTED");
}
throw mapHranaError(e);
}
return new WsClient(client, url, config.authToken, config.intMode, config.concurrency);
}
const maxConnAgeMillis = 60 * 1000;
const sqlCacheCapacity = 100;
export class WsClient {
#url;
#authToken;
#intMode;
// State of the current connection. The `hrana.WsClient` inside may be closed at any moment due to an
// asynchronous error.
#connState;
// If defined, this is a connection that will be used in the future, once it is ready.
#futureConnState;
closed;
protocol;
#isSchemaDatabase;
#promiseLimitFunction;
/** @private */
constructor(client, url, authToken, intMode, concurrency) {
this.#url = url;
this.#authToken = authToken;
this.#intMode = intMode;
this.#connState = this.#openConn(client);
this.#futureConnState = undefined;
this.closed = false;
this.protocol = "ws";
this.#promiseLimitFunction = promiseLimit(concurrency);
}
async limit(fn) {
return this.#promiseLimitFunction(fn);
}
async execute(stmtOrSql, args) {
let stmt;
if (typeof stmtOrSql === "string") {
stmt = {
sql: stmtOrSql,
args: args || [],
};
}
else {
stmt = stmtOrSql;
}
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const hranaStmt = stmtToHrana(stmt);
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
streamState.conn.sqlCache.apply([hranaStmt]);
const hranaRowsPromise = streamState.stream.query(hranaStmt);
streamState.stream.closeGracefully();
const hranaRowsResult = await hranaRowsPromise;
return resultSetFromHrana(hranaRowsResult);
}
catch (e) {
throw mapHranaError(e);
}
finally {
this._closeStream(streamState);
}
});
}
async batch(stmts, mode = "deferred") {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const normalizedStmts = stmts.map((stmt) => {
if (Array.isArray(stmt)) {
return {
sql: stmt[0],
args: stmt[1] || [],
};
}
return stmt;
});
const hranaStmts = normalizedStmts.map(stmtToHrana);
const version = await streamState.conn.client.getVersion();
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
streamState.conn.sqlCache.apply(hranaStmts);
const batch = streamState.stream.batch(version >= 3);
const resultsPromise = executeHranaBatch(mode, version, batch, hranaStmts);
const results = await resultsPromise;
return results;
}
catch (e) {
throw mapHranaError(e);
}
finally {
this._closeStream(streamState);
}
});
}
async migrate(stmts) {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const hranaStmts = stmts.map(stmtToHrana);
const version = await streamState.conn.client.getVersion();
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
const batch = streamState.stream.batch(version >= 3);
const resultsPromise = executeHranaBatch("deferred", version, batch, hranaStmts, true);
const results = await resultsPromise;
return results;
}
catch (e) {
throw mapHranaError(e);
}
finally {
this._closeStream(streamState);
}
});
}
async transaction(mode = "write") {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
const version = await streamState.conn.client.getVersion();
// the BEGIN statement will be batched with the first statement on the transaction to save a
// network roundtrip
return new WsTransaction(this, streamState, mode, version);
}
catch (e) {
this._closeStream(streamState);
throw mapHranaError(e);
}
});
}
async executeMultiple(sql) {
return this.limit(async () => {
const streamState = await this.#openStream();
try {
// Schedule all operations synchronously, so they will be pipelined and executed in a single
// network roundtrip.
const promise = streamState.stream.sequence(sql);
streamState.stream.closeGracefully();
await promise;
}
catch (e) {
throw mapHranaError(e);
}
finally {
this._closeStream(streamState);
}
});
}
sync() {
throw new LibsqlError("sync not supported in ws mode", "SYNC_NOT_SUPPORTED");
}
async #openStream() {
if (this.closed) {
throw new LibsqlError("The client is closed", "CLIENT_CLOSED");
}
const now = new Date();
const ageMillis = now.valueOf() - this.#connState.openTime.valueOf();
if (ageMillis > maxConnAgeMillis &&
this.#futureConnState === undefined) {
// The existing connection is too old, let's open a new one.
const futureConnState = this.#openConn();
this.#futureConnState = futureConnState;
// However, if we used `futureConnState` immediately, we would introduce additional latency,
// because we would have to wait for the WebSocket handshake to complete, even though we may a
// have perfectly good existing connection in `this.#connState`!
//
// So we wait until the `hrana.Client.getVersion()` operation completes (which happens when the
// WebSocket hanshake completes), and only then we replace `this.#connState` with
// `futureConnState`, which is stored in `this.#futureConnState` in the meantime.
futureConnState.client.getVersion().then((_version) => {
if (this.#connState !== futureConnState) {
// We need to close `this.#connState` before we replace it. However, it is possible
// that `this.#connState` has already been replaced: see the code below.
if (this.#connState.streamStates.size === 0) {
this.#connState.client.close();
}
else {
// If there are existing streams on the connection, we must not close it, because
// these streams would be broken. The last stream to be closed will also close the
// connection in `_closeStream()`.
}
}
this.#connState = futureConnState;
this.#futureConnState = undefined;
}, (_e) => {
// If the new connection could not be established, let's just ignore the error and keep
// using the existing connection.
this.#futureConnState = undefined;
});
}
if (this.#connState.client.closed) {
// An error happened on this connection and it has been closed. Let's try to seamlessly reconnect.
try {
if (this.#futureConnState !== undefined) {
// We are already in the process of opening a new connection, so let's just use it
// immediately.
this.#connState = this.#futureConnState;
}
else {
this.#connState = this.#openConn();
}
}
catch (e) {
throw mapHranaError(e);
}
}
const connState = this.#connState;
try {
// Now we wait for the WebSocket handshake to complete (if it hasn't completed yet). Note that
// this does not increase latency, because any messages that we would send on the WebSocket before
// the handshake would be queued until the handshake is completed anyway.
if (connState.useSqlCache === undefined) {
connState.useSqlCache =
(await connState.client.getVersion()) >= 2;
if (connState.useSqlCache) {
connState.sqlCache.capacity = sqlCacheCapacity;
}
}
const stream = connState.client.openStream();
stream.intMode = this.#intMode;
const streamState = { conn: connState, stream };
connState.streamStates.add(streamState);
return streamState;
}
catch (e) {
throw mapHranaError(e);
}
}
#openConn(client) {
try {
client ??= hrana.openWs(this.#url, this.#authToken);
return {
client,
useSqlCache: undefined,
sqlCache: new SqlCache(client, 0),
openTime: new Date(),
streamStates: new Set(),
};
}
catch (e) {
throw mapHranaError(e);
}
}
async reconnect() {
try {
for (const st of Array.from(this.#connState.streamStates)) {
try {
st.stream.close();
}
catch { }
}
this.#connState.client.close();
}
catch { }
if (this.#futureConnState) {
try {
this.#futureConnState.client.close();
}
catch { }
this.#futureConnState = undefined;
}
const next = this.#openConn();
const version = await next.client.getVersion();
next.useSqlCache = version >= 2;
if (next.useSqlCache) {
next.sqlCache.capacity = sqlCacheCapacity;
}
this.#connState = next;
this.closed = false;
}
_closeStream(streamState) {
streamState.stream.close();
const connState = streamState.conn;
connState.streamStates.delete(streamState);
if (connState.streamStates.size === 0 &&
connState !== this.#connState) {
// We are not using this connection anymore and this is the last stream that was using it, so we
// must close it now.
connState.client.close();
}
}
close() {
this.#connState.client.close();
this.closed = true;
if (this.#futureConnState) {
try {
this.#futureConnState.client.close();
}
catch { }
this.#futureConnState = undefined;
}
this.closed = true;
}
}
export class WsTransaction extends HranaTransaction {
#client;
#streamState;
/** @private */
constructor(client, state, mode, version) {
super(mode, version);
this.#client = client;
this.#streamState = state;
}
/** @private */
_getStream() {
return this.#streamState.stream;
}
/** @private */
_getSqlCache() {
return this.#streamState.conn.sqlCache;
}
close() {
this.#client._closeStream(this.#streamState);
}
get closed() {
return this.#streamState.stream.closed;
}
}
+123
View File
@@ -0,0 +1,123 @@
{
"name": "@libsql/client",
"version": "0.17.0",
"keywords": [
"libsql",
"database",
"sqlite",
"serverless",
"vercel",
"netlify",
"lambda"
],
"description": "libSQL driver for TypeScript and JavaScript",
"repository": {
"type": "git",
"url": "git+https://github.com/tursodatabase/libsql-client-ts",
"directory": "packages/libsql-client"
},
"authors": [
"Jan Špaček <[email protected]>",
"Pekka Enberg <[email protected]>",
"Jan Plhak <[email protected]>"
],
"license": "MIT",
"type": "module",
"main": "lib-cjs/node.js",
"types": "lib-esm/node.d.ts",
"exports": {
".": {
"types": "./lib-esm/node.d.ts",
"import": {
"workerd": "./lib-esm/web.js",
"deno": "./lib-esm/node.js",
"edge-light": "./lib-esm/web.js",
"netlify": "./lib-esm/web.js",
"node": "./lib-esm/node.js",
"browser": "./lib-esm/web.js",
"default": "./lib-esm/node.js"
},
"require": "./lib-cjs/node.js"
},
"./node": {
"types": "./lib-esm/node.d.ts",
"import": "./lib-esm/node.js",
"require": "./lib-cjs/node.js"
},
"./http": {
"types": "./lib-esm/http.d.ts",
"import": "./lib-esm/http.js",
"require": "./lib-cjs/http.js"
},
"./ws": {
"types": "./lib-esm/ws.d.ts",
"import": "./lib-esm/ws.js",
"require": "./lib-cjs/ws.js"
},
"./sqlite3": {
"types": "./lib-esm/sqlite3.d.ts",
"import": "./lib-esm/sqlite3.js",
"require": "./lib-cjs/sqlite3.js"
},
"./web": {
"types": "./lib-esm/web.d.ts",
"import": "./lib-esm/web.js",
"require": "./lib-cjs/web.js"
}
},
"typesVersions": {
"*": {
".": [
"./lib-esm/node.d.ts"
],
"http": [
"./lib-esm/http.d.ts"
],
"hrana": [
"./lib-esm/hrana.d.ts"
],
"sqlite3": [
"./lib-esm/sqlite3.d.ts"
],
"web": [
"./lib-esm/web.d.ts"
]
}
},
"files": [
"lib-cjs/**",
"lib-esm/**",
"README.md"
],
"scripts": {
"prepublishOnly": "npm run build",
"prebuild": "rm -rf ./lib-cjs ./lib-esm",
"build": "npm run build:cjs && npm run build:esm",
"build:cjs": "tsc -p tsconfig.build-cjs.json",
"build:esm": "tsc -p tsconfig.build-esm.json",
"format:check": "prettier --check .",
"postbuild": "cp package-cjs.json ./lib-cjs/package.json",
"test": "jest --runInBand",
"typecheck": "tsc --noEmit",
"typedoc": "rm -rf ./docs && typedoc",
"lint-staged": "lint-staged"
},
"dependencies": {
"@libsql/core": "^0.17.0",
"@libsql/hrana-client": "^0.9.0",
"js-base64": "^3.7.5",
"libsql": "^0.5.22",
"promise-limit": "^2.7.0"
},
"devDependencies": {
"@types/jest": "^29.2.5",
"@types/node": "^18.15.5",
"jest": "^29.3.1",
"lint-staged": "^15.2.2",
"msw": "^2.3.0",
"prettier": "3.2.5",
"ts-jest": "^29.0.5",
"typedoc": "^0.23.28",
"typescript": "^4.9.4"
}
}
+34
View File
@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LibsqlBatchError = exports.LibsqlError = void 0;
/** Error thrown by the client. */
class LibsqlError extends Error {
/** Machine-readable error code. */
code;
/** Extended error code with more specific information (e.g., SQLITE_CONSTRAINT_PRIMARYKEY). */
extendedCode;
/** Raw numeric error code */
rawCode;
constructor(message, code, extendedCode, rawCode, cause) {
if (code !== undefined) {
message = `${code}: ${message}`;
}
super(message, { cause });
this.code = code;
this.extendedCode = extendedCode;
this.rawCode = rawCode;
this.name = "LibsqlError";
}
}
exports.LibsqlError = LibsqlError;
/** Error thrown by the client during batch operations. */
class LibsqlBatchError extends LibsqlError {
/** The zero-based index of the statement that failed in the batch. */
statementIndex;
constructor(message, statementIndex, code, extendedCode, rawCode, cause) {
super(message, code, extendedCode, rawCode, cause);
this.statementIndex = statementIndex;
this.name = "LibsqlBatchError";
}
}
exports.LibsqlBatchError = LibsqlBatchError;
+143
View File
@@ -0,0 +1,143 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.expandConfig = exports.isInMemoryConfig = void 0;
const api_js_1 = require("./api.js");
const uri_js_1 = require("./uri.js");
const util_js_1 = require("./util.js");
const inMemoryMode = ":memory:";
function isInMemoryConfig(config) {
return (config.scheme === "file" &&
(config.path === ":memory:" || config.path.startsWith(":memory:?")));
}
exports.isInMemoryConfig = isInMemoryConfig;
function expandConfig(config, preferHttp) {
if (typeof config !== "object") {
// produce a reasonable error message in the common case where users type
// `createClient("libsql://...")` instead of `createClient({url: "libsql://..."})`
throw new TypeError(`Expected client configuration as object, got ${typeof config}`);
}
let { url, authToken, tls, intMode, concurrency } = config;
// fill simple defaults right here
concurrency = Math.max(0, concurrency || 20);
intMode ??= "number";
let connectionQueryParams = []; // recognized query parameters which we sanitize through white list of valid key-value pairs
// convert plain :memory: url to URI format to make logic more uniform
if (url === inMemoryMode) {
url = "file::memory:";
}
// parse url parameters first and override config with update values
const uri = (0, uri_js_1.parseUri)(url);
const originalUriScheme = uri.scheme.toLowerCase();
const isInMemoryMode = originalUriScheme === "file" &&
uri.path === inMemoryMode &&
uri.authority === undefined;
let queryParamsDef;
if (isInMemoryMode) {
queryParamsDef = {
cache: {
values: ["shared", "private"],
update: (key, value) => connectionQueryParams.push(`${key}=${value}`),
},
};
}
else {
queryParamsDef = {
tls: {
values: ["0", "1"],
update: (_, value) => (tls = value === "1"),
},
authToken: {
update: (_, value) => (authToken = value),
},
};
}
for (const { key, value } of uri.query?.pairs ?? []) {
if (!Object.hasOwn(queryParamsDef, key)) {
throw new api_js_1.LibsqlError(`Unsupported URL query parameter ${JSON.stringify(key)}`, "URL_PARAM_NOT_SUPPORTED");
}
const queryParamDef = queryParamsDef[key];
if (queryParamDef.values !== undefined &&
!queryParamDef.values.includes(value)) {
throw new api_js_1.LibsqlError(`Unknown value for the "${key}" query argument: ${JSON.stringify(value)}. Supported values are: [${queryParamDef.values.map((x) => '"' + x + '"').join(", ")}]`, "URL_INVALID");
}
if (queryParamDef.update !== undefined) {
queryParamDef?.update(key, value);
}
}
// fill complex defaults & validate config
const connectionQueryParamsString = connectionQueryParams.length === 0
? ""
: `?${connectionQueryParams.join("&")}`;
const path = uri.path + connectionQueryParamsString;
let scheme;
if (originalUriScheme === "libsql") {
if (tls === false) {
if (uri.authority?.port === undefined) {
throw new api_js_1.LibsqlError('A "libsql:" URL with ?tls=0 must specify an explicit port', "URL_INVALID");
}
scheme = preferHttp ? "http" : "ws";
}
else {
scheme = preferHttp ? "https" : "wss";
}
}
else {
scheme = originalUriScheme;
}
if (scheme === "http" || scheme === "ws") {
tls ??= false;
}
else {
tls ??= true;
}
if (scheme !== "http" &&
scheme !== "ws" &&
scheme !== "https" &&
scheme !== "wss" &&
scheme !== "file") {
throw new api_js_1.LibsqlError('The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, ' +
`got ${JSON.stringify(uri.scheme + ":")}. ` +
`For more information, please read ${util_js_1.supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (intMode !== "number" && intMode !== "bigint" && intMode !== "string") {
throw new TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(intMode)}`);
}
if (uri.fragment !== undefined) {
throw new api_js_1.LibsqlError(`URL fragments are not supported: ${JSON.stringify("#" + uri.fragment)}`, "URL_INVALID");
}
if (isInMemoryMode) {
return {
scheme: "file",
tls: false,
path,
intMode,
concurrency,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
authToken: undefined,
encryptionKey: undefined,
remoteEncryptionKey: undefined,
authority: undefined,
};
}
return {
scheme,
tls,
authority: uri.authority,
path,
authToken,
intMode,
concurrency,
encryptionKey: config.encryptionKey,
remoteEncryptionKey: config.remoteEncryptionKey,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
};
}
exports.expandConfig = expandConfig;
+3
View File
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
+125
View File
@@ -0,0 +1,125 @@
"use strict";
// URI parser based on RFC 3986
// We can't use the standard `URL` object, because we want to support relative `file:` URLs like
// `file:relative/path/database.db`, which are not correct according to RFC 8089, which standardizes the
// `file` scheme.
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeBaseUrl = exports.parseUri = void 0;
const api_js_1 = require("./api.js");
function parseUri(text) {
const match = URI_RE.exec(text);
if (match === null) {
throw new api_js_1.LibsqlError(`The URL '${text}' is not in a valid format`, "URL_INVALID");
}
const groups = match.groups;
const scheme = groups["scheme"];
const authority = groups["authority"] !== undefined
? parseAuthority(groups["authority"])
: undefined;
const path = percentDecode(groups["path"]);
const query = groups["query"] !== undefined ? parseQuery(groups["query"]) : undefined;
const fragment = groups["fragment"] !== undefined
? percentDecode(groups["fragment"])
: undefined;
return { scheme, authority, path, query, fragment };
}
exports.parseUri = parseUri;
const URI_RE = (() => {
const SCHEME = "(?<scheme>[A-Za-z][A-Za-z.+-]*)";
const AUTHORITY = "(?<authority>[^/?#]*)";
const PATH = "(?<path>[^?#]*)";
const QUERY = "(?<query>[^#]*)";
const FRAGMENT = "(?<fragment>.*)";
return new RegExp(`^${SCHEME}:(//${AUTHORITY})?${PATH}(\\?${QUERY})?(#${FRAGMENT})?$`, "su");
})();
function parseAuthority(text) {
const match = AUTHORITY_RE.exec(text);
if (match === null) {
throw new api_js_1.LibsqlError("The authority part of the URL is not in a valid format", "URL_INVALID");
}
const groups = match.groups;
const host = percentDecode(groups["host_br"] ?? groups["host"]);
const port = groups["port"] ? parseInt(groups["port"], 10) : undefined;
const userinfo = groups["username"] !== undefined
? {
username: percentDecode(groups["username"]),
password: groups["password"] !== undefined
? percentDecode(groups["password"])
: undefined,
}
: undefined;
return { host, port, userinfo };
}
const AUTHORITY_RE = (() => {
return new RegExp(`^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$`, "su");
})();
// Query string is parsed as application/x-www-form-urlencoded according to the Web URL standard:
// https://url.spec.whatwg.org/#urlencoded-parsing
function parseQuery(text) {
const sequences = text.split("&");
const pairs = [];
for (const sequence of sequences) {
if (sequence === "") {
continue;
}
let key;
let value;
const splitIdx = sequence.indexOf("=");
if (splitIdx < 0) {
key = sequence;
value = "";
}
else {
key = sequence.substring(0, splitIdx);
value = sequence.substring(splitIdx + 1);
}
pairs.push({
key: percentDecode(key.replaceAll("+", " ")),
value: percentDecode(value.replaceAll("+", " ")),
});
}
return { pairs };
}
function percentDecode(text) {
try {
return decodeURIComponent(text);
}
catch (e) {
if (e instanceof URIError) {
throw new api_js_1.LibsqlError(`URL component has invalid percent encoding: ${e}`, "URL_INVALID", undefined, undefined, e);
}
throw e;
}
}
function encodeBaseUrl(scheme, authority, path) {
if (authority === undefined) {
throw new api_js_1.LibsqlError(`URL with scheme ${JSON.stringify(scheme + ":")} requires authority (the "//" part)`, "URL_INVALID");
}
const schemeText = `${scheme}:`;
const hostText = encodeHost(authority.host);
const portText = encodePort(authority.port);
const userinfoText = encodeUserinfo(authority.userinfo);
const authorityText = `//${userinfoText}${hostText}${portText}`;
let pathText = path.split("/").map(encodeURIComponent).join("/");
if (pathText !== "" && !pathText.startsWith("/")) {
pathText = "/" + pathText;
}
return new URL(`${schemeText}${authorityText}${pathText}`);
}
exports.encodeBaseUrl = encodeBaseUrl;
function encodeHost(host) {
return host.includes(":") ? `[${encodeURI(host)}]` : encodeURI(host);
}
function encodePort(port) {
return port !== undefined ? `:${port}` : "";
}
function encodeUserinfo(userinfo) {
if (userinfo === undefined) {
return "";
}
const usernameText = encodeURIComponent(userinfo.username);
const passwordText = userinfo.password !== undefined
? `:${encodeURIComponent(userinfo.password)}`
: "";
return `${usernameText}${passwordText}@`;
}
+60
View File
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResultSetImpl = exports.transactionModeToBegin = exports.supportedUrlLink = void 0;
const js_base64_1 = require("js-base64");
exports.supportedUrlLink = "https://github.com/libsql/libsql-client-ts#supported-urls";
function transactionModeToBegin(mode) {
if (mode === "write") {
return "BEGIN IMMEDIATE";
}
else if (mode === "read") {
return "BEGIN TRANSACTION READONLY";
}
else if (mode === "deferred") {
return "BEGIN DEFERRED";
}
else {
throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"');
}
}
exports.transactionModeToBegin = transactionModeToBegin;
class ResultSetImpl {
columns;
columnTypes;
rows;
rowsAffected;
lastInsertRowid;
constructor(columns, columnTypes, rows, rowsAffected, lastInsertRowid) {
this.columns = columns;
this.columnTypes = columnTypes;
this.rows = rows;
this.rowsAffected = rowsAffected;
this.lastInsertRowid = lastInsertRowid;
}
toJSON() {
return {
columns: this.columns,
columnTypes: this.columnTypes,
rows: this.rows.map(rowToJson),
rowsAffected: this.rowsAffected,
lastInsertRowid: this.lastInsertRowid !== undefined
? "" + this.lastInsertRowid
: null,
};
}
}
exports.ResultSetImpl = ResultSetImpl;
function rowToJson(row) {
return Array.prototype.map.call(row, valueToJson);
}
function valueToJson(value) {
if (typeof value === "bigint") {
return "" + value;
}
else if (value instanceof ArrayBuffer) {
return js_base64_1.Base64.fromUint8Array(new Uint8Array(value));
}
else {
return value;
}
}
+459
View File
@@ -0,0 +1,459 @@
/** Configuration object for {@link createClient}. */
export interface Config {
/** The database URL.
*
* The client supports `libsql:`, `http:`/`https:`, `ws:`/`wss:` and `file:` URL. For more infomation,
* please refer to the project README:
*
* https://github.com/libsql/libsql-client-ts#supported-urls
*/
url: string;
/** Authentication token for the database. */
authToken?: string;
/** Encryption key for the database. */
encryptionKey?: string;
/** Encryption key for encryption in Turso Cloud. */
remoteEncryptionKey?: string;
/** URL of a remote server to synchronize database with. */
syncUrl?: string;
/** Sync interval in seconds. */
syncInterval?: number;
/** Read your writes */
readYourWrites?: boolean;
/** Enable offline writes */
offline?: boolean;
/** Enables or disables TLS for `libsql:` URLs.
*
* By default, `libsql:` URLs use TLS. You can set this option to `false` to disable TLS.
*/
tls?: boolean;
/** How to convert SQLite integers to JavaScript values:
*
* - `"number"` (default): returns SQLite integers as JavaScript `number`-s (double precision floats).
* `number` cannot precisely represent integers larger than 2^53-1 in absolute value, so attempting to read
* larger integers will throw a `RangeError`.
* - `"bigint"`: returns SQLite integers as JavaScript `bigint`-s (arbitrary precision integers). Bigints can
* precisely represent all SQLite integers.
* - `"string"`: returns SQLite integers as strings.
*/
intMode?: IntMode;
/** Custom `fetch` function to use for the HTTP client.
*
* By default, the HTTP client uses `fetch` from the `@libsql/isomorphic-fetch` package, but you can pass
* your own function here. The argument to this function will be `Request` from
* `@libsql/isomorphic-fetch`, and it must return a promise that resolves to an object that is compatible
* with the Web `Response`.
*/
fetch?: Function;
/** Concurrency limit.
*
* By default, the client performs up to 20 concurrent requests. You can set this option to a higher
* number to increase the concurrency limit or set it to 0 to disable concurrency limits completely.
*/
concurrency?: number | undefined;
}
/** Representation of integers from database as JavaScript values. See {@link Config.intMode}. */
export type IntMode = "number" | "bigint" | "string";
/** Client object for a remote or local database.
*
* After you are done with the client, you **should** close it by calling {@link close}.
*/
export interface Client {
/** Execute a single SQL statement.
*
* Every statement executed with this method is executed in its own logical database connection. If you
* want to execute a group of statements in a transaction, use the {@link batch} or the {@link
* transaction} methods.
*
* ```javascript
* // execute a statement without arguments
* const rs = await client.execute("SELECT * FROM books");
*
* // execute a statement with positional arguments
* const rs = await client.execute({
* sql: "SELECT * FROM books WHERE author = ?",
* args: ["Jane Austen"],
* });
*
* // execute a statement with named arguments
* const rs = await client.execute({
* sql: "SELECT * FROM books WHERE published_at > $year",
* args: {year: 1719},
* });
* ```
*/
execute(stmt: InStatement): Promise<ResultSet>;
execute(sql: string, args?: InArgs): Promise<ResultSet>;
/** Execute a batch of SQL statements in a transaction.
*
* The batch is executed in its own logical database connection and the statements are wrapped in a
* transaction. This ensures that the batch is applied atomically: either all or no changes are applied.
*
* The `mode` parameter selects the transaction mode for the batch; please see {@link TransactionMode} for
* details. The default transaction mode is `"deferred"`.
*
* If any of the statements in the batch fails with an error, the batch is aborted, the transaction is
* rolled back and the returned promise is rejected.
*
* This method provides non-interactive transactions. If you need interactive transactions, please use the
* {@link transaction} method.
*
* ```javascript
* const rss = await client.batch([
* // batch statement without arguments
* "DELETE FROM books WHERE name LIKE '%Crusoe'",
*
* // batch statement with positional arguments
* {
* sql: "INSERT INTO books (name, author, published_at) VALUES (?, ?, ?)",
* args: ["First Impressions", "Jane Austen", 1813],
* },
*
* // batch statement with named arguments
* {
* sql: "UPDATE books SET name = $new WHERE name = $old",
* args: {old: "First Impressions", new: "Pride and Prejudice"},
* },
* ], "write");
* ```
*/
batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;
/** Execute a batch of SQL statements in a transaction with PRAGMA foreign_keys=off; before and PRAGMA foreign_keys=on; after.
*
* The batch is executed in its own logical database connection and the statements are wrapped in a
* transaction. This ensures that the batch is applied atomically: either all or no changes are applied.
*
* The transaction mode is `"deferred"`.
*
* If any of the statements in the batch fails with an error, the batch is aborted, the transaction is
* rolled back and the returned promise is rejected.
*
* ```javascript
* const rss = await client.migrate([
* // statement without arguments
* "CREATE TABLE test (a INT)",
*
* // statement with positional arguments
* {
* sql: "INSERT INTO books (name, author, published_at) VALUES (?, ?, ?)",
* args: ["First Impressions", "Jane Austen", 1813],
* },
*
* // statement with named arguments
* {
* sql: "UPDATE books SET name = $new WHERE name = $old",
* args: {old: "First Impressions", new: "Pride and Prejudice"},
* },
* ]);
* ```
*/
migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
/** Start an interactive transaction.
*
* Interactive transactions allow you to interleave execution of SQL statements with your application
* logic. They can be used if the {@link batch} method is too restrictive, but please note that
* interactive transactions have higher latency.
*
* The `mode` parameter selects the transaction mode for the interactive transaction; please see {@link
* TransactionMode} for details. The default transaction mode is `"deferred"`.
*
* You **must** make sure that the returned {@link Transaction} object is closed, by calling {@link
* Transaction.close}, {@link Transaction.commit} or {@link Transaction.rollback}. The best practice is
* to call {@link Transaction.close} in a `finally` block, as follows:
*
* ```javascript
* const transaction = client.transaction("write");
* try {
* // do some operations with the transaction here
* await transaction.execute({
* sql: "INSERT INTO books (name, author) VALUES (?, ?)",
* args: ["First Impressions", "Jane Austen"],
* });
* await transaction.execute({
* sql: "UPDATE books SET name = ? WHERE name = ?",
* args: ["Pride and Prejudice", "First Impressions"],
* });
*
* // if all went well, commit the transaction
* await transaction.commit();
* } finally {
* // make sure to close the transaction, even if an exception was thrown
* transaction.close();
* }
* ```
*/
transaction(mode?: TransactionMode): Promise<Transaction>;
/** Start an interactive transaction in `"write"` mode.
*
* Please see {@link transaction} for details.
*
* @deprecated Please specify the `mode` explicitly. The default `"write"` will be removed in the next
* major release.
*/
transaction(): Promise<Transaction>;
/** Execute a sequence of SQL statements separated by semicolons.
*
* The statements are executed sequentially on a new logical database connection. If a statement fails,
* further statements are not executed and this method throws an error. All results from the statements
* are ignored.
*
* We do not wrap the statements in a transaction, but the SQL can contain explicit transaction-control
* statements such as `BEGIN` and `COMMIT`.
*
* This method is intended to be used with existing SQL scripts, such as migrations or small database
* dumps. If you want to execute a sequence of statements programmatically, please use {@link batch}
* instead.
*
* ```javascript
* await client.executeMultiple(`
* CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author_id INTEGER NOT NULL);
* CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
* `);
* ```
*/
executeMultiple(sql: string): Promise<void>;
sync(): Promise<Replicated>;
/** Close the client and release resources.
*
* This method closes the client (aborting any operations that are currently in progress) and releases any
* resources associated with the client (such as a WebSocket connection).
*/
close(): void;
/** Reconnect after the client has been closed.
*/
reconnect(): void;
/** Is the client closed?
*
* This is set to `true` after a call to {@link close} or if the client encounters an unrecoverable
* error.
*/
closed: boolean;
/** Which protocol does the client use?
*
* - `"http"` if the client connects over HTTP
* - `"ws"` if the client connects over WebSockets
* - `"file"` if the client works with a local file
*/
protocol: string;
}
/** Interactive transaction.
*
* A transaction groups multiple SQL statements together, so that they are applied atomically: either all
* changes are applied, or none are. Other SQL statements on the database (including statements executed on
* the same {@link Client} object outside of this transaction) will not see any changes from the transaction
* until the transaction is committed by calling {@link commit}. You can also use {@link rollback} to abort
* the transaction and roll back the changes.
*
* You **must** make sure that the {@link Transaction} object is closed, by calling {@link close}, {@link
* commit} or {@link rollback}. The best practice is to call {@link close} in a `finally` block, as follows:
*
* ```javascript
* const transaction = client.transaction("write");
* try {
* // do some operations with the transaction here
* await transaction.execute({
* sql: "INSERT INTO books (name, author) VALUES (?, ?)",
* args: ["First Impressions", "Jane Austen"],
* });
* await transaction.execute({
* sql: "UPDATE books SET name = ? WHERE name = ?",
* args: ["Pride and Prejudice", "First Impressions"],
* });
*
* // if all went well, commit the transaction
* await transaction.commit();
* } finally {
* // make sure to close the transaction, even if an exception was thrown
* transaction.close();
* }
* ```
*/
export interface Transaction {
/** Execute an SQL statement in this transaction.
*
* If the statement makes any changes to the database, these changes won't be visible to statements
* outside of this transaction until you call {@link rollback}.
*
* ```javascript
* await transaction.execute({
* sql: "INSERT INTO books (name, author) VALUES (?, ?)",
* args: ["First Impressions", "Jane Austen"],
* });
* ```
*/
execute(stmt: InStatement): Promise<ResultSet>;
/** Execute a batch of SQL statements in this transaction.
*
* If any of the statements in the batch fails with an error, further statements are not executed and the
* returned promise is rejected with an error, but the transaction is not rolled back.
*/
batch(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
/** Execute a sequence of SQL statements separated by semicolons.
*
* The statements are executed sequentially in the transaction. If a statement fails, further statements
* are not executed and this method throws an error, but the transaction won't be rolled back. All results
* from the statements are ignored.
*
* This method is intended to be used with existing SQL scripts, such as migrations or small database
* dumps. If you want to execute statements programmatically, please use {@link batch} instead.
*/
executeMultiple(sql: string): Promise<void>;
/** Roll back any changes from this transaction.
*
* This method closes the transaction and undoes any changes done by the previous SQL statements on this
* transaction. You cannot call this method after calling {@link commit}, though.
*/
rollback(): Promise<void>;
/** Commit changes from this transaction to the database.
*
* This method closes the transaction and applies all changes done by the previous SQL statement on this
* transaction. Once the returned promise is resolved successfully, the database guarantees that the
* changes were applied.
*/
commit(): Promise<void>;
/** Close the transaction.
*
* This method closes the transaction and releases any resources associated with the transaction. If the
* transaction is already closed (perhaps by a previous call to {@link commit} or {@link rollback}), then
* this method does nothing.
*
* If the transaction wasn't already committed by calling {@link commit}, the transaction is rolled
* back.
*/
close(): void;
/** Is the transaction closed?
*
* This is set to `true` after a call to {@link close}, {@link commit} or {@link rollback}, or if we
* encounter an unrecoverable error.
*/
closed: boolean;
}
/** Transaction mode.
*
* The client supports multiple modes for transactions:
*
* - `"write"` is a read-write transaction, started with `BEGIN IMMEDIATE`. This transaction mode supports
* both read statements (`SELECT`) and write statements (`INSERT`, `UPDATE`, `CREATE TABLE`, etc). The libSQL
* server cannot process multiple write transactions concurrently, so if there is another write transaction
* already started, our transaction will wait in a queue before it can begin.
*
* - `"read"` is a read-only transaction, started with `BEGIN TRANSACTION READONLY` (a libSQL extension). This
* transaction mode supports only reads (`SELECT`) and will not accept write statements. The libSQL server can
* handle multiple read transactions at the same time, so we don't need to wait for other transactions to
* complete. A read-only transaction can also be executed on a local replica, so it provides lower latency.
*
* - `"deferred"` is a transaction started with `BEGIN DEFERRED`, which starts as a read transaction, but the
* first write statement will try to upgrade it to a write transaction. However, this upgrade may fail if
* there already is a write transaction executing on the server, so you should be ready to handle these
* failures.
*
* If your transaction includes only read statements, `"read"` is always preferred over `"deferred"` or
* `"write"`, because `"read"` transactions can be executed more efficiently and don't block other
* transactions.
*
* If your transaction includes both read and write statements, you should be using the `"write"` mode most of
* the time. Use the `"deferred"` mode only if you prefer to fail the write transaction instead of waiting for
* the previous write transactions to complete.
*/
export type TransactionMode = "write" | "read" | "deferred";
/** Result of executing an SQL statement.
*
* ```javascript
* const rs = await client.execute("SELECT name, title FROM books");
* console.log(`Found ${rs.rows.length} books`);
* for (const row in rs.rows) {
* console.log(`Book ${row[0]} by ${row[1]}`);
* }
*
* const rs = await client.execute("DELETE FROM books WHERE author = 'Jane Austen'");
* console.log(`Deleted ${rs.rowsAffected} books`);
* ```
*/
export interface ResultSet {
/** Names of columns.
*
* Names of columns can be defined using the `AS` keyword in SQL:
*
* ```sql
* SELECT author AS author, COUNT(*) AS count FROM books GROUP BY author
* ```
*/
columns: Array<string>;
/** Types of columns.
*
* The types are currently shown for types declared in a SQL table. For
* column types of function calls, for example, an empty string is
* returned.
*/
columnTypes: Array<string>;
/** Rows produced by the statement. */
rows: Array<Row>;
/** Number of rows that were affected by an UPDATE, INSERT or DELETE operation.
*
* This value is not specified for other SQL statements.
*/
rowsAffected: number;
/** ROWID of the last inserted row.
*
* This value is not specified if the SQL statement was not an INSERT or if the table was not a ROWID
* table.
*/
lastInsertRowid: bigint | undefined;
/** Converts the result set to JSON.
*
* This is used automatically by `JSON.stringify()`, but you can also call it explicitly.
*/
toJSON(): any;
}
/** Row returned from an SQL statement.
*
* The row object can be used as an `Array` or as an object:
*
* ```javascript
* const rs = await client.execute("SELECT name, title FROM books");
* for (const row in rs.rows) {
* // Get the value from column `name`
* console.log(row.name);
* // Get the value from second column (`title`)
* console.log(row[1]);
* }
* ```
*/
export interface Row {
/** Number of columns in this row.
*
* All rows in one {@link ResultSet} have the same number and names of columns.
*/
length: number;
/** Columns can be accessed like an array by numeric indexes. */
[index: number]: Value;
/** Columns can be accessed like an object by column names. */
[name: string]: Value;
}
export type Replicated = {
frame_no: number;
frames_synced: number;
} | undefined;
export type Value = null | string | number | bigint | ArrayBuffer;
export type InValue = Value | boolean | Uint8Array | Date;
export type InStatement = {
sql: string;
args?: InArgs;
} | string;
export type InArgs = Array<InValue> | Record<string, InValue>;
/** Error thrown by the client. */
export declare class LibsqlError extends Error {
/** Machine-readable error code. */
code: string;
/** Extended error code with more specific information (e.g., SQLITE_CONSTRAINT_PRIMARYKEY). */
extendedCode?: string;
/** Raw numeric error code */
rawCode?: number;
constructor(message: string, code: string, extendedCode?: string, rawCode?: number, cause?: Error);
}
/** Error thrown by the client during batch operations. */
export declare class LibsqlBatchError extends LibsqlError {
/** The zero-based index of the statement that failed in the batch. */
statementIndex: number;
constructor(message: string, statementIndex: number, code: string, extendedCode?: string, rawCode?: number, cause?: Error);
}
+29
View File
@@ -0,0 +1,29 @@
/** Error thrown by the client. */
export class LibsqlError extends Error {
/** Machine-readable error code. */
code;
/** Extended error code with more specific information (e.g., SQLITE_CONSTRAINT_PRIMARYKEY). */
extendedCode;
/** Raw numeric error code */
rawCode;
constructor(message, code, extendedCode, rawCode, cause) {
if (code !== undefined) {
message = `${code}: ${message}`;
}
super(message, { cause });
this.code = code;
this.extendedCode = extendedCode;
this.rawCode = rawCode;
this.name = "LibsqlError";
}
}
/** Error thrown by the client during batch operations. */
export class LibsqlBatchError extends LibsqlError {
/** The zero-based index of the statement that failed in the batch. */
statementIndex;
constructor(message, statementIndex, code, extendedCode, rawCode, cause) {
super(message, code, extendedCode, rawCode, cause);
this.statementIndex = statementIndex;
this.name = "LibsqlBatchError";
}
}
+21
View File
@@ -0,0 +1,21 @@
import type { Config, IntMode } from "./api.js";
import type { Authority } from "./uri.js";
export interface ExpandedConfig {
scheme: ExpandedScheme;
tls: boolean;
authority: Authority | undefined;
path: string;
authToken: string | undefined;
encryptionKey: string | undefined;
remoteEncryptionKey: string | undefined;
syncUrl: string | undefined;
syncInterval: number | undefined;
readYourWrites: boolean | undefined;
offline: boolean | undefined;
intMode: IntMode;
fetch: Function | undefined;
concurrency: number;
}
export type ExpandedScheme = "wss" | "ws" | "https" | "http" | "file";
export declare function isInMemoryConfig(config: ExpandedConfig): boolean;
export declare function expandConfig(config: Readonly<Config>, preferHttp: boolean): ExpandedConfig;
+138
View File
@@ -0,0 +1,138 @@
import { LibsqlError } from "./api.js";
import { parseUri } from "./uri.js";
import { supportedUrlLink } from "./util.js";
const inMemoryMode = ":memory:";
export function isInMemoryConfig(config) {
return (config.scheme === "file" &&
(config.path === ":memory:" || config.path.startsWith(":memory:?")));
}
export function expandConfig(config, preferHttp) {
if (typeof config !== "object") {
// produce a reasonable error message in the common case where users type
// `createClient("libsql://...")` instead of `createClient({url: "libsql://..."})`
throw new TypeError(`Expected client configuration as object, got ${typeof config}`);
}
let { url, authToken, tls, intMode, concurrency } = config;
// fill simple defaults right here
concurrency = Math.max(0, concurrency || 20);
intMode ??= "number";
let connectionQueryParams = []; // recognized query parameters which we sanitize through white list of valid key-value pairs
// convert plain :memory: url to URI format to make logic more uniform
if (url === inMemoryMode) {
url = "file::memory:";
}
// parse url parameters first and override config with update values
const uri = parseUri(url);
const originalUriScheme = uri.scheme.toLowerCase();
const isInMemoryMode = originalUriScheme === "file" &&
uri.path === inMemoryMode &&
uri.authority === undefined;
let queryParamsDef;
if (isInMemoryMode) {
queryParamsDef = {
cache: {
values: ["shared", "private"],
update: (key, value) => connectionQueryParams.push(`${key}=${value}`),
},
};
}
else {
queryParamsDef = {
tls: {
values: ["0", "1"],
update: (_, value) => (tls = value === "1"),
},
authToken: {
update: (_, value) => (authToken = value),
},
};
}
for (const { key, value } of uri.query?.pairs ?? []) {
if (!Object.hasOwn(queryParamsDef, key)) {
throw new LibsqlError(`Unsupported URL query parameter ${JSON.stringify(key)}`, "URL_PARAM_NOT_SUPPORTED");
}
const queryParamDef = queryParamsDef[key];
if (queryParamDef.values !== undefined &&
!queryParamDef.values.includes(value)) {
throw new LibsqlError(`Unknown value for the "${key}" query argument: ${JSON.stringify(value)}. Supported values are: [${queryParamDef.values.map((x) => '"' + x + '"').join(", ")}]`, "URL_INVALID");
}
if (queryParamDef.update !== undefined) {
queryParamDef?.update(key, value);
}
}
// fill complex defaults & validate config
const connectionQueryParamsString = connectionQueryParams.length === 0
? ""
: `?${connectionQueryParams.join("&")}`;
const path = uri.path + connectionQueryParamsString;
let scheme;
if (originalUriScheme === "libsql") {
if (tls === false) {
if (uri.authority?.port === undefined) {
throw new LibsqlError('A "libsql:" URL with ?tls=0 must specify an explicit port', "URL_INVALID");
}
scheme = preferHttp ? "http" : "ws";
}
else {
scheme = preferHttp ? "https" : "wss";
}
}
else {
scheme = originalUriScheme;
}
if (scheme === "http" || scheme === "ws") {
tls ??= false;
}
else {
tls ??= true;
}
if (scheme !== "http" &&
scheme !== "ws" &&
scheme !== "https" &&
scheme !== "wss" &&
scheme !== "file") {
throw new LibsqlError('The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, ' +
`got ${JSON.stringify(uri.scheme + ":")}. ` +
`For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
}
if (intMode !== "number" && intMode !== "bigint" && intMode !== "string") {
throw new TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(intMode)}`);
}
if (uri.fragment !== undefined) {
throw new LibsqlError(`URL fragments are not supported: ${JSON.stringify("#" + uri.fragment)}`, "URL_INVALID");
}
if (isInMemoryMode) {
return {
scheme: "file",
tls: false,
path,
intMode,
concurrency,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
authToken: undefined,
encryptionKey: undefined,
remoteEncryptionKey: undefined,
authority: undefined,
};
}
return {
scheme,
tls,
authority: uri.authority,
path,
authToken,
intMode,
concurrency,
encryptionKey: config.encryptionKey,
remoteEncryptionKey: config.remoteEncryptionKey,
syncUrl: config.syncUrl,
syncInterval: config.syncInterval,
readYourWrites: config.readYourWrites,
offline: config.offline,
fetch: config.fetch,
};
}
+30
View File
@@ -0,0 +1,30 @@
/// <reference types="node" />
export interface Uri {
scheme: string;
authority: Authority | undefined;
path: string;
query: Query | undefined;
fragment: string | undefined;
}
export interface HierPart {
authority: Authority | undefined;
path: string;
}
export interface Authority {
host: string;
port: number | undefined;
userinfo: Userinfo | undefined;
}
export interface Userinfo {
username: string;
password: string | undefined;
}
export interface Query {
pairs: Array<KeyValue>;
}
export interface KeyValue {
key: string;
value: string;
}
export declare function parseUri(text: string): Uri;
export declare function encodeBaseUrl(scheme: string, authority: Authority | undefined, path: string): URL;
+120
View File
@@ -0,0 +1,120 @@
// URI parser based on RFC 3986
// We can't use the standard `URL` object, because we want to support relative `file:` URLs like
// `file:relative/path/database.db`, which are not correct according to RFC 8089, which standardizes the
// `file` scheme.
import { LibsqlError } from "./api.js";
export function parseUri(text) {
const match = URI_RE.exec(text);
if (match === null) {
throw new LibsqlError(`The URL '${text}' is not in a valid format`, "URL_INVALID");
}
const groups = match.groups;
const scheme = groups["scheme"];
const authority = groups["authority"] !== undefined
? parseAuthority(groups["authority"])
: undefined;
const path = percentDecode(groups["path"]);
const query = groups["query"] !== undefined ? parseQuery(groups["query"]) : undefined;
const fragment = groups["fragment"] !== undefined
? percentDecode(groups["fragment"])
: undefined;
return { scheme, authority, path, query, fragment };
}
const URI_RE = (() => {
const SCHEME = "(?<scheme>[A-Za-z][A-Za-z.+-]*)";
const AUTHORITY = "(?<authority>[^/?#]*)";
const PATH = "(?<path>[^?#]*)";
const QUERY = "(?<query>[^#]*)";
const FRAGMENT = "(?<fragment>.*)";
return new RegExp(`^${SCHEME}:(//${AUTHORITY})?${PATH}(\\?${QUERY})?(#${FRAGMENT})?$`, "su");
})();
function parseAuthority(text) {
const match = AUTHORITY_RE.exec(text);
if (match === null) {
throw new LibsqlError("The authority part of the URL is not in a valid format", "URL_INVALID");
}
const groups = match.groups;
const host = percentDecode(groups["host_br"] ?? groups["host"]);
const port = groups["port"] ? parseInt(groups["port"], 10) : undefined;
const userinfo = groups["username"] !== undefined
? {
username: percentDecode(groups["username"]),
password: groups["password"] !== undefined
? percentDecode(groups["password"])
: undefined,
}
: undefined;
return { host, port, userinfo };
}
const AUTHORITY_RE = (() => {
return new RegExp(`^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$`, "su");
})();
// Query string is parsed as application/x-www-form-urlencoded according to the Web URL standard:
// https://url.spec.whatwg.org/#urlencoded-parsing
function parseQuery(text) {
const sequences = text.split("&");
const pairs = [];
for (const sequence of sequences) {
if (sequence === "") {
continue;
}
let key;
let value;
const splitIdx = sequence.indexOf("=");
if (splitIdx < 0) {
key = sequence;
value = "";
}
else {
key = sequence.substring(0, splitIdx);
value = sequence.substring(splitIdx + 1);
}
pairs.push({
key: percentDecode(key.replaceAll("+", " ")),
value: percentDecode(value.replaceAll("+", " ")),
});
}
return { pairs };
}
function percentDecode(text) {
try {
return decodeURIComponent(text);
}
catch (e) {
if (e instanceof URIError) {
throw new LibsqlError(`URL component has invalid percent encoding: ${e}`, "URL_INVALID", undefined, undefined, e);
}
throw e;
}
}
export function encodeBaseUrl(scheme, authority, path) {
if (authority === undefined) {
throw new LibsqlError(`URL with scheme ${JSON.stringify(scheme + ":")} requires authority (the "//" part)`, "URL_INVALID");
}
const schemeText = `${scheme}:`;
const hostText = encodeHost(authority.host);
const portText = encodePort(authority.port);
const userinfoText = encodeUserinfo(authority.userinfo);
const authorityText = `//${userinfoText}${hostText}${portText}`;
let pathText = path.split("/").map(encodeURIComponent).join("/");
if (pathText !== "" && !pathText.startsWith("/")) {
pathText = "/" + pathText;
}
return new URL(`${schemeText}${authorityText}${pathText}`);
}
function encodeHost(host) {
return host.includes(":") ? `[${encodeURI(host)}]` : encodeURI(host);
}
function encodePort(port) {
return port !== undefined ? `:${port}` : "";
}
function encodeUserinfo(userinfo) {
if (userinfo === undefined) {
return "";
}
const usernameText = encodeURIComponent(userinfo.username);
const passwordText = userinfo.password !== undefined
? `:${encodeURIComponent(userinfo.password)}`
: "";
return `${usernameText}${passwordText}@`;
}
+12
View File
@@ -0,0 +1,12 @@
import { ResultSet, Row, TransactionMode } from "./api";
export declare const supportedUrlLink = "https://github.com/libsql/libsql-client-ts#supported-urls";
export declare function transactionModeToBegin(mode: TransactionMode): string;
export declare class ResultSetImpl implements ResultSet {
columns: Array<string>;
columnTypes: Array<string>;
rows: Array<Row>;
rowsAffected: number;
lastInsertRowid: bigint | undefined;
constructor(columns: Array<string>, columnTypes: Array<string>, rows: Array<Row>, rowsAffected: number, lastInsertRowid: bigint | undefined);
toJSON(): any;
}
+55
View File
@@ -0,0 +1,55 @@
import { Base64 } from "js-base64";
export const supportedUrlLink = "https://github.com/libsql/libsql-client-ts#supported-urls";
export function transactionModeToBegin(mode) {
if (mode === "write") {
return "BEGIN IMMEDIATE";
}
else if (mode === "read") {
return "BEGIN TRANSACTION READONLY";
}
else if (mode === "deferred") {
return "BEGIN DEFERRED";
}
else {
throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"');
}
}
export class ResultSetImpl {
columns;
columnTypes;
rows;
rowsAffected;
lastInsertRowid;
constructor(columns, columnTypes, rows, rowsAffected, lastInsertRowid) {
this.columns = columns;
this.columnTypes = columnTypes;
this.rows = rows;
this.rowsAffected = rowsAffected;
this.lastInsertRowid = lastInsertRowid;
}
toJSON() {
return {
columns: this.columns,
columnTypes: this.columnTypes,
rows: this.rows.map(rowToJson),
rowsAffected: this.rowsAffected,
lastInsertRowid: this.lastInsertRowid !== undefined
? "" + this.lastInsertRowid
: null,
};
}
}
function rowToJson(row) {
return Array.prototype.map.call(row, valueToJson);
}
function valueToJson(value) {
if (typeof value === "bigint") {
return "" + value;
}
else if (value instanceof ArrayBuffer) {
return Base64.fromUint8Array(new Uint8Array(value));
}
else {
return value;
}
}
+91
View File
@@ -0,0 +1,91 @@
{
"name": "@libsql/core",
"version": "0.17.0",
"keywords": [
"libsql",
"database",
"sqlite",
"serverless",
"vercel",
"netlify",
"lambda"
],
"description": "libSQL driver for TypeScript and JavaScript",
"repository": {
"type": "git",
"url": "git+https://github.com/tursodatabase/libsql-client-ts",
"directory": "packages/libsql-core"
},
"authors": [
"Jan Špaček <[email protected]>",
"Pekka Enberg <[email protected]>",
"Jan Plhak <[email protected]>"
],
"license": "MIT",
"type": "module",
"exports": {
"./api": {
"types": "./lib-esm/api.d.ts",
"import": "./lib-esm/api.js",
"require": "./lib-cjs/api.js"
},
"./config": {
"types": "./lib-esm/config.d.ts",
"import": "./lib-esm/config.js",
"require": "./lib-cjs/config.js"
},
"./uri": {
"types": "./lib-esm/uri.d.ts",
"import": "./lib-esm/uri.js",
"require": "./lib-cjs/uri.js"
},
"./util": {
"types": "./lib-esm/util.d.ts",
"import": "./lib-esm/util.js",
"require": "./lib-cjs/util.js"
}
},
"typesVersions": {
"*": {
"api": [
"./lib-esm/api.d.ts"
],
"config": [
"./lib-esm/config.d.ts"
],
"uri": [
"./lib-esm/uri.d.ts"
],
"util": [
"./lib-esm/util.d.ts"
]
}
},
"files": [
"lib-cjs/**",
"lib-esm/**"
],
"scripts": {
"prepublishOnly": "npm run build",
"prebuild": "rm -rf ./lib-cjs ./lib-esm",
"build": "npm run build:cjs && npm run build:esm",
"build:cjs": "tsc -p tsconfig.build-cjs.json",
"build:esm": "tsc -p tsconfig.build-esm.json",
"format:check": "prettier --check .",
"postbuild": "cp package-cjs.json ./lib-cjs/package.json",
"test": "jest --runInBand",
"typecheck": "tsc --noEmit",
"typedoc": "rm -rf ./docs && typedoc"
},
"dependencies": {
"js-base64": "^3.7.5"
},
"devDependencies": {
"@types/jest": "^29.2.5",
"@types/node": "^18.15.5",
"jest": "^29.3.1",
"ts-jest": "^29.0.5",
"typedoc": "^0.23.28",
"typescript": "^4.9.4"
}
}
+3
View File
@@ -0,0 +1,3 @@
# `@libsql/darwin-arm64`
Prebuilt binary package for `libsql` on `darwin-arm64`.
Binary file not shown.
+36
View File
@@ -0,0 +1,36 @@
{
"name": "@libsql/darwin-arm64",
"description": "Prebuilt binary package for `libsql` on `darwin-arm64`.",
"version": "0.5.22",
"os": [
"darwin"
],
"cpu": [
"arm64"
],
"main": "index.node",
"files": [
"index.node"
],
"neon": {
"type": "binary",
"rust": "aarch64-apple-darwin",
"node": "darwin-arm64",
"platform": "darwin",
"arch": "arm64",
"abi": null
},
"author": "Pekka Enberg <[email protected]>",
"repository": {
"type": "git",
"url": "git+https://github.com/tursodatabase/libsql-js.git"
},
"keywords": [
"libsql"
],
"bugs": {
"url": "https://github.com/tursodatabase/libsql-js/issues"
},
"homepage": "https://github.com/tursodatabase/libsql-js",
"license": "MIT"
}
+20
View File
@@ -0,0 +1,20 @@
MIT License
Copyright 2023 the sqld authors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+59
View File
@@ -0,0 +1,59 @@
# Hrana client for TypeScript
**[API docs][docs] | [Github][github] | [npm][npm]**
[docs]: https://libsql.org/hrana-client-ts/
[github]: https://github.com/libsql/hrana-client-ts/
[npm]: https://www.npmjs.com/package/@libsql/hrana-client
This package implements a Hrana client for TypeScript. Hrana is the protocol for connecting to sqld using WebSocket or HTTP.
> This package is intended mostly for internal use. Consider using the [`@libsql/client`][libsql-client] package, which will use Hrana automatically.
[libsql-client]: https://www.npmjs.com/package/@libsql/client
## Usage
```typescript
import * as hrana from "@libsql/hrana-client";
// Open a `hrana.Client`, which works like a connection pool in standard SQL
// databases.
const url = process.env.URL ?? "ws://localhost:8080"; // Address of the sqld server
const jwt = process.env.JWT; // JWT token for authentication
// Here we are using Hrana over WebSocket:
const client = hrana.openWs(url, jwt);
// But we can also use Hrana over HTTP:
// const client = hrana.openHttp(url, jwt);
// Open a `hrana.Stream`, which is an interactive SQL stream. This corresponds
// to a "connection" from other SQL databases
const stream = client.openStream();
// Fetch all rows returned by a SQL statement
const books = await stream.query("SELECT title, year FROM book WHERE author = 'Jane Austen'");
// The rows are returned in an Array...
for (const book of books.rows) {
// every returned row works as an array (`book[1]`) and as an object (`book.year`)
console.log(`${book.title} from ${book.year}`);
}
// Fetch a single row
const book = await stream.queryRow("SELECT title, MIN(year) FROM book");
if (book.row !== undefined) {
console.log(`The oldest book is ${book.row.title} from year ${book.row[1]}`);
}
// Fetch a single value, using a bound parameter
const year = await stream.queryValue(["SELECT MAX(year) FROM book WHERE author = ?", ["Jane Austen"]]);
if (year.value !== undefined) {
console.log(`Last book from Jane Austen was published in ${year.value}`);
}
// Execute a statement that does not return any rows
const res = await stream.run(["DELETE FROM book WHERE author = ?", ["J. K. Rowling"]])
console.log(`${res.affectedRowCount} books have been cancelled`);
// When you are done, remember to close the client
client.close();
```
+277
View File
@@ -0,0 +1,277 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchCond = exports.BatchStep = exports.Batch = void 0;
const errors_js_1 = require("./errors.js");
const result_js_1 = require("./result.js");
const stmt_js_1 = require("./stmt.js");
const util_js_1 = require("./util.js");
/** A builder for creating a batch and executing it on the server. */
class Batch {
/** @private */
_stream;
#useCursor;
/** @private */
_steps;
#executed;
/** @private */
constructor(stream, useCursor) {
this._stream = stream;
this.#useCursor = useCursor;
this._steps = [];
this.#executed = false;
}
/** Return a builder for adding a step to the batch. */
step() {
return new BatchStep(this);
}
/** Execute the batch. */
execute() {
if (this.#executed) {
throw new errors_js_1.MisuseError("This batch has already been executed");
}
this.#executed = true;
const batch = {
steps: this._steps.map((step) => step.proto),
};
if (this.#useCursor) {
return executeCursor(this._stream, this._steps, batch);
}
else {
return executeRegular(this._stream, this._steps, batch);
}
}
}
exports.Batch = Batch;
function executeRegular(stream, steps, batch) {
return stream._batch(batch).then((result) => {
for (let step = 0; step < steps.length; ++step) {
const stepResult = result.stepResults.get(step);
const stepError = result.stepErrors.get(step);
steps[step].callback(stepResult, stepError);
}
});
}
async function executeCursor(stream, steps, batch) {
const cursor = await stream._openCursor(batch);
try {
let nextStep = 0;
let beginEntry = undefined;
let rows = [];
for (;;) {
const entry = await cursor.next();
if (entry === undefined) {
break;
}
if (entry.type === "step_begin") {
if (entry.step < nextStep || entry.step >= steps.length) {
throw new errors_js_1.ProtoError("Server produced StepBeginEntry for unexpected step");
}
else if (beginEntry !== undefined) {
throw new errors_js_1.ProtoError("Server produced StepBeginEntry before terminating previous step");
}
for (let step = nextStep; step < entry.step; ++step) {
steps[step].callback(undefined, undefined);
}
nextStep = entry.step + 1;
beginEntry = entry;
rows = [];
}
else if (entry.type === "step_end") {
if (beginEntry === undefined) {
throw new errors_js_1.ProtoError("Server produced StepEndEntry but no step is active");
}
const stmtResult = {
cols: beginEntry.cols,
rows,
affectedRowCount: entry.affectedRowCount,
lastInsertRowid: entry.lastInsertRowid,
};
steps[beginEntry.step].callback(stmtResult, undefined);
beginEntry = undefined;
rows = [];
}
else if (entry.type === "step_error") {
if (beginEntry === undefined) {
if (entry.step >= steps.length) {
throw new errors_js_1.ProtoError("Server produced StepErrorEntry for unexpected step");
}
for (let step = nextStep; step < entry.step; ++step) {
steps[step].callback(undefined, undefined);
}
}
else {
if (entry.step !== beginEntry.step) {
throw new errors_js_1.ProtoError("Server produced StepErrorEntry for unexpected step");
}
beginEntry = undefined;
rows = [];
}
steps[entry.step].callback(undefined, entry.error);
nextStep = entry.step + 1;
}
else if (entry.type === "row") {
if (beginEntry === undefined) {
throw new errors_js_1.ProtoError("Server produced RowEntry but no step is active");
}
rows.push(entry.row);
}
else if (entry.type === "error") {
throw (0, result_js_1.errorFromProto)(entry.error);
}
else if (entry.type === "none") {
throw new errors_js_1.ProtoError("Server produced unrecognized CursorEntry");
}
else {
throw (0, util_js_1.impossible)(entry, "Impossible CursorEntry");
}
}
if (beginEntry !== undefined) {
throw new errors_js_1.ProtoError("Server closed Cursor before terminating active step");
}
for (let step = nextStep; step < steps.length; ++step) {
steps[step].callback(undefined, undefined);
}
}
finally {
cursor.close();
}
}
/** A builder for adding a step to the batch. */
class BatchStep {
/** @private */
_batch;
#conds;
/** @private */
_index;
/** @private */
constructor(batch) {
this._batch = batch;
this.#conds = [];
this._index = undefined;
}
/** Add the condition that needs to be satisfied to execute the statement. If you use this method multiple
* times, we join the conditions with a logical AND. */
condition(cond) {
this.#conds.push(cond._proto);
return this;
}
/** Add a statement that returns rows. */
query(stmt) {
return this.#add(stmt, true, result_js_1.rowsResultFromProto);
}
/** Add a statement that returns at most a single row. */
queryRow(stmt) {
return this.#add(stmt, true, result_js_1.rowResultFromProto);
}
/** Add a statement that returns at most a single value. */
queryValue(stmt) {
return this.#add(stmt, true, result_js_1.valueResultFromProto);
}
/** Add a statement without returning rows. */
run(stmt) {
return this.#add(stmt, false, result_js_1.stmtResultFromProto);
}
#add(inStmt, wantRows, fromProto) {
if (this._index !== undefined) {
throw new errors_js_1.MisuseError("This BatchStep has already been added to the batch");
}
const stmt = (0, stmt_js_1.stmtToProto)(this._batch._stream._sqlOwner(), inStmt, wantRows);
let condition;
if (this.#conds.length === 0) {
condition = undefined;
}
else if (this.#conds.length === 1) {
condition = this.#conds[0];
}
else {
condition = { type: "and", conds: this.#conds.slice() };
}
const proto = { stmt, condition };
return new Promise((outputCallback, errorCallback) => {
const callback = (stepResult, stepError) => {
if (stepResult !== undefined && stepError !== undefined) {
errorCallback(new errors_js_1.ProtoError("Server returned both result and error"));
}
else if (stepError !== undefined) {
errorCallback((0, result_js_1.errorFromProto)(stepError));
}
else if (stepResult !== undefined) {
outputCallback(fromProto(stepResult, this._batch._stream.intMode));
}
else {
outputCallback(undefined);
}
};
this._index = this._batch._steps.length;
this._batch._steps.push({ proto, callback });
});
}
}
exports.BatchStep = BatchStep;
class BatchCond {
/** @private */
_batch;
/** @private */
_proto;
/** @private */
constructor(batch, proto) {
this._batch = batch;
this._proto = proto;
}
/** Create a condition that evaluates to true when the given step executes successfully.
*
* If the given step fails error or is skipped because its condition evaluated to false, this
* condition evaluates to false.
*/
static ok(step) {
return new BatchCond(step._batch, { type: "ok", step: stepIndex(step) });
}
/** Create a condition that evaluates to true when the given step fails.
*
* If the given step succeeds or is skipped because its condition evaluated to false, this condition
* evaluates to false.
*/
static error(step) {
return new BatchCond(step._batch, { type: "error", step: stepIndex(step) });
}
/** Create a condition that is a logical negation of another condition.
*/
static not(cond) {
return new BatchCond(cond._batch, { type: "not", cond: cond._proto });
}
/** Create a condition that is a logical AND of other conditions.
*/
static and(batch, conds) {
for (const cond of conds) {
checkCondBatch(batch, cond);
}
return new BatchCond(batch, { type: "and", conds: conds.map(e => e._proto) });
}
/** Create a condition that is a logical OR of other conditions.
*/
static or(batch, conds) {
for (const cond of conds) {
checkCondBatch(batch, cond);
}
return new BatchCond(batch, { type: "or", conds: conds.map(e => e._proto) });
}
/** Create a condition that evaluates to true when the SQL connection is in autocommit mode (not inside an
* explicit transaction). This requires protocol version 3 or higher.
*/
static isAutocommit(batch) {
batch._stream.client()._ensureVersion(3, "BatchCond.isAutocommit()");
return new BatchCond(batch, { type: "is_autocommit" });
}
}
exports.BatchCond = BatchCond;
function stepIndex(step) {
if (step._index === undefined) {
throw new errors_js_1.MisuseError("Cannot add a condition referencing a step that has not been added to the batch");
}
return step._index;
}
function checkCondBatch(expectedBatch, cond) {
if (cond._batch !== expectedBatch) {
throw new errors_js_1.MisuseError("Cannot mix BatchCond objects for different Batch objects");
}
}
@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ByteQueue = void 0;
class ByteQueue {
#array;
#shiftPos;
#pushPos;
constructor(initialCap) {
this.#array = new Uint8Array(new ArrayBuffer(initialCap));
this.#shiftPos = 0;
this.#pushPos = 0;
}
get length() {
return this.#pushPos - this.#shiftPos;
}
data() {
return this.#array.slice(this.#shiftPos, this.#pushPos);
}
push(chunk) {
this.#ensurePush(chunk.byteLength);
this.#array.set(chunk, this.#pushPos);
this.#pushPos += chunk.byteLength;
}
#ensurePush(pushLength) {
if (this.#pushPos + pushLength <= this.#array.byteLength) {
return;
}
const filledLength = this.#pushPos - this.#shiftPos;
if (filledLength + pushLength <= this.#array.byteLength &&
2 * this.#pushPos >= this.#array.byteLength) {
this.#array.copyWithin(0, this.#shiftPos, this.#pushPos);
}
else {
let newCap = this.#array.byteLength;
do {
newCap *= 2;
} while (filledLength + pushLength > newCap);
const newArray = new Uint8Array(new ArrayBuffer(newCap));
newArray.set(this.#array.slice(this.#shiftPos, this.#pushPos), 0);
this.#array = newArray;
}
this.#pushPos = filledLength;
this.#shiftPos = 0;
}
shift(length) {
this.#shiftPos += length;
}
}
exports.ByteQueue = ByteQueue;
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
/** A client for the Hrana protocol (a "database connection pool"). */
class Client {
/** @private */
constructor() {
this.intMode = "number";
}
/** Representation of integers returned from the database. See {@link IntMode}.
*
* This value is inherited by {@link Stream} objects created with {@link openStream}, but you can
* override the integer mode for every stream by setting {@link Stream.intMode} on the stream.
*/
intMode;
}
exports.Client = Client;
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Cursor = void 0;
class Cursor {
}
exports.Cursor = Cursor;
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.describeResultFromProto = void 0;
function describeResultFromProto(result) {
return {
paramNames: result.params.map((p) => p.name),
columns: result.cols,
isExplain: result.isExplain,
isReadonly: result.isReadonly,
};
}
exports.describeResultFromProto = describeResultFromProto;
@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeProtobufMessage = exports.readProtobufMessage = exports.writeJsonObject = exports.readJsonObject = void 0;
var decode_js_1 = require("./json/decode.js");
Object.defineProperty(exports, "readJsonObject", { enumerable: true, get: function () { return decode_js_1.readJsonObject; } });
var encode_js_1 = require("./json/encode.js");
Object.defineProperty(exports, "writeJsonObject", { enumerable: true, get: function () { return encode_js_1.writeJsonObject; } });
var decode_js_2 = require("./protobuf/decode.js");
Object.defineProperty(exports, "readProtobufMessage", { enumerable: true, get: function () { return decode_js_2.readProtobufMessage; } });
var encode_js_2 = require("./protobuf/encode.js");
Object.defineProperty(exports, "writeProtobufMessage", { enumerable: true, get: function () { return encode_js_2.writeProtobufMessage; } });
@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readJsonObject = exports.arrayObjectsMap = exports.object = exports.array = exports.boolean = exports.number = exports.stringOpt = exports.string = void 0;
const errors_js_1 = require("../../errors.js");
function string(value) {
if (typeof value === "string") {
return value;
}
throw typeError(value, "string");
}
exports.string = string;
function stringOpt(value) {
if (value === null || value === undefined) {
return undefined;
}
else if (typeof value === "string") {
return value;
}
throw typeError(value, "string or null");
}
exports.stringOpt = stringOpt;
function number(value) {
if (typeof value === "number") {
return value;
}
throw typeError(value, "number");
}
exports.number = number;
function boolean(value) {
if (typeof value === "boolean") {
return value;
}
throw typeError(value, "boolean");
}
exports.boolean = boolean;
function array(value) {
if (Array.isArray(value)) {
return value;
}
throw typeError(value, "array");
}
exports.array = array;
function object(value) {
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
return value;
}
throw typeError(value, "object");
}
exports.object = object;
function arrayObjectsMap(value, fun) {
return array(value).map((elemValue) => fun(object(elemValue)));
}
exports.arrayObjectsMap = arrayObjectsMap;
function typeError(value, expected) {
if (value === undefined) {
return new errors_js_1.ProtoError(`Expected ${expected}, but the property was missing`);
}
let received = typeof value;
if (value === null) {
received = "null";
}
else if (Array.isArray(value)) {
received = "array";
}
return new errors_js_1.ProtoError(`Expected ${expected}, received ${received}`);
}
function readJsonObject(value, fun) {
return fun(object(value));
}
exports.readJsonObject = readJsonObject;
@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeJsonObject = exports.ObjectWriter = void 0;
class ObjectWriter {
#output;
#isFirst;
constructor(output) {
this.#output = output;
this.#isFirst = false;
}
begin() {
this.#output.push('{');
this.#isFirst = true;
}
end() {
this.#output.push('}');
this.#isFirst = false;
}
#key(name) {
if (this.#isFirst) {
this.#output.push('"');
this.#isFirst = false;
}
else {
this.#output.push(',"');
}
this.#output.push(name);
this.#output.push('":');
}
string(name, value) {
this.#key(name);
this.#output.push(JSON.stringify(value));
}
stringRaw(name, value) {
this.#key(name);
this.#output.push('"');
this.#output.push(value);
this.#output.push('"');
}
number(name, value) {
this.#key(name);
this.#output.push("" + value);
}
boolean(name, value) {
this.#key(name);
this.#output.push(value ? "true" : "false");
}
object(name, value, valueFun) {
this.#key(name);
this.begin();
valueFun(this, value);
this.end();
}
arrayObjects(name, values, valueFun) {
this.#key(name);
this.#output.push('[');
for (let i = 0; i < values.length; ++i) {
if (i !== 0) {
this.#output.push(',');
}
this.begin();
valueFun(this, values[i]);
this.end();
}
this.#output.push(']');
}
}
exports.ObjectWriter = ObjectWriter;
function writeJsonObject(value, fun) {
const output = [];
const writer = new ObjectWriter(output);
writer.begin();
fun(writer, value);
writer.end();
return output.join("");
}
exports.writeJsonObject = writeJsonObject;
@@ -0,0 +1,155 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readProtobufMessage = exports.FieldReader = void 0;
const errors_js_1 = require("../../errors.js");
const util_js_1 = require("./util.js");
class MessageReader {
#array;
#view;
#pos;
constructor(array) {
this.#array = array;
this.#view = new DataView(array.buffer, array.byteOffset, array.byteLength);
this.#pos = 0;
}
varint() {
let value = 0;
for (let shift = 0;; shift += 7) {
const byte = this.#array[this.#pos++];
value |= (byte & 0x7f) << shift;
if (!(byte & 0x80)) {
break;
}
}
return value;
}
varintBig() {
let value = 0n;
for (let shift = 0n;; shift += 7n) {
const byte = this.#array[this.#pos++];
value |= BigInt(byte & 0x7f) << shift;
if (!(byte & 0x80)) {
break;
}
}
return value;
}
bytes(length) {
const array = new Uint8Array(this.#array.buffer, this.#array.byteOffset + this.#pos, length);
this.#pos += length;
return array;
}
double() {
const value = this.#view.getFloat64(this.#pos, true);
this.#pos += 8;
return value;
}
skipVarint() {
for (;;) {
const byte = this.#array[this.#pos++];
if (!(byte & 0x80)) {
break;
}
}
}
skip(count) {
this.#pos += count;
}
eof() {
return this.#pos >= this.#array.byteLength;
}
}
class FieldReader {
#reader;
#wireType;
constructor(reader) {
this.#reader = reader;
this.#wireType = -1;
}
setup(wireType) {
this.#wireType = wireType;
}
#expect(expectedWireType) {
if (this.#wireType !== expectedWireType) {
throw new errors_js_1.ProtoError(`Expected wire type ${expectedWireType}, got ${this.#wireType}`);
}
this.#wireType = -1;
}
bytes() {
this.#expect(util_js_1.LENGTH_DELIMITED);
const length = this.#reader.varint();
return this.#reader.bytes(length);
}
string() {
return new TextDecoder().decode(this.bytes());
}
message(def) {
return readProtobufMessage(this.bytes(), def);
}
int32() {
this.#expect(util_js_1.VARINT);
return this.#reader.varint();
}
uint32() {
return this.int32();
}
bool() {
return this.int32() !== 0;
}
uint64() {
this.#expect(util_js_1.VARINT);
return this.#reader.varintBig();
}
sint64() {
const value = this.uint64();
return (value >> 1n) ^ (-(value & 1n));
}
double() {
this.#expect(util_js_1.FIXED_64);
return this.#reader.double();
}
maybeSkip() {
if (this.#wireType < 0) {
return;
}
else if (this.#wireType === util_js_1.VARINT) {
this.#reader.skipVarint();
}
else if (this.#wireType === util_js_1.FIXED_64) {
this.#reader.skip(8);
}
else if (this.#wireType === util_js_1.LENGTH_DELIMITED) {
const length = this.#reader.varint();
this.#reader.skip(length);
}
else if (this.#wireType === util_js_1.FIXED_32) {
this.#reader.skip(4);
}
else {
throw new errors_js_1.ProtoError(`Unexpected wire type ${this.#wireType}`);
}
this.#wireType = -1;
}
}
exports.FieldReader = FieldReader;
function readProtobufMessage(data, def) {
const msgReader = new MessageReader(data);
const fieldReader = new FieldReader(msgReader);
let value = def.default();
while (!msgReader.eof()) {
const key = msgReader.varint();
const tag = key >> 3;
const wireType = key & 0x7;
fieldReader.setup(wireType);
const tagFun = def[tag];
if (tagFun !== undefined) {
const returnedValue = tagFun(fieldReader, value);
if (returnedValue !== undefined) {
value = returnedValue;
}
}
fieldReader.maybeSkip();
}
return value;
}
exports.readProtobufMessage = readProtobufMessage;
@@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeProtobufMessage = exports.MessageWriter = void 0;
const util_js_1 = require("./util.js");
class MessageWriter {
#buf;
#array;
#view;
#pos;
constructor() {
this.#buf = new ArrayBuffer(256);
this.#array = new Uint8Array(this.#buf);
this.#view = new DataView(this.#buf);
this.#pos = 0;
}
#ensure(extra) {
if (this.#pos + extra <= this.#buf.byteLength) {
return;
}
let newCap = this.#buf.byteLength;
while (newCap < this.#pos + extra) {
newCap *= 2;
}
const newBuf = new ArrayBuffer(newCap);
const newArray = new Uint8Array(newBuf);
const newView = new DataView(newBuf);
newArray.set(new Uint8Array(this.#buf, 0, this.#pos));
this.#buf = newBuf;
this.#array = newArray;
this.#view = newView;
}
#varint(value) {
this.#ensure(5);
value = 0 | value;
do {
let byte = value & 0x7f;
value >>>= 7;
byte |= (value ? 0x80 : 0);
this.#array[this.#pos++] = byte;
} while (value);
}
#varintBig(value) {
this.#ensure(10);
value = value & 0xffffffffffffffffn;
do {
let byte = Number(value & 0x7fn);
value >>= 7n;
byte |= (value ? 0x80 : 0);
this.#array[this.#pos++] = byte;
} while (value);
}
#tag(tag, wireType) {
this.#varint((tag << 3) | wireType);
}
bytes(tag, value) {
this.#tag(tag, util_js_1.LENGTH_DELIMITED);
this.#varint(value.byteLength);
this.#ensure(value.byteLength);
this.#array.set(value, this.#pos);
this.#pos += value.byteLength;
}
string(tag, value) {
this.bytes(tag, new TextEncoder().encode(value));
}
message(tag, value, fun) {
const writer = new MessageWriter();
fun(writer, value);
this.bytes(tag, writer.data());
}
int32(tag, value) {
this.#tag(tag, util_js_1.VARINT);
this.#varint(value);
}
uint32(tag, value) {
this.int32(tag, value);
}
bool(tag, value) {
this.int32(tag, value ? 1 : 0);
}
sint64(tag, value) {
this.#tag(tag, util_js_1.VARINT);
this.#varintBig((value << 1n) ^ (value >> 63n));
}
double(tag, value) {
this.#tag(tag, util_js_1.FIXED_64);
this.#ensure(8);
this.#view.setFloat64(this.#pos, value, true);
this.#pos += 8;
}
data() {
return new Uint8Array(this.#buf, 0, this.#pos);
}
}
exports.MessageWriter = MessageWriter;
function writeProtobufMessage(value, fun) {
const w = new MessageWriter();
fun(w, value);
return w.data();
}
exports.writeProtobufMessage = writeProtobufMessage;
@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FIXED_32 = exports.GROUP_END = exports.GROUP_START = exports.LENGTH_DELIMITED = exports.FIXED_64 = exports.VARINT = void 0;
exports.VARINT = 0;
exports.FIXED_64 = 1;
exports.LENGTH_DELIMITED = 2;
exports.GROUP_START = 3;
exports.GROUP_END = 4;
exports.FIXED_32 = 5;
+116
View File
@@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MisuseError = exports.InternalError = exports.ProtocolVersionError = exports.LibsqlUrlParseError = exports.HttpServerError = exports.WebSocketError = exports.WebSocketUnsupportedError = exports.ClosedError = exports.ResponseError = exports.ProtoError = exports.ClientError = void 0;
/** Generic error produced by the Hrana client. */
class ClientError extends Error {
/** @private */
constructor(message) {
super(message);
this.name = "ClientError";
}
}
exports.ClientError = ClientError;
/** Error thrown when the server violates the protocol. */
class ProtoError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "ProtoError";
}
}
exports.ProtoError = ProtoError;
/** Error thrown when the server returns an error response. */
class ResponseError extends ClientError {
code;
/** @internal */
proto;
/** @private */
constructor(message, protoError) {
super(message);
this.name = "ResponseError";
this.code = protoError.code;
this.proto = protoError;
this.stack = undefined;
}
}
exports.ResponseError = ResponseError;
/** Error thrown when the client or stream is closed. */
class ClosedError extends ClientError {
/** @private */
constructor(message, cause) {
if (cause !== undefined) {
super(`${message}: ${cause}`);
this.cause = cause;
}
else {
super(message);
}
this.name = "ClosedError";
}
}
exports.ClosedError = ClosedError;
/** Error thrown when the environment does not seem to support WebSockets. */
class WebSocketUnsupportedError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "WebSocketUnsupportedError";
}
}
exports.WebSocketUnsupportedError = WebSocketUnsupportedError;
/** Error thrown when we encounter a WebSocket error. */
class WebSocketError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "WebSocketError";
}
}
exports.WebSocketError = WebSocketError;
/** Error thrown when the HTTP server returns an error response. */
class HttpServerError extends ClientError {
status;
/** @private */
constructor(message, status) {
super(message);
this.status = status;
this.name = "HttpServerError";
}
}
exports.HttpServerError = HttpServerError;
/** Error thrown when a libsql URL is not valid. */
class LibsqlUrlParseError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "LibsqlUrlParseError";
}
}
exports.LibsqlUrlParseError = LibsqlUrlParseError;
/** Error thrown when the protocol version is too low to support a feature. */
class ProtocolVersionError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "ProtocolVersionError";
}
}
exports.ProtocolVersionError = ProtocolVersionError;
/** Error thrown when an internal client error happens. */
class InternalError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "InternalError";
}
}
exports.InternalError = InternalError;
/** Error thrown when the API is misused. */
class MisuseError extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "MisuseError";
}
}
exports.MisuseError = MisuseError;
@@ -0,0 +1,130 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpClient = exports.checkEndpoints = void 0;
const cross_fetch_1 = require("cross-fetch");
const client_js_1 = require("../client.js");
const errors_js_1 = require("../errors.js");
const stream_js_1 = require("./stream.js");
exports.checkEndpoints = [
{
versionPath: "v3-protobuf",
pipelinePath: "v3-protobuf/pipeline",
cursorPath: "v3-protobuf/cursor",
version: 3,
encoding: "protobuf",
},
/*
{
versionPath: "v3",
pipelinePath: "v3/pipeline",
cursorPath: "v3/cursor",
version: 3,
encoding: "json",
},
*/
];
const fallbackEndpoint = {
versionPath: "v2",
pipelinePath: "v2/pipeline",
cursorPath: undefined,
version: 2,
encoding: "json",
};
/** A client for the Hrana protocol over HTTP. */
class HttpClient extends client_js_1.Client {
#url;
#jwt;
#fetch;
#remoteEncryptionKey;
#closed;
#streams;
/** @private */
_endpointPromise;
/** @private */
_endpoint;
/** @private */
constructor(url, jwt, customFetch, remoteEncryptionKey, protocolVersion = 2) {
super();
this.#url = url;
this.#jwt = jwt;
this.#fetch = customFetch ?? cross_fetch_1.fetch;
this.#remoteEncryptionKey = remoteEncryptionKey;
this.#closed = undefined;
this.#streams = new Set();
if (protocolVersion == 3) {
this._endpointPromise = findEndpoint(this.#fetch, this.#url);
this._endpointPromise.then((endpoint) => this._endpoint = endpoint, (error) => this.#setClosed(error));
}
else {
this._endpointPromise = Promise.resolve(fallbackEndpoint);
this._endpointPromise.then((endpoint) => this._endpoint = endpoint, (error) => this.#setClosed(error));
}
}
/** Get the protocol version supported by the server. */
async getVersion() {
if (this._endpoint !== undefined) {
return this._endpoint.version;
}
return (await this._endpointPromise).version;
}
// Make sure that the negotiated version is at least `minVersion`.
/** @private */
_ensureVersion(minVersion, feature) {
if (minVersion <= fallbackEndpoint.version) {
return;
}
else if (this._endpoint === undefined) {
throw new errors_js_1.ProtocolVersionError(`${feature} is supported only on protocol version ${minVersion} and higher, ` +
"but the version supported by the HTTP server is not yet known. " +
"Use Client.getVersion() to wait until the version is available.");
}
else if (this._endpoint.version < minVersion) {
throw new errors_js_1.ProtocolVersionError(`${feature} is supported only on protocol version ${minVersion} and higher, ` +
`but the HTTP server only supports version ${this._endpoint.version}.`);
}
}
/** Open a {@link HttpStream}, a stream for executing SQL statements. */
openStream() {
if (this.#closed !== undefined) {
throw new errors_js_1.ClosedError("Client is closed", this.#closed);
}
const stream = new stream_js_1.HttpStream(this, this.#url, this.#jwt, this.#fetch, this.#remoteEncryptionKey);
this.#streams.add(stream);
return stream;
}
/** @private */
_streamClosed(stream) {
this.#streams.delete(stream);
}
/** Close the client and all its streams. */
close() {
this.#setClosed(new errors_js_1.ClientError("Client was manually closed"));
}
/** True if the client is closed. */
get closed() {
return this.#closed !== undefined;
}
#setClosed(error) {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
for (const stream of Array.from(this.#streams)) {
stream._setClosed(new errors_js_1.ClosedError("Client was closed", error));
}
}
}
exports.HttpClient = HttpClient;
async function findEndpoint(customFetch, clientUrl) {
const fetch = customFetch;
for (const endpoint of exports.checkEndpoints) {
const url = new URL(endpoint.versionPath, clientUrl);
const request = new cross_fetch_1.Request(url.toString(), { method: "GET" });
const response = await fetch(request);
await response.arrayBuffer();
if (response.ok) {
return endpoint;
}
}
return fallbackEndpoint;
}
@@ -0,0 +1,165 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpCursor = void 0;
const byte_queue_js_1 = require("../byte_queue.js");
const cursor_js_1 = require("../cursor.js");
const jsond = __importStar(require("../encoding/json/decode.js"));
const protobufd = __importStar(require("../encoding/protobuf/decode.js"));
const errors_js_1 = require("../errors.js");
const util_js_1 = require("../util.js");
const json_decode_js_1 = require("./json_decode.js");
const protobuf_decode_js_1 = require("./protobuf_decode.js");
const json_decode_js_2 = require("../shared/json_decode.js");
const protobuf_decode_js_2 = require("../shared/protobuf_decode.js");
class HttpCursor extends cursor_js_1.Cursor {
#stream;
#encoding;
#reader;
#queue;
#closed;
#done;
/** @private */
constructor(stream, encoding) {
super();
this.#stream = stream;
this.#encoding = encoding;
this.#reader = undefined;
this.#queue = new byte_queue_js_1.ByteQueue(16 * 1024);
this.#closed = undefined;
this.#done = false;
}
async open(response) {
if (response.body === null) {
throw new errors_js_1.ProtoError("No response body for cursor request");
}
// node-fetch do not fully support WebStream API, especially getReader() function
// see https://github.com/node-fetch/node-fetch/issues/387
// so, we are using async iterator which behaves similarly here instead
this.#reader = response.body[Symbol.asyncIterator]();
const respBody = await this.#nextItem(json_decode_js_1.CursorRespBody, protobuf_decode_js_1.CursorRespBody);
if (respBody === undefined) {
throw new errors_js_1.ProtoError("Empty response to cursor request");
}
return respBody;
}
/** Fetch the next entry from the cursor. */
next() {
return this.#nextItem(json_decode_js_2.CursorEntry, protobuf_decode_js_2.CursorEntry);
}
/** Close the cursor. */
close() {
this._setClosed(new errors_js_1.ClientError("Cursor was manually closed"));
}
/** @private */
_setClosed(error) {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
this.#stream._cursorClosed(this);
if (this.#reader !== undefined) {
this.#reader.return();
}
}
/** True if the cursor is closed. */
get closed() {
return this.#closed !== undefined;
}
async #nextItem(jsonFun, protobufDef) {
for (;;) {
if (this.#done) {
return undefined;
}
else if (this.#closed !== undefined) {
throw new errors_js_1.ClosedError("Cursor is closed", this.#closed);
}
if (this.#encoding === "json") {
const jsonData = this.#parseItemJson();
if (jsonData !== undefined) {
const jsonText = new TextDecoder().decode(jsonData);
const jsonValue = JSON.parse(jsonText);
return jsond.readJsonObject(jsonValue, jsonFun);
}
}
else if (this.#encoding === "protobuf") {
const protobufData = this.#parseItemProtobuf();
if (protobufData !== undefined) {
return protobufd.readProtobufMessage(protobufData, protobufDef);
}
}
else {
throw (0, util_js_1.impossible)(this.#encoding, "Impossible encoding");
}
if (this.#reader === undefined) {
throw new errors_js_1.InternalError("Attempted to read from HTTP cursor before it was opened");
}
const { value, done } = await this.#reader.next();
if (done && this.#queue.length === 0) {
this.#done = true;
}
else if (done) {
throw new errors_js_1.ProtoError("Unexpected end of cursor stream");
}
else {
this.#queue.push(value);
}
}
}
#parseItemJson() {
const data = this.#queue.data();
const newlineByte = 10;
const newlinePos = data.indexOf(newlineByte);
if (newlinePos < 0) {
return undefined;
}
const jsonData = data.slice(0, newlinePos);
this.#queue.shift(newlinePos + 1);
return jsonData;
}
#parseItemProtobuf() {
const data = this.#queue.data();
let varintValue = 0;
let varintLength = 0;
for (;;) {
if (varintLength >= data.byteLength) {
return undefined;
}
const byte = data[varintLength];
varintValue |= (byte & 0x7f) << (7 * varintLength);
varintLength += 1;
if (!(byte & 0x80)) {
break;
}
}
if (data.byteLength < varintLength + varintValue) {
return undefined;
}
const protobufData = data.slice(varintLength, varintLength + varintValue);
this.#queue.shift(varintLength + varintValue);
return protobufData;
}
}
exports.HttpCursor = HttpCursor;
@@ -0,0 +1,90 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorRespBody = exports.PipelineRespBody = void 0;
const errors_js_1 = require("../errors.js");
const d = __importStar(require("../encoding/json/decode.js"));
const json_decode_js_1 = require("../shared/json_decode.js");
function PipelineRespBody(obj) {
const baton = d.stringOpt(obj["baton"]);
const baseUrl = d.stringOpt(obj["base_url"]);
const results = d.arrayObjectsMap(obj["results"], StreamResult);
return { baton, baseUrl, results };
}
exports.PipelineRespBody = PipelineRespBody;
function StreamResult(obj) {
const type = d.string(obj["type"]);
if (type === "ok") {
const response = StreamResponse(d.object(obj["response"]));
return { type: "ok", response };
}
else if (type === "error") {
const error = (0, json_decode_js_1.Error)(d.object(obj["error"]));
return { type: "error", error };
}
else {
throw new errors_js_1.ProtoError("Unexpected type of StreamResult");
}
}
function StreamResponse(obj) {
const type = d.string(obj["type"]);
if (type === "close") {
return { type: "close" };
}
else if (type === "execute") {
const result = (0, json_decode_js_1.StmtResult)(d.object(obj["result"]));
return { type: "execute", result };
}
else if (type === "batch") {
const result = (0, json_decode_js_1.BatchResult)(d.object(obj["result"]));
return { type: "batch", result };
}
else if (type === "sequence") {
return { type: "sequence" };
}
else if (type === "describe") {
const result = (0, json_decode_js_1.DescribeResult)(d.object(obj["result"]));
return { type: "describe", result };
}
else if (type === "store_sql") {
return { type: "store_sql" };
}
else if (type === "close_sql") {
return { type: "close_sql" };
}
else if (type === "get_autocommit") {
const isAutocommit = d.boolean(obj["is_autocommit"]);
return { type: "get_autocommit", isAutocommit };
}
else {
throw new errors_js_1.ProtoError("Unexpected type of StreamResponse");
}
}
function CursorRespBody(obj) {
const baton = d.stringOpt(obj["baton"]);
const baseUrl = d.stringOpt(obj["base_url"]);
return { baton, baseUrl };
}
exports.CursorRespBody = CursorRespBody;
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorReqBody = exports.PipelineReqBody = void 0;
const json_encode_js_1 = require("../shared/json_encode.js");
const util_js_1 = require("../util.js");
function PipelineReqBody(w, msg) {
if (msg.baton !== undefined) {
w.string("baton", msg.baton);
}
w.arrayObjects("requests", msg.requests, StreamRequest);
}
exports.PipelineReqBody = PipelineReqBody;
function StreamRequest(w, msg) {
w.stringRaw("type", msg.type);
if (msg.type === "close") {
// do nothing
}
else if (msg.type === "execute") {
w.object("stmt", msg.stmt, json_encode_js_1.Stmt);
}
else if (msg.type === "batch") {
w.object("batch", msg.batch, json_encode_js_1.Batch);
}
else if (msg.type === "sequence") {
if (msg.sql !== undefined) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== undefined) {
w.number("sql_id", msg.sqlId);
}
}
else if (msg.type === "describe") {
if (msg.sql !== undefined) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== undefined) {
w.number("sql_id", msg.sqlId);
}
}
else if (msg.type === "store_sql") {
w.number("sql_id", msg.sqlId);
w.string("sql", msg.sql);
}
else if (msg.type === "close_sql") {
w.number("sql_id", msg.sqlId);
}
else if (msg.type === "get_autocommit") {
// do nothing
}
else {
throw (0, util_js_1.impossible)(msg, "Impossible type of StreamRequest");
}
}
function CursorReqBody(w, msg) {
if (msg.baton !== undefined) {
w.string("baton", msg.baton);
}
w.object("batch", msg.batch, json_encode_js_1.Batch);
}
exports.CursorReqBody = CursorReqBody;
@@ -0,0 +1,18 @@
"use strict";
// Types for the structures specific to Hrana over HTTP.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("../shared/proto.js"), exports);
@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorRespBody = exports.PipelineRespBody = void 0;
const protobuf_decode_js_1 = require("../shared/protobuf_decode.js");
exports.PipelineRespBody = {
default() { return { baton: undefined, baseUrl: undefined, results: [] }; },
1(r, msg) { msg.baton = r.string(); },
2(r, msg) { msg.baseUrl = r.string(); },
3(r, msg) { msg.results.push(r.message(StreamResult)); },
};
const StreamResult = {
default() { return { type: "none" }; },
1(r) { return { type: "ok", response: r.message(StreamResponse) }; },
2(r) { return { type: "error", error: r.message(protobuf_decode_js_1.Error) }; },
};
const StreamResponse = {
default() { return { type: "none" }; },
1(r) { return { type: "close" }; },
2(r) { return r.message(ExecuteStreamResp); },
3(r) { return r.message(BatchStreamResp); },
4(r) { return { type: "sequence" }; },
5(r) { return r.message(DescribeStreamResp); },
6(r) { return { type: "store_sql" }; },
7(r) { return { type: "close_sql" }; },
8(r) { return r.message(GetAutocommitStreamResp); },
};
const ExecuteStreamResp = {
default() { return { type: "execute", result: protobuf_decode_js_1.StmtResult.default() }; },
1(r, msg) { msg.result = r.message(protobuf_decode_js_1.StmtResult); },
};
const BatchStreamResp = {
default() { return { type: "batch", result: protobuf_decode_js_1.BatchResult.default() }; },
1(r, msg) { msg.result = r.message(protobuf_decode_js_1.BatchResult); },
};
const DescribeStreamResp = {
default() { return { type: "describe", result: protobuf_decode_js_1.DescribeResult.default() }; },
1(r, msg) { msg.result = r.message(protobuf_decode_js_1.DescribeResult); },
};
const GetAutocommitStreamResp = {
default() { return { type: "get_autocommit", isAutocommit: false }; },
1(r, msg) { msg.isAutocommit = r.bool(); },
};
exports.CursorRespBody = {
default() { return { baton: undefined, baseUrl: undefined }; },
1(r, msg) { msg.baton = r.string(); },
2(r, msg) { msg.baseUrl = r.string(); },
};
@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CursorReqBody = exports.PipelineReqBody = void 0;
const protobuf_encode_js_1 = require("../shared/protobuf_encode.js");
const util_js_1 = require("../util.js");
function PipelineReqBody(w, msg) {
if (msg.baton !== undefined) {
w.string(1, msg.baton);
}
for (const req of msg.requests) {
w.message(2, req, StreamRequest);
}
}
exports.PipelineReqBody = PipelineReqBody;
function StreamRequest(w, msg) {
if (msg.type === "close") {
w.message(1, msg, CloseStreamReq);
}
else if (msg.type === "execute") {
w.message(2, msg, ExecuteStreamReq);
}
else if (msg.type === "batch") {
w.message(3, msg, BatchStreamReq);
}
else if (msg.type === "sequence") {
w.message(4, msg, SequenceStreamReq);
}
else if (msg.type === "describe") {
w.message(5, msg, DescribeStreamReq);
}
else if (msg.type === "store_sql") {
w.message(6, msg, StoreSqlStreamReq);
}
else if (msg.type === "close_sql") {
w.message(7, msg, CloseSqlStreamReq);
}
else if (msg.type === "get_autocommit") {
w.message(8, msg, GetAutocommitStreamReq);
}
else {
throw (0, util_js_1.impossible)(msg, "Impossible type of StreamRequest");
}
}
function CloseStreamReq(_w, _msg) {
}
function ExecuteStreamReq(w, msg) {
w.message(1, msg.stmt, protobuf_encode_js_1.Stmt);
}
function BatchStreamReq(w, msg) {
w.message(1, msg.batch, protobuf_encode_js_1.Batch);
}
function SequenceStreamReq(w, msg) {
if (msg.sql !== undefined) {
w.string(1, msg.sql);
}
if (msg.sqlId !== undefined) {
w.int32(2, msg.sqlId);
}
}
function DescribeStreamReq(w, msg) {
if (msg.sql !== undefined) {
w.string(1, msg.sql);
}
if (msg.sqlId !== undefined) {
w.int32(2, msg.sqlId);
}
}
function StoreSqlStreamReq(w, msg) {
w.int32(1, msg.sqlId);
w.string(2, msg.sql);
}
function CloseSqlStreamReq(w, msg) {
w.int32(1, msg.sqlId);
}
function GetAutocommitStreamReq(_w, _msg) {
}
function CursorReqBody(w, msg) {
if (msg.baton !== undefined) {
w.string(1, msg.baton);
}
w.message(2, msg.batch, protobuf_encode_js_1.Batch);
}
exports.CursorReqBody = CursorReqBody;
@@ -0,0 +1,372 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpStream = void 0;
const cross_fetch_1 = require("cross-fetch");
const errors_js_1 = require("../errors.js");
const index_js_1 = require("../encoding/index.js");
const id_alloc_js_1 = require("../id_alloc.js");
const queue_js_1 = require("../queue.js");
const queue_microtask_js_1 = require("../queue_microtask.js");
const result_js_1 = require("../result.js");
const sql_js_1 = require("../sql.js");
const stream_js_1 = require("../stream.js");
const util_js_1 = require("../util.js");
const cursor_js_1 = require("./cursor.js");
const json_encode_js_1 = require("./json_encode.js");
const protobuf_encode_js_1 = require("./protobuf_encode.js");
const json_encode_js_2 = require("./json_encode.js");
const protobuf_encode_js_2 = require("./protobuf_encode.js");
const json_decode_js_1 = require("./json_decode.js");
const protobuf_decode_js_1 = require("./protobuf_decode.js");
class HttpStream extends stream_js_1.Stream {
#client;
#baseUrl;
#jwt;
#fetch;
#remoteEncryptionKey;
#baton;
#queue;
#flushing;
#cursor;
#closing;
#closeQueued;
#closed;
#sqlIdAlloc;
/** @private */
constructor(client, baseUrl, jwt, customFetch, remoteEncryptionKey) {
super(client.intMode);
this.#client = client;
this.#baseUrl = baseUrl.toString();
this.#jwt = jwt;
this.#fetch = customFetch;
this.#remoteEncryptionKey = remoteEncryptionKey;
this.#baton = undefined;
this.#queue = new queue_js_1.Queue();
this.#flushing = false;
this.#closing = false;
this.#closeQueued = false;
this.#closed = undefined;
this.#sqlIdAlloc = new id_alloc_js_1.IdAlloc();
}
/** Get the {@link HttpClient} object that this stream belongs to. */
client() {
return this.#client;
}
/** @private */
_sqlOwner() {
return this;
}
/** Cache a SQL text on the server. */
storeSql(sql) {
const sqlId = this.#sqlIdAlloc.alloc();
this.#sendStreamRequest({ type: "store_sql", sqlId, sql }).then(() => undefined, (error) => this._setClosed(error));
return new sql_js_1.Sql(this, sqlId);
}
/** @private */
_closeSql(sqlId) {
if (this.#closed !== undefined) {
return;
}
this.#sendStreamRequest({ type: "close_sql", sqlId }).then(() => this.#sqlIdAlloc.free(sqlId), (error) => this._setClosed(error));
}
/** @private */
_execute(stmt) {
return this.#sendStreamRequest({ type: "execute", stmt }).then((response) => {
return response.result;
});
}
/** @private */
_batch(batch) {
return this.#sendStreamRequest({ type: "batch", batch }).then((response) => {
return response.result;
});
}
/** @private */
_describe(protoSql) {
return this.#sendStreamRequest({
type: "describe",
sql: protoSql.sql,
sqlId: protoSql.sqlId
}).then((response) => {
return response.result;
});
}
/** @private */
_sequence(protoSql) {
return this.#sendStreamRequest({
type: "sequence",
sql: protoSql.sql,
sqlId: protoSql.sqlId,
}).then((_response) => {
return undefined;
});
}
/** Check whether the SQL connection underlying this stream is in autocommit state (i.e., outside of an
* explicit transaction). This requires protocol version 3 or higher.
*/
getAutocommit() {
this.#client._ensureVersion(3, "getAutocommit()");
return this.#sendStreamRequest({
type: "get_autocommit",
}).then((response) => {
return response.isAutocommit;
});
}
#sendStreamRequest(request) {
return new Promise((responseCallback, errorCallback) => {
this.#pushToQueue({ type: "pipeline", request, responseCallback, errorCallback });
});
}
/** @private */
_openCursor(batch) {
return new Promise((cursorCallback, errorCallback) => {
this.#pushToQueue({ type: "cursor", batch, cursorCallback, errorCallback });
});
}
/** @private */
_cursorClosed(cursor) {
if (cursor !== this.#cursor) {
throw new errors_js_1.InternalError("Cursor was closed, but it was not associated with the stream");
}
this.#cursor = undefined;
(0, queue_microtask_js_1.queueMicrotask)(() => this.#flushQueue());
}
/** Immediately close the stream. */
close() {
this._setClosed(new errors_js_1.ClientError("Stream was manually closed"));
}
/** Gracefully close the stream. */
closeGracefully() {
this.#closing = true;
(0, queue_microtask_js_1.queueMicrotask)(() => this.#flushQueue());
}
/** True if the stream is closed. */
get closed() {
return this.#closed !== undefined || this.#closing;
}
/** @private */
_setClosed(error) {
if (this.#closed !== undefined) {
return;
}
this.#closed = error;
if (this.#cursor !== undefined) {
this.#cursor._setClosed(error);
}
this.#client._streamClosed(this);
for (;;) {
const entry = this.#queue.shift();
if (entry !== undefined) {
entry.errorCallback(error);
}
else {
break;
}
}
if ((this.#baton !== undefined || this.#flushing) && !this.#closeQueued) {
this.#queue.push({
type: "pipeline",
request: { type: "close" },
responseCallback: () => undefined,
errorCallback: () => undefined,
});
this.#closeQueued = true;
(0, queue_microtask_js_1.queueMicrotask)(() => this.#flushQueue());
}
}
#pushToQueue(entry) {
if (this.#closed !== undefined) {
throw new errors_js_1.ClosedError("Stream is closed", this.#closed);
}
else if (this.#closing) {
throw new errors_js_1.ClosedError("Stream is closing", undefined);
}
else {
this.#queue.push(entry);
(0, queue_microtask_js_1.queueMicrotask)(() => this.#flushQueue());
}
}
#flushQueue() {
if (this.#flushing || this.#cursor !== undefined) {
return;
}
if (this.#closing && this.#queue.length === 0) {
this._setClosed(new errors_js_1.ClientError("Stream was gracefully closed"));
return;
}
const endpoint = this.#client._endpoint;
if (endpoint === undefined) {
this.#client._endpointPromise.then(() => this.#flushQueue(), (error) => this._setClosed(error));
return;
}
const firstEntry = this.#queue.shift();
if (firstEntry === undefined) {
return;
}
else if (firstEntry.type === "pipeline") {
const pipeline = [firstEntry];
for (;;) {
const entry = this.#queue.first();
if (entry !== undefined && entry.type === "pipeline") {
pipeline.push(entry);
this.#queue.shift();
}
else if (entry === undefined && this.#closing && !this.#closeQueued) {
pipeline.push({
type: "pipeline",
request: { type: "close" },
responseCallback: () => undefined,
errorCallback: () => undefined,
});
this.#closeQueued = true;
break;
}
else {
break;
}
}
this.#flushPipeline(endpoint, pipeline);
}
else if (firstEntry.type === "cursor") {
this.#flushCursor(endpoint, firstEntry);
}
else {
throw (0, util_js_1.impossible)(firstEntry, "Impossible type of QueueEntry");
}
}
#flushPipeline(endpoint, pipeline) {
this.#flush(() => this.#createPipelineRequest(pipeline, endpoint), (resp) => decodePipelineResponse(resp, endpoint.encoding), (respBody) => respBody.baton, (respBody) => respBody.baseUrl, (respBody) => handlePipelineResponse(pipeline, respBody), (error) => pipeline.forEach((entry) => entry.errorCallback(error)));
}
#flushCursor(endpoint, entry) {
const cursor = new cursor_js_1.HttpCursor(this, endpoint.encoding);
this.#cursor = cursor;
this.#flush(() => this.#createCursorRequest(entry, endpoint), (resp) => cursor.open(resp), (respBody) => respBody.baton, (respBody) => respBody.baseUrl, (_respBody) => entry.cursorCallback(cursor), (error) => entry.errorCallback(error));
}
#flush(createRequest, decodeResponse, getBaton, getBaseUrl, handleResponse, handleError) {
let promise;
try {
const request = createRequest();
const fetch = this.#fetch;
promise = fetch(request);
}
catch (error) {
promise = Promise.reject(error);
}
this.#flushing = true;
promise.then((resp) => {
if (!resp.ok) {
return errorFromResponse(resp).then((error) => {
throw error;
});
}
return decodeResponse(resp);
}).then((r) => {
this.#baton = getBaton(r);
this.#baseUrl = getBaseUrl(r) ?? this.#baseUrl;
handleResponse(r);
}).catch((error) => {
this._setClosed(error);
handleError(error);
}).finally(() => {
this.#flushing = false;
this.#flushQueue();
});
}
#createPipelineRequest(pipeline, endpoint) {
return this.#createRequest(new URL(endpoint.pipelinePath, this.#baseUrl), {
baton: this.#baton,
requests: pipeline.map((entry) => entry.request),
}, endpoint.encoding, json_encode_js_1.PipelineReqBody, protobuf_encode_js_1.PipelineReqBody);
}
#createCursorRequest(entry, endpoint) {
if (endpoint.cursorPath === undefined) {
throw new errors_js_1.ProtocolVersionError("Cursors are supported only on protocol version 3 and higher, " +
`but the HTTP server only supports version ${endpoint.version}.`);
}
return this.#createRequest(new URL(endpoint.cursorPath, this.#baseUrl), {
baton: this.#baton,
batch: entry.batch,
}, endpoint.encoding, json_encode_js_2.CursorReqBody, protobuf_encode_js_2.CursorReqBody);
}
#createRequest(url, reqBody, encoding, jsonFun, protobufFun) {
let bodyData;
let contentType;
if (encoding === "json") {
bodyData = (0, index_js_1.writeJsonObject)(reqBody, jsonFun);
contentType = "application/json";
}
else if (encoding === "protobuf") {
bodyData = (0, index_js_1.writeProtobufMessage)(reqBody, protobufFun);
contentType = "application/x-protobuf";
}
else {
throw (0, util_js_1.impossible)(encoding, "Impossible encoding");
}
const headers = new cross_fetch_1.Headers();
headers.set("content-type", contentType);
if (this.#jwt !== undefined) {
headers.set("authorization", `Bearer ${this.#jwt}`);
}
if (this.#remoteEncryptionKey !== undefined) {
headers.set("x-turso-encryption-key", this.#remoteEncryptionKey);
}
return new cross_fetch_1.Request(url.toString(), { method: "POST", headers, body: bodyData });
}
}
exports.HttpStream = HttpStream;
function handlePipelineResponse(pipeline, respBody) {
if (respBody.results.length !== pipeline.length) {
throw new errors_js_1.ProtoError("Server returned unexpected number of pipeline results");
}
for (let i = 0; i < pipeline.length; ++i) {
const result = respBody.results[i];
const entry = pipeline[i];
if (result.type === "ok") {
if (result.response.type !== entry.request.type) {
throw new errors_js_1.ProtoError("Received unexpected type of response");
}
entry.responseCallback(result.response);
}
else if (result.type === "error") {
entry.errorCallback((0, result_js_1.errorFromProto)(result.error));
}
else if (result.type === "none") {
throw new errors_js_1.ProtoError("Received unrecognized type of StreamResult");
}
else {
throw (0, util_js_1.impossible)(result, "Received impossible type of StreamResult");
}
}
}
async function decodePipelineResponse(resp, encoding) {
if (encoding === "json") {
const respJson = await resp.json();
return (0, index_js_1.readJsonObject)(respJson, json_decode_js_1.PipelineRespBody);
}
if (encoding === "protobuf") {
const respData = await resp.arrayBuffer();
return (0, index_js_1.readProtobufMessage)(new Uint8Array(respData), protobuf_decode_js_1.PipelineRespBody);
}
await resp.body?.cancel();
throw (0, util_js_1.impossible)(encoding, "Impossible encoding");
}
async function errorFromResponse(resp) {
const respType = resp.headers.get("content-type") ?? "text/plain";
let message = `Server returned HTTP status ${resp.status}`;
if (respType === "application/json") {
const respBody = await resp.json();
if ("message" in respBody) {
return (0, result_js_1.errorFromProto)(respBody);
}
return new errors_js_1.HttpServerError(message, resp.status);
}
if (respType === "text/plain") {
const respBody = (await resp.text()).trim();
if (respBody !== "") {
message += `: ${respBody}`;
}
return new errors_js_1.HttpServerError(message, resp.status);
}
await resp.body?.cancel();
return new errors_js_1.HttpServerError(message, resp.status);
}
@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IdAlloc = void 0;
const errors_js_1 = require("./errors.js");
// An allocator of non-negative integer ids.
//
// This clever data structure has these "ideal" properties:
// - It consumes memory proportional to the number of used ids (which is optimal).
// - All operations are O(1) time.
// - The allocated ids are small (with a slight modification, we could always provide the smallest possible
// id).
class IdAlloc {
// Set of all allocated ids
#usedIds;
// Set of all free ids lower than `#usedIds.size`
#freeIds;
constructor() {
this.#usedIds = new Set();
this.#freeIds = new Set();
}
// Returns an id that was free, and marks it as used.
alloc() {
// this "loop" is just a way to pick an arbitrary element from the `#freeIds` set
for (const freeId of this.#freeIds) {
this.#freeIds.delete(freeId);
this.#usedIds.add(freeId);
// maintain the invariant of `#freeIds`
if (!this.#usedIds.has(this.#usedIds.size - 1)) {
this.#freeIds.add(this.#usedIds.size - 1);
}
return freeId;
}
// the `#freeIds` set is empty, so there are no free ids lower than `#usedIds.size`
// this means that `#usedIds` is a set that contains all numbers from 0 to `#usedIds.size - 1`,
// so `#usedIds.size` is free
const freeId = this.#usedIds.size;
this.#usedIds.add(freeId);
return freeId;
}
free(id) {
if (!this.#usedIds.delete(id)) {
throw new errors_js_1.InternalError("Freeing an id that is not allocated");
}
// maintain the invariant of `#freeIds`
this.#freeIds.delete(this.#usedIds.size);
if (id < this.#usedIds.size) {
this.#freeIds.add(id);
}
}
}
exports.IdAlloc = IdAlloc;
+77
View File
@@ -0,0 +1,77 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.openHttp = exports.openWs = exports.WsStream = exports.WsClient = exports.HttpStream = exports.HttpClient = exports.Stream = exports.Stmt = exports.Sql = exports.parseLibsqlUrl = exports.BatchCond = exports.BatchStep = exports.Batch = exports.Client = exports.Headers = exports.Request = exports.fetch = exports.WebSocket = void 0;
const isomorphic_ws_1 = require("@libsql/isomorphic-ws");
const client_js_1 = require("./ws/client.js");
const errors_js_1 = require("./errors.js");
const client_js_2 = require("./http/client.js");
const client_js_3 = require("./ws/client.js");
var isomorphic_ws_2 = require("@libsql/isomorphic-ws");
Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function () { return isomorphic_ws_2.WebSocket; } });
var cross_fetch_1 = require("cross-fetch");
Object.defineProperty(exports, "fetch", { enumerable: true, get: function () { return cross_fetch_1.fetch; } });
Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return cross_fetch_1.Request; } });
Object.defineProperty(exports, "Headers", { enumerable: true, get: function () { return cross_fetch_1.Headers; } });
var client_js_4 = require("./client.js");
Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_js_4.Client; } });
__exportStar(require("./errors.js"), exports);
var batch_js_1 = require("./batch.js");
Object.defineProperty(exports, "Batch", { enumerable: true, get: function () { return batch_js_1.Batch; } });
Object.defineProperty(exports, "BatchStep", { enumerable: true, get: function () { return batch_js_1.BatchStep; } });
Object.defineProperty(exports, "BatchCond", { enumerable: true, get: function () { return batch_js_1.BatchCond; } });
var libsql_url_js_1 = require("./libsql_url.js");
Object.defineProperty(exports, "parseLibsqlUrl", { enumerable: true, get: function () { return libsql_url_js_1.parseLibsqlUrl; } });
var sql_js_1 = require("./sql.js");
Object.defineProperty(exports, "Sql", { enumerable: true, get: function () { return sql_js_1.Sql; } });
var stmt_js_1 = require("./stmt.js");
Object.defineProperty(exports, "Stmt", { enumerable: true, get: function () { return stmt_js_1.Stmt; } });
var stream_js_1 = require("./stream.js");
Object.defineProperty(exports, "Stream", { enumerable: true, get: function () { return stream_js_1.Stream; } });
var client_js_5 = require("./http/client.js");
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return client_js_5.HttpClient; } });
var stream_js_2 = require("./http/stream.js");
Object.defineProperty(exports, "HttpStream", { enumerable: true, get: function () { return stream_js_2.HttpStream; } });
var client_js_6 = require("./ws/client.js");
Object.defineProperty(exports, "WsClient", { enumerable: true, get: function () { return client_js_6.WsClient; } });
var stream_js_3 = require("./ws/stream.js");
Object.defineProperty(exports, "WsStream", { enumerable: true, get: function () { return stream_js_3.WsStream; } });
/** Open a Hrana client over WebSocket connected to the given `url`. */
function openWs(url, jwt, protocolVersion = 2) {
if (typeof isomorphic_ws_1.WebSocket === "undefined") {
throw new errors_js_1.WebSocketUnsupportedError("WebSockets are not supported in this environment");
}
var subprotocols = undefined;
if (protocolVersion == 3) {
subprotocols = Array.from(client_js_1.subprotocolsV3.keys());
}
else {
subprotocols = Array.from(client_js_1.subprotocolsV2.keys());
}
const socket = new isomorphic_ws_1.WebSocket(url, subprotocols);
return new client_js_3.WsClient(socket, jwt);
}
exports.openWs = openWs;
/** Open a Hrana client over HTTP connected to the given `url`.
*
* If the `customFetch` argument is passed and not `undefined`, it is used in place of the `fetch` function
* from `cross-fetch`. This function is always called with a `Request` object from
* `cross-fetch`.
*/
function openHttp(url, jwt, customFetch, remoteEncryptionKey, protocolVersion = 2) {
return new client_js_2.HttpClient(url instanceof URL ? url : new URL(url), jwt, customFetch, remoteEncryptionKey, protocolVersion);
}
exports.openHttp = openHttp;
@@ -0,0 +1,79 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseLibsqlUrl = void 0;
const errors_js_1 = require("./errors.js");
;
/** Parses a URL compatible with the libsql client (`@libsql/client`). This URL may have the "libsql:" scheme
* and may contain query parameters. */
function parseLibsqlUrl(urlStr) {
const url = new URL(urlStr);
let authToken = undefined;
let tls = undefined;
for (const [key, value] of url.searchParams.entries()) {
if (key === "authToken") {
authToken = value;
}
else if (key === "tls") {
if (value === "0") {
tls = false;
}
else if (value === "1") {
tls = true;
}
else {
throw new errors_js_1.LibsqlUrlParseError(`Unknown value for the "tls" query argument: ${JSON.stringify(value)}`);
}
}
else {
throw new errors_js_1.LibsqlUrlParseError(`Unknown URL query argument ${JSON.stringify(key)}`);
}
}
let hranaWsScheme;
let hranaHttpScheme;
if ((url.protocol === "http:" || url.protocol === "ws:") && (tls === true)) {
throw new errors_js_1.LibsqlUrlParseError(`A ${JSON.stringify(url.protocol)} URL cannot opt into TLS using ?tls=1`);
}
else if ((url.protocol === "https:" || url.protocol === "wss:") && (tls === false)) {
throw new errors_js_1.LibsqlUrlParseError(`A ${JSON.stringify(url.protocol)} URL cannot opt out of TLS using ?tls=0`);
}
if (url.protocol === "http:" || url.protocol === "https:") {
hranaHttpScheme = url.protocol;
}
else if (url.protocol === "ws:" || url.protocol === "wss:") {
hranaWsScheme = url.protocol;
}
else if (url.protocol === "libsql:") {
if (tls === false) {
if (!url.port) {
throw new errors_js_1.LibsqlUrlParseError(`A "libsql:" URL with ?tls=0 must specify an explicit port`);
}
hranaHttpScheme = "http:";
hranaWsScheme = "ws:";
}
else {
hranaHttpScheme = "https:";
hranaWsScheme = "wss:";
}
}
else {
throw new errors_js_1.LibsqlUrlParseError(`This client does not support ${JSON.stringify(url.protocol)} URLs. ` +
'Please use a "libsql:", "ws:", "wss:", "http:" or "https:" URL instead.');
}
if (url.username || url.password) {
throw new errors_js_1.LibsqlUrlParseError("This client does not support HTTP Basic authentication with a username and password. " +
'You can authenticate using a token passed in the "authToken" URL query parameter.');
}
if (url.hash) {
throw new errors_js_1.LibsqlUrlParseError("URL fragments are not supported");
}
let hranaPath = url.pathname;
if (hranaPath === "/") {
hranaPath = "";
}
const hranaWsUrl = hranaWsScheme !== undefined
? `${hranaWsScheme}//${url.host}${hranaPath}` : undefined;
const hranaHttpUrl = hranaHttpScheme !== undefined
? `${hranaHttpScheme}//${url.host}${hranaPath}` : undefined;
return { hranaWsUrl, hranaHttpUrl, authToken };
}
exports.parseLibsqlUrl = parseLibsqlUrl;
Loaded 100 of 3282 files, more files were not shown because too many files have changed in this diff. Show more