Files
vmail/docs/email-worker-source.js
T
2024-04-09 09:58:53 +08:00

17910 lines
513 KiB
JavaScript

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) =>
key in obj
? __defProp(obj, key, {
enumerable: true,
configurable: true,
writable: true,
value,
})
: (obj[key] = value);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/entity.js
var entityKind = Symbol.for("drizzle:entityKind");
var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
function is(value, type) {
if (!value || typeof value !== "object") {
return false;
}
if (value instanceof type) {
return true;
}
if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
throw new Error(
`Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
);
}
let cls = value.constructor;
if (cls) {
while (cls) {
if (entityKind in cls && cls[entityKind] === type[entityKind]) {
return true;
}
cls = Object.getPrototypeOf(cls);
}
}
return false;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/column.js
var _a;
var Column = class {
constructor(table, config) {
this.table = table;
this.config = config;
this.name = config.name;
this.notNull = config.notNull;
this.default = config.default;
this.defaultFn = config.defaultFn;
this.hasDefault = config.hasDefault;
this.primary = config.primaryKey;
this.isUnique = config.isUnique;
this.uniqueName = config.uniqueName;
this.uniqueType = config.uniqueType;
this.dataType = config.dataType;
this.columnType = config.columnType;
}
name;
primary;
notNull;
default;
defaultFn;
hasDefault;
isUnique;
uniqueName;
uniqueType;
dataType;
columnType;
enumValues = void 0;
config;
mapFromDriverValue(value) {
return value;
}
mapToDriverValue(value) {
return value;
}
};
_a = entityKind;
__publicField(Column, _a, "Column");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/table.js
var TableName = Symbol.for("drizzle:Name");
var Schema = Symbol.for("drizzle:Schema");
var Columns = Symbol.for("drizzle:Columns");
var OriginalName = Symbol.for("drizzle:OriginalName");
var BaseName = Symbol.for("drizzle:BaseName");
var IsAlias = Symbol.for("drizzle:IsAlias");
var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
var _a2;
var Table = class {
/**
* @internal
* Can be changed if the table is aliased.
*/
[((_a2 = entityKind), TableName)];
/**
* @internal
* Used to store the original name of the table, before any aliasing.
*/
[OriginalName];
/** @internal */
[Schema];
/** @internal */
[Columns];
/**
* @internal
* Used to store the table name before the transformation via the `tableCreator` functions.
*/
[BaseName];
/** @internal */
[IsAlias] = false;
/** @internal */
[ExtraConfigBuilder] = void 0;
[IsDrizzleTable] = true;
constructor(name, schema, baseName) {
this[TableName] = this[OriginalName] = name;
this[Schema] = schema;
this[BaseName] = baseName;
}
};
__publicField(Table, _a2, "Table");
/** @internal */
__publicField(Table, "Symbol", {
Name: TableName,
Schema,
OriginalName,
Columns,
BaseName,
IsAlias,
ExtraConfigBuilder,
});
function isTable(table) {
return typeof table === "object" && table !== null && IsDrizzleTable in table;
}
function getTableName(table) {
return table[TableName];
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/table.js
var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
var _a3;
var PgTable = class extends Table {
/**@internal */
[((_a3 = entityKind), InlineForeignKeys)] = [];
/** @internal */
[Table.Symbol.ExtraConfigBuilder] = void 0;
};
__publicField(PgTable, _a3, "PgTable");
/** @internal */
__publicField(
PgTable,
"Symbol",
Object.assign({}, Table.Symbol, {
InlineForeignKeys,
})
);
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/primary-keys.js
var _a4;
var PrimaryKeyBuilder = class {
/** @internal */
columns;
/** @internal */
name;
constructor(columns, name) {
this.columns = columns;
this.name = name;
}
/** @internal */
build(table) {
return new PrimaryKey(table, this.columns, this.name);
}
};
_a4 = entityKind;
__publicField(PrimaryKeyBuilder, _a4, "PgPrimaryKeyBuilder");
var _a5;
var PrimaryKey = class {
constructor(table, columns, name) {
this.table = table;
this.columns = columns;
this.name = name;
}
columns;
name;
getName() {
return (
this.name ??
`${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`
);
}
};
_a5 = entityKind;
__publicField(PrimaryKey, _a5, "PgPrimaryKey");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sql/expressions/conditions.js
function bindIfParam(value, column) {
if (
isDriverValueEncoder(column) &&
!isSQLWrapper(value) &&
!is(value, Param) &&
!is(value, Placeholder) &&
!is(value, Column) &&
!is(value, Table) &&
!is(value, View)
) {
return new Param(value, column);
}
return value;
}
var eq = (left, right) => {
return sql`${left} = ${bindIfParam(right, left)}`;
};
var ne = (left, right) => {
return sql`${left} <> ${bindIfParam(right, left)}`;
};
function and(...unfilteredConditions) {
const conditions = unfilteredConditions.filter((c2) => c2 !== void 0);
if (conditions.length === 0) {
return void 0;
}
if (conditions.length === 1) {
return new SQL(conditions);
}
return new SQL([
new StringChunk("("),
sql.join(conditions, new StringChunk(" and ")),
new StringChunk(")"),
]);
}
function or(...unfilteredConditions) {
const conditions = unfilteredConditions.filter((c2) => c2 !== void 0);
if (conditions.length === 0) {
return void 0;
}
if (conditions.length === 1) {
return new SQL(conditions);
}
return new SQL([
new StringChunk("("),
sql.join(conditions, new StringChunk(" or ")),
new StringChunk(")"),
]);
}
function not(condition) {
return sql`not ${condition}`;
}
var gt = (left, right) => {
return sql`${left} > ${bindIfParam(right, left)}`;
};
var gte = (left, right) => {
return sql`${left} >= ${bindIfParam(right, left)}`;
};
var lt = (left, right) => {
return sql`${left} < ${bindIfParam(right, left)}`;
};
var lte = (left, right) => {
return sql`${left} <= ${bindIfParam(right, left)}`;
};
function inArray(column, values) {
if (Array.isArray(values)) {
if (values.length === 0) {
throw new Error("inArray requires at least one value");
}
return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;
}
return sql`${column} in ${bindIfParam(values, column)}`;
}
function notInArray(column, values) {
if (Array.isArray(values)) {
if (values.length === 0) {
throw new Error("notInArray requires at least one value");
}
return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;
}
return sql`${column} not in ${bindIfParam(values, column)}`;
}
function isNull(value) {
return sql`${value} is null`;
}
function isNotNull(value) {
return sql`${value} is not null`;
}
function exists(subquery) {
return sql`exists ${subquery}`;
}
function notExists(subquery) {
return sql`not exists ${subquery}`;
}
function between(column, min, max) {
return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(
max,
column
)}`;
}
function notBetween(column, min, max) {
return sql`${column} not between ${bindIfParam(
min,
column
)} and ${bindIfParam(max, column)}`;
}
function like(column, value) {
return sql`${column} like ${value}`;
}
function notLike(column, value) {
return sql`${column} not like ${value}`;
}
function ilike(column, value) {
return sql`${column} ilike ${value}`;
}
function notIlike(column, value) {
return sql`${column} not ilike ${value}`;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sql/expressions/select.js
function asc(column) {
return sql`${column} asc`;
}
function desc(column) {
return sql`${column} desc`;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/relations.js
var _a6;
var Relation = class {
constructor(sourceTable, referencedTable, relationName) {
this.sourceTable = sourceTable;
this.referencedTable = referencedTable;
this.relationName = relationName;
this.referencedTableName = referencedTable[Table.Symbol.Name];
}
referencedTableName;
fieldName;
};
_a6 = entityKind;
__publicField(Relation, _a6, "Relation");
var _a7;
var Relations = class {
constructor(table, config) {
this.table = table;
this.config = config;
}
};
_a7 = entityKind;
__publicField(Relations, _a7, "Relations");
var _a8;
var _One = class extends Relation {
constructor(sourceTable, referencedTable, config, isNullable) {
super(sourceTable, referencedTable, config?.relationName);
this.config = config;
this.isNullable = isNullable;
}
withFieldName(fieldName) {
const relation = new _One(
this.sourceTable,
this.referencedTable,
this.config,
this.isNullable
);
relation.fieldName = fieldName;
return relation;
}
};
var One = _One;
_a8 = entityKind;
__publicField(One, _a8, "One");
var _a9;
var _Many = class extends Relation {
constructor(sourceTable, referencedTable, config) {
super(sourceTable, referencedTable, config?.relationName);
this.config = config;
}
withFieldName(fieldName) {
const relation = new _Many(
this.sourceTable,
this.referencedTable,
this.config
);
relation.fieldName = fieldName;
return relation;
}
};
var Many = _Many;
_a9 = entityKind;
__publicField(Many, _a9, "Many");
function getOperators() {
return {
and,
between,
eq,
exists,
gt,
gte,
ilike,
inArray,
isNull,
isNotNull,
like,
lt,
lte,
ne,
not,
notBetween,
notExists,
notLike,
notIlike,
notInArray,
or,
sql,
};
}
function getOrderByOperators() {
return {
sql,
asc,
desc,
};
}
function extractTablesRelationalConfig(schema, configHelpers) {
if (
Object.keys(schema).length === 1 &&
"default" in schema &&
!is(schema["default"], Table)
) {
schema = schema["default"];
}
const tableNamesMap = {};
const relationsBuffer = {};
const tablesConfig = {};
for (const [key, value] of Object.entries(schema)) {
if (isTable(value)) {
const dbName = value[Table.Symbol.Name];
const bufferedRelations = relationsBuffer[dbName];
tableNamesMap[dbName] = key;
tablesConfig[key] = {
tsName: key,
dbName: value[Table.Symbol.Name],
schema: value[Table.Symbol.Schema],
columns: value[Table.Symbol.Columns],
relations: bufferedRelations?.relations ?? {},
primaryKey: bufferedRelations?.primaryKey ?? [],
};
for (const column of Object.values(value[Table.Symbol.Columns])) {
if (column.primary) {
tablesConfig[key].primaryKey.push(column);
}
}
const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value);
if (extraConfig) {
for (const configEntry of Object.values(extraConfig)) {
if (is(configEntry, PrimaryKeyBuilder)) {
tablesConfig[key].primaryKey.push(...configEntry.columns);
}
}
}
} else if (is(value, Relations)) {
const dbName = value.table[Table.Symbol.Name];
const tableName = tableNamesMap[dbName];
const relations2 = value.config(configHelpers(value.table));
let primaryKey;
for (const [relationName, relation] of Object.entries(relations2)) {
if (tableName) {
const tableConfig = tablesConfig[tableName];
tableConfig.relations[relationName] = relation;
if (primaryKey) {
tableConfig.primaryKey.push(...primaryKey);
}
} else {
if (!(dbName in relationsBuffer)) {
relationsBuffer[dbName] = {
relations: {},
primaryKey,
};
}
relationsBuffer[dbName].relations[relationName] = relation;
}
}
}
}
return { tables: tablesConfig, tableNamesMap };
}
function createOne(sourceTable) {
return function one(table, config) {
return new One(
sourceTable,
table,
config,
config?.fields.reduce((res, f2) => res && f2.notNull, true) ?? false
);
};
}
function createMany(sourceTable) {
return function many(referencedTable, config) {
return new Many(sourceTable, referencedTable, config);
};
}
function normalizeRelation(schema, tableNamesMap, relation) {
if (is(relation, One) && relation.config) {
return {
fields: relation.config.fields,
references: relation.config.references,
};
}
const referencedTableTsName =
tableNamesMap[relation.referencedTable[Table.Symbol.Name]];
if (!referencedTableTsName) {
throw new Error(
`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`
);
}
const referencedTableConfig = schema[referencedTableTsName];
if (!referencedTableConfig) {
throw new Error(`Table "${referencedTableTsName}" not found in schema`);
}
const sourceTable = relation.sourceTable;
const sourceTableTsName = tableNamesMap[sourceTable[Table.Symbol.Name]];
if (!sourceTableTsName) {
throw new Error(
`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`
);
}
const reverseRelations = [];
for (const referencedTableRelation of Object.values(
referencedTableConfig.relations
)) {
if (
(relation.relationName &&
relation !== referencedTableRelation &&
referencedTableRelation.relationName === relation.relationName) ||
(!relation.relationName &&
referencedTableRelation.referencedTable === relation.sourceTable)
) {
reverseRelations.push(referencedTableRelation);
}
}
if (reverseRelations.length > 1) {
throw relation.relationName
? new Error(
`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
)
: new Error(
`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`
);
}
if (
reverseRelations[0] &&
is(reverseRelations[0], One) &&
reverseRelations[0].config
) {
return {
fields: reverseRelations[0].config.references,
references: reverseRelations[0].config.fields,
};
}
throw new Error(
`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
);
}
function createTableRelationsHelpers(sourceTable) {
return {
one: createOne(sourceTable),
many: createMany(sourceTable),
};
}
function mapRelationalRow(
tablesConfig,
tableConfig,
row,
buildQueryResultSelection,
mapColumnValue = (value) => value
) {
const result = {};
for (const [
selectionItemIndex,
selectionItem,
] of buildQueryResultSelection.entries()) {
if (selectionItem.isJson) {
const relation = tableConfig.relations[selectionItem.tsKey];
const rawSubRows = row[selectionItemIndex];
const subRows =
typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
result[selectionItem.tsKey] = is(relation, One)
? subRows &&
mapRelationalRow(
tablesConfig,
tablesConfig[selectionItem.relationTableTsKey],
subRows,
selectionItem.selection,
mapColumnValue
)
: subRows.map((subRow) =>
mapRelationalRow(
tablesConfig,
tablesConfig[selectionItem.relationTableTsKey],
subRow,
selectionItem.selection,
mapColumnValue
)
);
} else {
const value = mapColumnValue(row[selectionItemIndex]);
const field = selectionItem.field;
let decoder;
if (is(field, Column)) {
decoder = field;
} else if (is(field, SQL)) {
decoder = field.decoder;
} else {
decoder = field.sql.decoder;
}
result[selectionItem.tsKey] =
value === null ? null : decoder.mapFromDriverValue(value);
}
}
return result;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/subquery.js
var SubqueryConfig = Symbol.for("drizzle:SubqueryConfig");
var _a10;
var Subquery = class {
/** @internal */
[((_a10 = entityKind), SubqueryConfig)];
constructor(sql2, selection, alias, isWith = false) {
this[SubqueryConfig] = {
sql: sql2,
selection,
alias,
isWith,
};
}
// getSQL(): SQL<unknown> {
// return new SQL([this]);
// }
};
__publicField(Subquery, _a10, "Subquery");
var _a11;
var WithSubquery = class extends Subquery {};
_a11 = entityKind;
__publicField(WithSubquery, _a11, "WithSubquery");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/tracing-utils.js
function iife(fn, ...args) {
return fn(...args);
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/version.js
var version = "0.29.3";
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/tracing.js
var otel;
var rawTracer;
var tracer = {
startActiveSpan(name, fn) {
if (!otel) {
return fn();
}
if (!rawTracer) {
rawTracer = otel.trace.getTracer("drizzle-orm", version);
}
return iife(
(otel2, rawTracer2) =>
rawTracer2.startActiveSpan(name, (span) => {
try {
return fn(span);
} catch (e) {
span.setStatus({
code: otel2.SpanStatusCode.ERROR,
message: e instanceof Error ? e.message : "Unknown error",
// eslint-disable-line no-instanceof/no-instanceof
});
throw e;
} finally {
span.end();
}
}),
otel,
rawTracer
);
},
};
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/view-common.js
var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sql/sql.js
var _a12;
var FakePrimitiveParam = class {};
_a12 = entityKind;
__publicField(FakePrimitiveParam, _a12, "FakePrimitiveParam");
function isSQLWrapper(value) {
return (
typeof value === "object" &&
value !== null &&
"getSQL" in value &&
typeof value.getSQL === "function"
);
}
function mergeQueries(queries) {
const result = { sql: "", params: [] };
for (const query of queries) {
result.sql += query.sql;
result.params.push(...query.params);
if (query.typings?.length) {
if (!result.typings) {
result.typings = [];
}
result.typings.push(...query.typings);
}
}
return result;
}
var _a13;
var StringChunk = class {
value;
constructor(value) {
this.value = Array.isArray(value) ? value : [value];
}
getSQL() {
return new SQL([this]);
}
};
_a13 = entityKind;
__publicField(StringChunk, _a13, "StringChunk");
var _a14;
var _SQL = class {
constructor(queryChunks) {
this.queryChunks = queryChunks;
}
/** @internal */
decoder = noopDecoder;
shouldInlineParams = false;
append(query) {
this.queryChunks.push(...query.queryChunks);
return this;
}
toQuery(config) {
return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
const query = this.buildQueryFromSourceParams(this.queryChunks, config);
span?.setAttributes({
"drizzle.query.text": query.sql,
"drizzle.query.params": JSON.stringify(query.params),
});
return query;
});
}
buildQueryFromSourceParams(chunks, _config) {
const config = Object.assign({}, _config, {
inlineParams: _config.inlineParams || this.shouldInlineParams,
paramStartIndex: _config.paramStartIndex || { value: 0 },
});
const {
escapeName,
escapeParam,
prepareTyping,
inlineParams,
paramStartIndex,
} = config;
return mergeQueries(
chunks.map((chunk) => {
if (is(chunk, StringChunk)) {
return { sql: chunk.value.join(""), params: [] };
}
if (is(chunk, Name)) {
return { sql: escapeName(chunk.value), params: [] };
}
if (chunk === void 0) {
return { sql: "", params: [] };
}
if (Array.isArray(chunk)) {
const result = [new StringChunk("(")];
for (const [i, p2] of chunk.entries()) {
result.push(p2);
if (i < chunk.length - 1) {
result.push(new StringChunk(", "));
}
}
result.push(new StringChunk(")"));
return this.buildQueryFromSourceParams(result, config);
}
if (is(chunk, _SQL)) {
return this.buildQueryFromSourceParams(chunk.queryChunks, {
...config,
inlineParams: inlineParams || chunk.shouldInlineParams,
});
}
if (is(chunk, Table)) {
const schemaName = chunk[Table.Symbol.Schema];
const tableName = chunk[Table.Symbol.Name];
return {
sql:
schemaName === void 0
? escapeName(tableName)
: escapeName(schemaName) + "." + escapeName(tableName),
params: [],
};
}
if (is(chunk, Column)) {
return {
sql:
escapeName(chunk.table[Table.Symbol.Name]) +
"." +
escapeName(chunk.name),
params: [],
};
}
if (is(chunk, View)) {
const schemaName = chunk[ViewBaseConfig].schema;
const viewName = chunk[ViewBaseConfig].name;
return {
sql:
schemaName === void 0
? escapeName(viewName)
: escapeName(schemaName) + "." + escapeName(viewName),
params: [],
};
}
if (is(chunk, Param)) {
const mappedValue =
chunk.value === null
? null
: chunk.encoder.mapToDriverValue(chunk.value);
if (is(mappedValue, _SQL)) {
return this.buildQueryFromSourceParams([mappedValue], config);
}
if (inlineParams) {
return {
sql: this.mapInlineParam(mappedValue, config),
params: [],
};
}
let typings;
if (prepareTyping !== void 0) {
typings = [prepareTyping(chunk.encoder)];
}
return {
sql: escapeParam(paramStartIndex.value++, mappedValue),
params: [mappedValue],
typings,
};
}
if (is(chunk, Placeholder)) {
return {
sql: escapeParam(paramStartIndex.value++, chunk),
params: [chunk],
};
}
if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) {
return { sql: escapeName(chunk.fieldAlias), params: [] };
}
if (is(chunk, Subquery)) {
if (chunk[SubqueryConfig].isWith) {
return { sql: escapeName(chunk[SubqueryConfig].alias), params: [] };
}
return this.buildQueryFromSourceParams(
[
new StringChunk("("),
chunk[SubqueryConfig].sql,
new StringChunk(") "),
new Name(chunk[SubqueryConfig].alias),
],
config
);
}
if (isSQLWrapper(chunk)) {
return this.buildQueryFromSourceParams(
[new StringChunk("("), chunk.getSQL(), new StringChunk(")")],
config
);
}
if (is(chunk, Relation)) {
return this.buildQueryFromSourceParams(
[
chunk.sourceTable,
new StringChunk("."),
sql.identifier(chunk.fieldName),
],
config
);
}
if (inlineParams) {
return { sql: this.mapInlineParam(chunk, config), params: [] };
}
return {
sql: escapeParam(paramStartIndex.value++, chunk),
params: [chunk],
};
})
);
}
mapInlineParam(chunk, { escapeString }) {
if (chunk === null) {
return "null";
}
if (typeof chunk === "number" || typeof chunk === "boolean") {
return chunk.toString();
}
if (typeof chunk === "string") {
return escapeString(chunk);
}
if (typeof chunk === "object") {
const mappedValueAsString = chunk.toString();
if (mappedValueAsString === "[object Object]") {
return escapeString(JSON.stringify(chunk));
}
return escapeString(mappedValueAsString);
}
throw new Error("Unexpected param value: " + chunk);
}
getSQL() {
return this;
}
as(alias) {
if (alias === void 0) {
return this;
}
return new _SQL.Aliased(this, alias);
}
mapWith(decoder) {
this.decoder =
typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
return this;
}
inlineParams() {
this.shouldInlineParams = true;
return this;
}
};
var SQL = _SQL;
_a14 = entityKind;
__publicField(SQL, _a14, "SQL");
var _a15;
var Name = class {
constructor(value) {
this.value = value;
}
brand;
getSQL() {
return new SQL([this]);
}
};
_a15 = entityKind;
__publicField(Name, _a15, "Name");
function isDriverValueEncoder(value) {
return (
typeof value === "object" &&
value !== null &&
"mapToDriverValue" in value &&
typeof value.mapToDriverValue === "function"
);
}
var noopDecoder = {
mapFromDriverValue: (value) => value,
};
var noopEncoder = {
mapToDriverValue: (value) => value,
};
var noopMapper = {
...noopDecoder,
...noopEncoder,
};
var _a16;
var Param = class {
/**
* @param value - Parameter value
* @param encoder - Encoder to convert the value to a driver parameter
*/
constructor(value, encoder = noopEncoder) {
this.value = value;
this.encoder = encoder;
}
brand;
getSQL() {
return new SQL([this]);
}
};
_a16 = entityKind;
__publicField(Param, _a16, "Param");
function sql(strings, ...params) {
const queryChunks = [];
if (params.length > 0 || (strings.length > 0 && strings[0] !== "")) {
queryChunks.push(new StringChunk(strings[0]));
}
for (const [paramIndex, param2] of params.entries()) {
queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
}
return new SQL(queryChunks);
}
((sql2) => {
function empty() {
return new SQL([]);
}
sql2.empty = empty;
function fromList(list) {
return new SQL(list);
}
sql2.fromList = fromList;
function raw(str) {
return new SQL([new StringChunk(str)]);
}
sql2.raw = raw;
function join(chunks, separator) {
const result = [];
for (const [i, chunk] of chunks.entries()) {
if (i > 0 && separator !== void 0) {
result.push(separator);
}
result.push(chunk);
}
return new SQL(result);
}
sql2.join = join;
function identifier(value) {
return new Name(value);
}
sql2.identifier = identifier;
function placeholder2(name2) {
return new Placeholder(name2);
}
sql2.placeholder = placeholder2;
function param2(value, encoder) {
return new Param(value, encoder);
}
sql2.param = param2;
})(sql || (sql = {}));
((SQL2) => {
class Aliased {
constructor(sql2, fieldAlias) {
this.sql = sql2;
this.fieldAlias = fieldAlias;
}
static [entityKind] = "SQL.Aliased";
/** @internal */
isSelectionField = false;
getSQL() {
return this.sql;
}
/** @internal */
clone() {
return new Aliased(this.sql, this.fieldAlias);
}
}
SQL2.Aliased = Aliased;
})(SQL || (SQL = {}));
var _a17;
var Placeholder = class {
constructor(name2) {
this.name = name2;
}
getSQL() {
return new SQL([this]);
}
};
_a17 = entityKind;
__publicField(Placeholder, _a17, "Placeholder");
function fillPlaceholders(params, values) {
return params.map((p2) => {
if (is(p2, Placeholder)) {
if (!(p2.name in values)) {
throw new Error(`No value for placeholder "${p2.name}" was provided`);
}
return values[p2.name];
}
return p2;
});
}
var _a18;
var View = class {
/** @internal */
[((_a18 = entityKind), ViewBaseConfig)];
constructor({ name: name2, schema, selectedFields, query }) {
this[ViewBaseConfig] = {
name: name2,
originalName: name2,
schema,
selectedFields,
query,
isExisting: !query,
isAlias: false,
};
}
getSQL() {
return new SQL([this]);
}
};
__publicField(View, _a18, "View");
Column.prototype.getSQL = function () {
return new SQL([this]);
};
Table.prototype.getSQL = function () {
return new SQL([this]);
};
Subquery.prototype.getSQL = function () {
return new SQL([this]);
};
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/alias.js
var _a19;
var ColumnAliasProxyHandler = class {
constructor(table) {
this.table = table;
}
get(columnObj, prop) {
if (prop === "table") {
return this.table;
}
return columnObj[prop];
}
};
_a19 = entityKind;
__publicField(ColumnAliasProxyHandler, _a19, "ColumnAliasProxyHandler");
var _a20;
var TableAliasProxyHandler = class {
constructor(alias, replaceOriginalName) {
this.alias = alias;
this.replaceOriginalName = replaceOriginalName;
}
get(target, prop) {
if (prop === Table.Symbol.IsAlias) {
return true;
}
if (prop === Table.Symbol.Name) {
return this.alias;
}
if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {
return this.alias;
}
if (prop === ViewBaseConfig) {
return {
...target[ViewBaseConfig],
name: this.alias,
isAlias: true,
};
}
if (prop === Table.Symbol.Columns) {
const columns = target[Table.Symbol.Columns];
if (!columns) {
return columns;
}
const proxiedColumns = {};
Object.keys(columns).map((key) => {
proxiedColumns[key] = new Proxy(
columns[key],
new ColumnAliasProxyHandler(new Proxy(target, this))
);
});
return proxiedColumns;
}
const value = target[prop];
if (is(value, Column)) {
return new Proxy(
value,
new ColumnAliasProxyHandler(new Proxy(target, this))
);
}
return value;
}
};
_a20 = entityKind;
__publicField(TableAliasProxyHandler, _a20, "TableAliasProxyHandler");
var _a21;
var RelationTableAliasProxyHandler = class {
constructor(alias) {
this.alias = alias;
}
get(target, prop) {
if (prop === "sourceTable") {
return aliasedTable(target.sourceTable, this.alias);
}
return target[prop];
}
};
_a21 = entityKind;
__publicField(
RelationTableAliasProxyHandler,
_a21,
"RelationTableAliasProxyHandler"
);
function aliasedTable(table, tableAlias) {
return new Proxy(table, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedTableColumn(column, tableAlias) {
return new Proxy(
column,
new ColumnAliasProxyHandler(
new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))
)
);
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
return new SQL.Aliased(
mapColumnsInSQLToAlias(query.sql, alias),
query.fieldAlias
);
}
function mapColumnsInSQLToAlias(query, alias) {
return sql.join(
query.queryChunks.map((c2) => {
if (is(c2, Column)) {
return aliasedTableColumn(c2, alias);
}
if (is(c2, SQL)) {
return mapColumnsInSQLToAlias(c2, alias);
}
if (is(c2, SQL.Aliased)) {
return mapColumnsInAliasedSQLToAlias(c2, alias);
}
return c2;
})
);
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/column-builder.js
var _a22;
var ColumnBuilder = class {
config;
constructor(name, dataType, columnType) {
this.config = {
name,
notNull: false,
default: void 0,
hasDefault: false,
primaryKey: false,
isUnique: false,
uniqueName: void 0,
uniqueType: void 0,
dataType,
columnType,
};
}
/**
* Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
*
* @example
* ```ts
* const users = pgTable('users', {
* id: integer('id').$type<UserId>().primaryKey(),
* details: json('details').$type<UserDetails>().notNull(),
* });
* ```
*/
$type() {
return this;
}
/**
* Adds a `not null` clause to the column definition.
*
* Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
*/
notNull() {
this.config.notNull = true;
return this;
}
/**
* Adds a `default <value>` clause to the column definition.
*
* Affects the `insert` model of the table - columns *with* `default` are optional on insert.
*
* If you need to set a dynamic default value, use {@link $defaultFn} instead.
*/
default(value) {
this.config.default = value;
this.config.hasDefault = true;
return this;
}
/**
* Adds a dynamic default value to the column.
* The function will be called when the row is inserted, and the returned value will be used as the column value.
*
* **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
*/
$defaultFn(fn) {
this.config.defaultFn = fn;
this.config.hasDefault = true;
return this;
}
/**
* Alias for {@link $defaultFn}.
*/
$default = this.$defaultFn;
/**
* Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
*
* In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
*/
primaryKey() {
this.config.primaryKey = true;
this.config.notNull = true;
return this;
}
};
_a22 = entityKind;
__publicField(ColumnBuilder, _a22, "ColumnBuilder");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/errors.js
var _a23;
var DrizzleError = class extends Error {
constructor({ message, cause }) {
super(message);
this.name = "DrizzleError";
this.cause = cause;
}
};
_a23 = entityKind;
__publicField(DrizzleError, _a23, "DrizzleError");
var _a24;
var TransactionRollbackError = class extends DrizzleError {
constructor() {
super({ message: "Rollback" });
}
};
_a24 = entityKind;
__publicField(TransactionRollbackError, _a24, "TransactionRollbackError");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/logger.js
var _a25;
var ConsoleLogWriter = class {
write(message) {
console.log(message);
}
};
_a25 = entityKind;
__publicField(ConsoleLogWriter, _a25, "ConsoleLogWriter");
var _a26;
var DefaultLogger = class {
writer;
constructor(config) {
this.writer = config?.writer ?? new ConsoleLogWriter();
}
logQuery(query, params) {
const stringifiedParams = params.map((p2) => {
try {
return JSON.stringify(p2);
} catch {
return String(p2);
}
});
const paramsStr = stringifiedParams.length
? ` -- params: [${stringifiedParams.join(", ")}]`
: "";
this.writer.write(`Query: ${query}${paramsStr}`);
}
};
_a26 = entityKind;
__publicField(DefaultLogger, _a26, "DefaultLogger");
var _a27;
var NoopLogger = class {
logQuery() {}
};
_a27 = entityKind;
__publicField(NoopLogger, _a27, "NoopLogger");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/query-promise.js
var _a28;
var QueryPromise = class {
[((_a28 = entityKind), Symbol.toStringTag)] = "QueryPromise";
catch(onRejected) {
return this.then(void 0, onRejected);
}
finally(onFinally) {
return this.then(
(value) => {
onFinally?.();
return value;
},
(reason) => {
onFinally?.();
throw reason;
}
);
}
then(onFulfilled, onRejected) {
return this.execute().then(onFulfilled, onRejected);
}
};
__publicField(QueryPromise, _a28, "QueryPromise");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/utils.js
function mapResultRow(columns, row, joinsNotNullableMap) {
const nullifyMap = {};
const result = columns.reduce((result2, { path, field }, columnIndex) => {
let decoder;
if (is(field, Column)) {
decoder = field;
} else if (is(field, SQL)) {
decoder = field.decoder;
} else {
decoder = field.sql.decoder;
}
let node = result2;
for (const [pathChunkIndex, pathChunk] of path.entries()) {
if (pathChunkIndex < path.length - 1) {
if (!(pathChunk in node)) {
node[pathChunk] = {};
}
node = node[pathChunk];
} else {
const rawValue = row[columnIndex];
const value = (node[pathChunk] =
rawValue === null ? null : decoder.mapFromDriverValue(rawValue));
if (joinsNotNullableMap && is(field, Column) && path.length === 2) {
const objectName = path[0];
if (!(objectName in nullifyMap)) {
nullifyMap[objectName] =
value === null ? getTableName(field.table) : false;
} else if (
typeof nullifyMap[objectName] === "string" &&
nullifyMap[objectName] !== getTableName(field.table)
) {
nullifyMap[objectName] = false;
}
}
}
}
return result2;
}, {});
if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
for (const [objectName, tableName] of Object.entries(nullifyMap)) {
if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
result[objectName] = null;
}
}
}
return result;
}
function orderSelectedFields(fields, pathPrefix) {
return Object.entries(fields).reduce((result, [name, field]) => {
if (typeof name !== "string") {
return result;
}
const newPath = pathPrefix ? [...pathPrefix, name] : [name];
if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {
result.push({ path: newPath, field });
} else if (is(field, Table)) {
result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));
} else {
result.push(...orderSelectedFields(field, newPath));
}
return result;
}, []);
}
function haveSameKeys(left, right) {
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) {
return false;
}
for (const [index, key] of leftKeys.entries()) {
if (key !== rightKeys[index]) {
return false;
}
}
return true;
}
function mapUpdateSet(table, values) {
const entries = Object.entries(values)
.filter(([, value]) => value !== void 0)
.map(([key, value]) => {
if (is(value, SQL)) {
return [key, value];
} else {
return [key, new Param(value, table[Table.Symbol.Columns][key])];
}
});
if (entries.length === 0) {
throw new Error("No values to set");
}
return Object.fromEntries(entries);
}
function applyMixins(baseClass, extendedClasses) {
for (const extendedClass of extendedClasses) {
for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {
if (name === "constructor") continue;
Object.defineProperty(
baseClass.prototype,
name,
Object.getOwnPropertyDescriptor(extendedClass.prototype, name) ||
/* @__PURE__ */ Object.create(null)
);
}
}
}
function getTableColumns(table) {
return table[Table.Symbol.Columns];
}
function getTableLikeName(table) {
return is(table, Subquery)
? table[SubqueryConfig].alias
: is(table, View)
? table[ViewBaseConfig].name
: is(table, SQL)
? void 0
: table[Table.Symbol.IsAlias]
? table[Table.Symbol.Name]
: table[Table.Symbol.BaseName];
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/table.js
var InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
var _a29;
var SQLiteTable = class extends Table {
/** @internal */
[((_a29 = entityKind), Table.Symbol.Columns)];
/** @internal */
[InlineForeignKeys2] = [];
/** @internal */
[Table.Symbol.ExtraConfigBuilder] = void 0;
};
__publicField(SQLiteTable, _a29, "SQLiteTable");
/** @internal */
__publicField(
SQLiteTable,
"Symbol",
Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys2,
})
);
function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) {
const rawTable = new SQLiteTable(name, schema, baseName);
const builtColumns = Object.fromEntries(
Object.entries(columns).map(([name2, colBuilderBase]) => {
const colBuilder = colBuilderBase;
const column = colBuilder.build(rawTable);
rawTable[InlineForeignKeys2].push(
...colBuilder.buildForeignKeys(column, rawTable)
);
return [name2, column];
})
);
const table = Object.assign(rawTable, builtColumns);
table[Table.Symbol.Columns] = builtColumns;
if (extraConfig) {
table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
}
return table;
}
var sqliteTable = (name, columns, extraConfig) => {
return sqliteTableBase(name, columns, extraConfig);
};
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/foreign-keys.js
var _a30;
var ForeignKeyBuilder = class {
/** @internal */
reference;
/** @internal */
_onUpdate;
/** @internal */
_onDelete;
constructor(config, actions) {
this.reference = () => {
const { name, columns, foreignColumns } = config();
return {
name,
columns,
foreignTable: foreignColumns[0].table,
foreignColumns,
};
};
if (actions) {
this._onUpdate = actions.onUpdate;
this._onDelete = actions.onDelete;
}
}
onUpdate(action) {
this._onUpdate = action;
return this;
}
onDelete(action) {
this._onDelete = action;
return this;
}
/** @internal */
build(table) {
return new ForeignKey(table, this);
}
};
_a30 = entityKind;
__publicField(ForeignKeyBuilder, _a30, "SQLiteForeignKeyBuilder");
var _a31;
var ForeignKey = class {
constructor(table, builder) {
this.table = table;
this.reference = builder.reference;
this.onUpdate = builder._onUpdate;
this.onDelete = builder._onDelete;
}
reference;
onUpdate;
onDelete;
getName() {
const { name, columns, foreignColumns } = this.reference();
const columnNames = columns.map((column) => column.name);
const foreignColumnNames = foreignColumns.map((column) => column.name);
const chunks = [
this.table[SQLiteTable.Symbol.Name],
...columnNames,
foreignColumns[0].table[SQLiteTable.Symbol.Name],
...foreignColumnNames,
];
return name ?? `${chunks.join("_")}_fk`;
}
};
_a31 = entityKind;
__publicField(ForeignKey, _a31, "SQLiteForeignKey");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/unique-constraint.js
function uniqueKeyName(table, columns) {
return `${table[SQLiteTable.Symbol.Name]}_${columns.join("_")}_unique`;
}
var _a32;
var UniqueConstraintBuilder = class {
constructor(columns, name) {
this.name = name;
this.columns = columns;
}
/** @internal */
columns;
/** @internal */
build(table) {
return new UniqueConstraint(table, this.columns, this.name);
}
};
_a32 = entityKind;
__publicField(UniqueConstraintBuilder, _a32, "SQLiteUniqueConstraintBuilder");
var _a33;
var UniqueOnConstraintBuilder = class {
/** @internal */
name;
constructor(name) {
this.name = name;
}
on(...columns) {
return new UniqueConstraintBuilder(columns, this.name);
}
};
_a33 = entityKind;
__publicField(
UniqueOnConstraintBuilder,
_a33,
"SQLiteUniqueOnConstraintBuilder"
);
var _a34;
var UniqueConstraint = class {
constructor(table, columns, name) {
this.table = table;
this.columns = columns;
this.name =
name ??
uniqueKeyName(
this.table,
this.columns.map((column) => column.name)
);
}
columns;
name;
getName() {
return this.name;
}
};
_a34 = entityKind;
__publicField(UniqueConstraint, _a34, "SQLiteUniqueConstraint");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/columns/common.js
var _a35;
var SQLiteColumnBuilder = class extends ColumnBuilder {
foreignKeyConfigs = [];
references(ref, actions = {}) {
this.foreignKeyConfigs.push({ ref, actions });
return this;
}
unique(name) {
this.config.isUnique = true;
this.config.uniqueName = name;
return this;
}
/** @internal */
buildForeignKeys(column, table) {
return this.foreignKeyConfigs.map(({ ref, actions }) => {
return ((ref2, actions2) => {
const builder = new ForeignKeyBuilder(() => {
const foreignColumn = ref2();
return { columns: [column], foreignColumns: [foreignColumn] };
});
if (actions2.onUpdate) {
builder.onUpdate(actions2.onUpdate);
}
if (actions2.onDelete) {
builder.onDelete(actions2.onDelete);
}
return builder.build(table);
})(ref, actions);
});
}
};
_a35 = entityKind;
__publicField(SQLiteColumnBuilder, _a35, "SQLiteColumnBuilder");
var _a36;
var SQLiteColumn = class extends Column {
constructor(table, config) {
if (!config.uniqueName) {
config.uniqueName = uniqueKeyName(table, [config.name]);
}
super(table, config);
this.table = table;
}
};
_a36 = entityKind;
__publicField(SQLiteColumn, _a36, "SQLiteColumn");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/columns/integer.js
var _a37;
var SQLiteBaseIntegerBuilder = class extends SQLiteColumnBuilder {
constructor(name, dataType, columnType) {
super(name, dataType, columnType);
this.config.autoIncrement = false;
}
primaryKey(config) {
if (config?.autoIncrement) {
this.config.autoIncrement = true;
}
this.config.hasDefault = true;
return super.primaryKey();
}
};
_a37 = entityKind;
__publicField(SQLiteBaseIntegerBuilder, _a37, "SQLiteBaseIntegerBuilder");
var _a38;
var SQLiteBaseInteger = class extends SQLiteColumn {
autoIncrement = this.config.autoIncrement;
getSQLType() {
return "integer";
}
};
_a38 = entityKind;
__publicField(SQLiteBaseInteger, _a38, "SQLiteBaseInteger");
var _a39;
var SQLiteIntegerBuilder = class extends SQLiteBaseIntegerBuilder {
constructor(name) {
super(name, "number", "SQLiteInteger");
}
build(table) {
return new SQLiteInteger(table, this.config);
}
};
_a39 = entityKind;
__publicField(SQLiteIntegerBuilder, _a39, "SQLiteIntegerBuilder");
var _a40;
var SQLiteInteger = class extends SQLiteBaseInteger {};
_a40 = entityKind;
__publicField(SQLiteInteger, _a40, "SQLiteInteger");
var _a41;
var SQLiteTimestampBuilder = class extends SQLiteBaseIntegerBuilder {
constructor(name, mode) {
super(name, "date", "SQLiteTimestamp");
this.config.mode = mode;
}
/**
* @deprecated Use `default()` with your own expression instead.
*
* Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.
*/
defaultNow() {
return this.default(
sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`
);
}
build(table) {
return new SQLiteTimestamp(table, this.config);
}
};
_a41 = entityKind;
__publicField(SQLiteTimestampBuilder, _a41, "SQLiteTimestampBuilder");
var _a42;
var SQLiteTimestamp = class extends SQLiteBaseInteger {
mode = this.config.mode;
mapFromDriverValue(value) {
if (this.config.mode === "timestamp") {
return new Date(value * 1e3);
}
return new Date(value);
}
mapToDriverValue(value) {
const unix = value.getTime();
if (this.config.mode === "timestamp") {
return Math.floor(unix / 1e3);
}
return unix;
}
};
_a42 = entityKind;
__publicField(SQLiteTimestamp, _a42, "SQLiteTimestamp");
var _a43;
var SQLiteBooleanBuilder = class extends SQLiteBaseIntegerBuilder {
constructor(name, mode) {
super(name, "boolean", "SQLiteBoolean");
this.config.mode = mode;
}
build(table) {
return new SQLiteBoolean(table, this.config);
}
};
_a43 = entityKind;
__publicField(SQLiteBooleanBuilder, _a43, "SQLiteBooleanBuilder");
var _a44;
var SQLiteBoolean = class extends SQLiteBaseInteger {
mode = this.config.mode;
mapFromDriverValue(value) {
return Number(value) === 1;
}
mapToDriverValue(value) {
return value ? 1 : 0;
}
};
_a44 = entityKind;
__publicField(SQLiteBoolean, _a44, "SQLiteBoolean");
function integer(name, config) {
if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
return new SQLiteTimestampBuilder(name, config.mode);
}
if (config?.mode === "boolean") {
return new SQLiteBooleanBuilder(name, config.mode);
}
return new SQLiteIntegerBuilder(name);
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/columns/text.js
var _a45;
var SQLiteTextBuilder = class extends SQLiteColumnBuilder {
constructor(name, config) {
super(name, "string", "SQLiteText");
this.config.enumValues = config.enum;
this.config.length = config.length;
}
/** @internal */
build(table) {
return new SQLiteText(table, this.config);
}
};
_a45 = entityKind;
__publicField(SQLiteTextBuilder, _a45, "SQLiteTextBuilder");
var _a46;
var SQLiteText = class extends SQLiteColumn {
enumValues = this.config.enumValues;
length = this.config.length;
constructor(table, config) {
super(table, config);
}
getSQLType() {
return `text${this.config.length ? `(${this.config.length})` : ""}`;
}
};
_a46 = entityKind;
__publicField(SQLiteText, _a46, "SQLiteText");
var _a47;
var SQLiteTextJsonBuilder = class extends SQLiteColumnBuilder {
constructor(name) {
super(name, "json", "SQLiteTextJson");
}
/** @internal */
build(table) {
return new SQLiteTextJson(table, this.config);
}
};
_a47 = entityKind;
__publicField(SQLiteTextJsonBuilder, _a47, "SQLiteTextJsonBuilder");
var _a48;
var SQLiteTextJson = class extends SQLiteColumn {
getSQLType() {
return "text";
}
mapFromDriverValue(value) {
return JSON.parse(value);
}
mapToDriverValue(value) {
return JSON.stringify(value);
}
};
_a48 = entityKind;
__publicField(SQLiteTextJson, _a48, "SQLiteTextJson");
function text(name, config = {}) {
return config.mode === "json"
? new SQLiteTextJsonBuilder(name)
: new SQLiteTextBuilder(name, config);
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/selection-proxy.js
var _a49;
var _SelectionProxyHandler = class {
config;
constructor(config) {
this.config = { ...config };
}
get(subquery, prop) {
if (prop === SubqueryConfig) {
return {
...subquery[SubqueryConfig],
selection: new Proxy(subquery[SubqueryConfig].selection, this),
};
}
if (prop === ViewBaseConfig) {
return {
...subquery[ViewBaseConfig],
selectedFields: new Proxy(
subquery[ViewBaseConfig].selectedFields,
this
),
};
}
if (typeof prop === "symbol") {
return subquery[prop];
}
const columns = is(subquery, Subquery)
? subquery[SubqueryConfig].selection
: is(subquery, View)
? subquery[ViewBaseConfig].selectedFields
: subquery;
const value = columns[prop];
if (is(value, SQL.Aliased)) {
if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
return value.sql;
}
const newValue = value.clone();
newValue.isSelectionField = true;
return newValue;
}
if (is(value, SQL)) {
if (this.config.sqlBehavior === "sql") {
return value;
}
throw new Error(
`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
);
}
if (is(value, Column)) {
if (this.config.alias) {
return new Proxy(
value,
new ColumnAliasProxyHandler(
new Proxy(
value.table,
new TableAliasProxyHandler(
this.config.alias,
this.config.replaceOriginalName ?? false
)
)
)
);
}
return value;
}
if (typeof value !== "object" || value === null) {
return value;
}
return new Proxy(value, new _SelectionProxyHandler(this.config));
}
};
var SelectionProxyHandler = _SelectionProxyHandler;
_a49 = entityKind;
__publicField(SelectionProxyHandler, _a49, "SelectionProxyHandler");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js
var _a50;
var SQLiteDeleteBase = class extends QueryPromise {
constructor(table, session, dialect) {
super();
this.table = table;
this.session = session;
this.dialect = dialect;
this.config = { table };
}
/** @internal */
config;
/**
* Adds a `where` clause to the query.
*
* Calling this method will delete only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be deleted.
*
* ```ts
* // Delete all cars with green color
* db.delete(cars).where(eq(cars.color, 'green'));
* // or
* db.delete(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Delete all BMW cars with a green color
* db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Delete all cars with the green or blue color
* db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildDeleteQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(
this.getSQL()
);
return rest;
}
prepare(isOneTimeQuery) {
return this.session[
isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"
](
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning,
this.config.returning ? "all" : "run"
);
}
run = (placeholderValues) => {
return this.prepare(true).run(placeholderValues);
};
all = (placeholderValues) => {
return this.prepare(true).all(placeholderValues);
};
get = (placeholderValues) => {
return this.prepare(true).get(placeholderValues);
};
values = (placeholderValues) => {
return this.prepare(true).values(placeholderValues);
};
async execute(placeholderValues) {
return this.prepare(true).execute(placeholderValues);
}
$dynamic() {
return this;
}
};
_a50 = entityKind;
__publicField(SQLiteDeleteBase, _a50, "SQLiteDelete");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js
var _a51;
var SQLiteInsertBuilder = class {
constructor(table, session, dialect) {
this.table = table;
this.session = session;
this.dialect = dialect;
}
values(values) {
values = Array.isArray(values) ? values : [values];
if (values.length === 0) {
throw new Error("values() must be called with at least one value");
}
const mappedValues = values.map((entry) => {
const result = {};
const cols = this.table[Table.Symbol.Columns];
for (const colKey of Object.keys(entry)) {
const colValue = entry[colKey];
result[colKey] = is(colValue, SQL)
? colValue
: new Param(colValue, cols[colKey]);
}
return result;
});
return new SQLiteInsertBase(
this.table,
mappedValues,
this.session,
this.dialect
);
}
};
_a51 = entityKind;
__publicField(SQLiteInsertBuilder, _a51, "SQLiteInsertBuilder");
var _a52;
var SQLiteInsertBase = class extends QueryPromise {
constructor(table, values, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { table, values };
}
/** @internal */
config;
returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
this.config.returning = orderSelectedFields(fields);
return this;
}
/**
* Adds an `on conflict do nothing` clause to the query.
*
* Calling this method simply avoids inserting a row as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
*
* @param config The `target` and `where` clauses.
*
* @example
* ```ts
* // Insert one row and cancel the insert if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing();
*
* // Explicitly specify conflict target
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoNothing({ target: cars.id });
* ```
*/
onConflictDoNothing(config = {}) {
if (config.target === void 0) {
this.config.onConflict = sql`do nothing`;
} else {
const targetSql = Array.isArray(config.target)
? sql`${config.target}`
: sql`${[config.target]}`;
const whereSql = config.where ? sql` where ${config.where}` : sql``;
this.config.onConflict = sql`${targetSql} do nothing${whereSql}`;
}
return this;
}
/**
* Adds an `on conflict do update` clause to the query.
*
* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
*
* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
*
* @param config The `target`, `set` and `where` clauses.
*
* @example
* ```ts
* // Update the row if there's a conflict
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'Porsche' }
* });
*
* // Upsert with 'where' clause
* await db.insert(cars)
* .values({ id: 1, brand: 'BMW' })
* .onConflictDoUpdate({
* target: cars.id,
* set: { brand: 'newBMW' },
* where: sql`${cars.createdAt} > '2023-01-01'::date`,
* });
* ```
*/
onConflictDoUpdate(config) {
const targetSql = Array.isArray(config.target)
? sql`${config.target}`
: sql`${[config.target]}`;
const whereSql = config.where ? sql` where ${config.where}` : sql``;
const setSql = this.dialect.buildUpdateSet(
this.config.table,
mapUpdateSet(this.config.table, config.set)
);
this.config.onConflict = sql`${targetSql} do update set ${setSql}${whereSql}`;
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildInsertQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(
this.getSQL()
);
return rest;
}
prepare(isOneTimeQuery) {
return this.session[
isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"
](
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning,
this.config.returning ? "all" : "run"
);
}
run = (placeholderValues) => {
return this.prepare(true).run(placeholderValues);
};
all = (placeholderValues) => {
return this.prepare(true).all(placeholderValues);
};
get = (placeholderValues) => {
return this.prepare(true).get(placeholderValues);
};
values = (placeholderValues) => {
return this.prepare(true).values(placeholderValues);
};
async execute() {
return this.config.returning ? this.all() : this.run();
}
$dynamic() {
return this;
}
};
_a52 = entityKind;
__publicField(SQLiteInsertBase, _a52, "SQLiteInsert");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/view-base.js
var _a53;
var SQLiteViewBase = class extends View {};
_a53 = entityKind;
__publicField(SQLiteViewBase, _a53, "SQLiteViewBase");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/dialect.js
var _a54;
var SQLiteDialect = class {
escapeName(name) {
return `"${name}"`;
}
escapeParam(_num) {
return "?";
}
escapeString(str) {
return `'${str.replace(/'/g, "''")}'`;
}
buildDeleteQuery({ table, where, returning }) {
const returningSql = returning
? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`
: void 0;
const whereSql = where ? sql` where ${where}` : void 0;
return sql`delete from ${table}${whereSql}${returningSql}`;
}
buildUpdateSet(table, set) {
const setEntries = Object.entries(set);
const setSize = setEntries.length;
return sql.join(
setEntries.flatMap(([colName, value], i) => {
const col = table[Table.Symbol.Columns][colName];
const res = sql`${sql.identifier(col.name)} = ${value}`;
if (i < setSize - 1) {
return [res, sql.raw(", ")];
}
return [res];
})
);
}
buildUpdateQuery({ table, set, where, returning }) {
const setSql = this.buildUpdateSet(table, set);
const returningSql = returning
? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`
: void 0;
const whereSql = where ? sql` where ${where}` : void 0;
return sql`update ${table} set ${setSql}${whereSql}${returningSql}`;
}
/**
* Builds selection SQL with provided fields/expressions
*
* Examples:
*
* `select <selection> from`
*
* `insert ... returning <selection>`
*
* If `isSingleTable` is true, then columns won't be prefixed with table name
*/
buildSelection(fields, { isSingleTable = false } = {}) {
const columnsLen = fields.length;
const chunks = fields.flatMap(({ field }, i) => {
const chunk = [];
if (is(field, SQL.Aliased) && field.isSelectionField) {
chunk.push(sql.identifier(field.fieldAlias));
} else if (is(field, SQL.Aliased) || is(field, SQL)) {
const query = is(field, SQL.Aliased) ? field.sql : field;
if (isSingleTable) {
chunk.push(
new SQL(
query.queryChunks.map((c2) => {
if (is(c2, Column)) {
return sql.identifier(c2.name);
}
return c2;
})
)
);
} else {
chunk.push(query);
}
if (is(field, SQL.Aliased)) {
chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
}
} else if (is(field, Column)) {
const tableName = field.table[Table.Symbol.Name];
const columnName = field.name;
if (isSingleTable) {
chunk.push(sql.identifier(columnName));
} else {
chunk.push(
sql`${sql.identifier(tableName)}.${sql.identifier(columnName)}`
);
}
}
if (i < columnsLen - 1) {
chunk.push(sql`, `);
}
return chunk;
});
return sql.join(chunks);
}
buildSelectQuery({
withList,
fields,
fieldsFlat,
where,
having,
table,
joins,
orderBy,
groupBy,
limit,
offset,
distinct,
setOperators,
}) {
const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
for (const f2 of fieldsList) {
if (
is(f2.field, Column) &&
getTableName(f2.field.table) !==
(is(table, Subquery)
? table[SubqueryConfig].alias
: is(table, SQLiteViewBase)
? table[ViewBaseConfig].name
: is(table, SQL)
? void 0
: getTableName(table)) &&
!((table2) =>
joins?.some(
({ alias }) =>
alias ===
(table2[Table.Symbol.IsAlias]
? getTableName(table2)
: table2[Table.Symbol.BaseName])
))(f2.field.table)
) {
const tableName = getTableName(f2.field.table);
throw new Error(
`Your "${f2.path.join("->")}" field references a column "${tableName}"."${f2.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
);
}
}
const isSingleTable = !joins || joins.length === 0;
let withSql;
if (withList?.length) {
const withSqlChunks = [sql`with `];
for (const [i, w] of withList.entries()) {
withSqlChunks.push(
sql`${sql.identifier(w[SubqueryConfig].alias)} as (${w[SubqueryConfig].sql})`
);
if (i < withList.length - 1) {
withSqlChunks.push(sql`, `);
}
}
withSqlChunks.push(sql` `);
withSql = sql.join(withSqlChunks);
}
const distinctSql = distinct ? sql` distinct` : void 0;
const selection = this.buildSelection(fieldsList, { isSingleTable });
const tableSql = (() => {
if (
is(table, Table) &&
table[Table.Symbol.OriginalName] !== table[Table.Symbol.Name]
) {
return sql`${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`;
}
return table;
})();
const joinsArray = [];
if (joins) {
for (const [index, joinMeta] of joins.entries()) {
if (index === 0) {
joinsArray.push(sql` `);
}
const table2 = joinMeta.table;
if (is(table2, SQLiteTable)) {
const tableName = table2[SQLiteTable.Symbol.Name];
const tableSchema = table2[SQLiteTable.Symbol.Schema];
const origTableName = table2[SQLiteTable.Symbol.OriginalName];
const alias = tableName === origTableName ? void 0 : joinMeta.alias;
joinsArray.push(
sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`} on ${joinMeta.on}`
);
} else {
joinsArray.push(
sql`${sql.raw(joinMeta.joinType)} join ${table2} on ${joinMeta.on}`
);
}
if (index < joins.length - 1) {
joinsArray.push(sql` `);
}
}
}
const joinsSql = sql.join(joinsArray);
const whereSql = where ? sql` where ${where}` : void 0;
const havingSql = having ? sql` having ${having}` : void 0;
const orderByList = [];
if (orderBy) {
for (const [index, orderByValue] of orderBy.entries()) {
orderByList.push(orderByValue);
if (index < orderBy.length - 1) {
orderByList.push(sql`, `);
}
}
}
const groupByList = [];
if (groupBy) {
for (const [index, groupByValue] of groupBy.entries()) {
groupByList.push(groupByValue);
if (index < groupBy.length - 1) {
groupByList.push(sql`, `);
}
}
}
const groupBySql =
groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
const orderBySql =
orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
const limitSql = limit ? sql` limit ${limit}` : void 0;
const offsetSql = offset ? sql` offset ${offset}` : void 0;
const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
if (setOperators.length > 0) {
return this.buildSetOperations(finalQuery, setOperators);
}
return finalQuery;
}
buildSetOperations(leftSelect, setOperators) {
const [setOperator, ...rest] = setOperators;
if (!setOperator) {
throw new Error("Cannot pass undefined values to any set operator");
}
if (rest.length === 0) {
return this.buildSetOperationQuery({ leftSelect, setOperator });
}
return this.buildSetOperations(
this.buildSetOperationQuery({ leftSelect, setOperator }),
rest
);
}
buildSetOperationQuery({
leftSelect,
setOperator: { type, isAll, rightSelect, limit, orderBy, offset },
}) {
const leftChunk = sql`${leftSelect.getSQL()} `;
const rightChunk = sql`${rightSelect.getSQL()}`;
let orderBySql;
if (orderBy && orderBy.length > 0) {
const orderByValues = [];
for (const singleOrderBy of orderBy) {
if (is(singleOrderBy, SQLiteColumn)) {
orderByValues.push(sql.identifier(singleOrderBy.name));
} else if (is(singleOrderBy, SQL)) {
for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
const chunk = singleOrderBy.queryChunks[i];
if (is(chunk, SQLiteColumn)) {
singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
}
}
orderByValues.push(sql`${singleOrderBy}`);
} else {
orderByValues.push(sql`${singleOrderBy}`);
}
}
orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
}
const limitSql = limit ? sql` limit ${limit}` : void 0;
const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
const offsetSql = offset ? sql` offset ${offset}` : void 0;
return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
}
buildInsertQuery({ table, values, onConflict, returning }) {
const valuesSqlList = [];
const columns = table[Table.Symbol.Columns];
const colEntries = Object.entries(columns);
const insertOrder = colEntries.map(([, column]) =>
sql.identifier(column.name)
);
for (const [valueIndex, value] of values.entries()) {
const valueList = [];
for (const [fieldName, col] of colEntries) {
const colValue = value[fieldName];
if (
colValue === void 0 ||
(is(colValue, Param) && colValue.value === void 0)
) {
let defaultValue;
if (col.default !== null && col.default !== void 0) {
defaultValue = is(col.default, SQL)
? col.default
: sql.param(col.default, col);
} else if (col.defaultFn !== void 0) {
const defaultFnResult = col.defaultFn();
defaultValue = is(defaultFnResult, SQL)
? defaultFnResult
: sql.param(defaultFnResult, col);
} else {
defaultValue = sql`null`;
}
valueList.push(defaultValue);
} else {
valueList.push(colValue);
}
}
valuesSqlList.push(valueList);
if (valueIndex < values.length - 1) {
valuesSqlList.push(sql`, `);
}
}
const valuesSql = sql.join(valuesSqlList);
const returningSql = returning
? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`
: void 0;
const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
return sql`insert into ${table} ${insertOrder} values ${valuesSql}${onConflictSql}${returningSql}`;
}
sqlToQuery(sql2) {
return sql2.toQuery({
escapeName: this.escapeName,
escapeParam: this.escapeParam,
escapeString: this.escapeString,
});
}
buildRelationalQuery({
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
queryConfig: config,
tableAlias,
nestedQueryRelation,
joinOn,
}) {
let selection = [];
let limit,
offset,
orderBy = [],
where;
const joins = [];
if (config === true) {
const selectionEntries = Object.entries(tableConfig.columns);
selection = selectionEntries.map(([key, value]) => ({
dbKey: value.name,
tsKey: key,
field: aliasedTableColumn(value, tableAlias),
relationTableTsKey: void 0,
isJson: false,
selection: [],
}));
} else {
const aliasedColumns = Object.fromEntries(
Object.entries(tableConfig.columns).map(([key, value]) => [
key,
aliasedTableColumn(value, tableAlias),
])
);
if (config.where) {
const whereSql =
typeof config.where === "function"
? config.where(aliasedColumns, getOperators())
: config.where;
where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
}
const fieldsSelection = [];
let selectedColumns = [];
if (config.columns) {
let isIncludeMode = false;
for (const [field, value] of Object.entries(config.columns)) {
if (value === void 0) {
continue;
}
if (field in tableConfig.columns) {
if (!isIncludeMode && value === true) {
isIncludeMode = true;
}
selectedColumns.push(field);
}
}
if (selectedColumns.length > 0) {
selectedColumns = isIncludeMode
? selectedColumns.filter((c2) => config.columns?.[c2] === true)
: Object.keys(tableConfig.columns).filter(
(key) => !selectedColumns.includes(key)
);
}
} else {
selectedColumns = Object.keys(tableConfig.columns);
}
for (const field of selectedColumns) {
const column = tableConfig.columns[field];
fieldsSelection.push({ tsKey: field, value: column });
}
let selectedRelations = [];
if (config.with) {
selectedRelations = Object.entries(config.with)
.filter((entry) => !!entry[1])
.map(([tsKey, queryConfig]) => ({
tsKey,
queryConfig,
relation: tableConfig.relations[tsKey],
}));
}
let extras;
if (config.extras) {
extras =
typeof config.extras === "function"
? config.extras(aliasedColumns, { sql })
: config.extras;
for (const [tsKey, value] of Object.entries(extras)) {
fieldsSelection.push({
tsKey,
value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
});
}
}
for (const { tsKey, value } of fieldsSelection) {
selection.push({
dbKey: is(value, SQL.Aliased)
? value.fieldAlias
: tableConfig.columns[tsKey].name,
tsKey,
field: is(value, Column)
? aliasedTableColumn(value, tableAlias)
: value,
relationTableTsKey: void 0,
isJson: false,
selection: [],
});
}
let orderByOrig =
typeof config.orderBy === "function"
? config.orderBy(aliasedColumns, getOrderByOperators())
: config.orderBy ?? [];
if (!Array.isArray(orderByOrig)) {
orderByOrig = [orderByOrig];
}
orderBy = orderByOrig.map((orderByValue) => {
if (is(orderByValue, Column)) {
return aliasedTableColumn(orderByValue, tableAlias);
}
return mapColumnsInSQLToAlias(orderByValue, tableAlias);
});
limit = config.limit;
offset = config.offset;
for (const {
tsKey: selectedRelationTsKey,
queryConfig: selectedRelationConfigValue,
relation,
} of selectedRelations) {
const normalizedRelation = normalizeRelation(
schema,
tableNamesMap,
relation
);
const relationTableName = relation.referencedTable[Table.Symbol.Name];
const relationTableTsName = tableNamesMap[relationTableName];
const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
const joinOn2 = and(
...normalizedRelation.fields.map((field2, i) =>
eq(
aliasedTableColumn(
normalizedRelation.references[i],
relationTableAlias
),
aliasedTableColumn(field2, tableAlias)
)
)
);
const builtRelation = this.buildRelationalQuery({
fullSchema,
schema,
tableNamesMap,
table: fullSchema[relationTableTsName],
tableConfig: schema[relationTableTsName],
queryConfig: is(relation, One)
? selectedRelationConfigValue === true
? { limit: 1 }
: { ...selectedRelationConfigValue, limit: 1 }
: selectedRelationConfigValue,
tableAlias: relationTableAlias,
joinOn: joinOn2,
nestedQueryRelation: relation,
});
const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
selection.push({
dbKey: selectedRelationTsKey,
tsKey: selectedRelationTsKey,
field,
relationTableTsKey: relationTableTsName,
isJson: true,
selection: builtRelation.selection,
});
}
}
if (selection.length === 0) {
throw new DrizzleError({
message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`,
});
}
let result;
where = and(joinOn, where);
if (nestedQueryRelation) {
let field = sql`json_array(${sql.join(
selection.map(({ field: field2 }) =>
is(field2, SQLiteColumn)
? sql.identifier(field2.name)
: is(field2, SQL.Aliased)
? field2.sql
: field2
),
sql`, `
)})`;
if (is(nestedQueryRelation, Many)) {
field = sql`coalesce(json_group_array(${field}), json_array())`;
}
const nestedSelection = [
{
dbKey: "data",
tsKey: "data",
field: field.as("data"),
isJson: true,
relationTableTsKey: tableConfig.tsName,
selection,
},
];
const needsSubquery =
limit !== void 0 || offset !== void 0 || orderBy.length > 0;
if (needsSubquery) {
result = this.buildSelectQuery({
table: aliasedTable(table, tableAlias),
fields: {},
fieldsFlat: [
{
path: [],
field: sql.raw("*"),
},
],
where,
limit,
offset,
orderBy,
setOperators: [],
});
where = void 0;
limit = void 0;
offset = void 0;
orderBy = void 0;
} else {
result = aliasedTable(table, tableAlias);
}
result = this.buildSelectQuery({
table: is(result, SQLiteTable)
? result
: new Subquery(result, {}, tableAlias),
fields: {},
fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
path: [],
field: is(field2, Column)
? aliasedTableColumn(field2, tableAlias)
: field2,
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: [],
});
} else {
result = this.buildSelectQuery({
table: aliasedTable(table, tableAlias),
fields: {},
fieldsFlat: selection.map(({ field }) => ({
path: [],
field: is(field, Column)
? aliasedTableColumn(field, tableAlias)
: field,
})),
joins,
where,
limit,
offset,
orderBy,
setOperators: [],
});
}
return {
tableTsKey: tableConfig.tsName,
sql: result,
selection,
};
}
};
_a54 = entityKind;
__publicField(SQLiteDialect, _a54, "SQLiteDialect");
var _a55;
var SQLiteSyncDialect = class extends SQLiteDialect {
migrate(migrations, session) {
const migrationTableCreate = sql`
CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
id SERIAL PRIMARY KEY,
hash text NOT NULL,
created_at numeric
)
`;
session.run(migrationTableCreate);
const dbMigrations = session.values(
sql`SELECT id, hash, created_at FROM "__drizzle_migrations" ORDER BY created_at DESC LIMIT 1`
);
const lastDbMigration = dbMigrations[0] ?? void 0;
session.run(sql`BEGIN`);
try {
for (const migration of migrations) {
if (
!lastDbMigration ||
Number(lastDbMigration[2]) < migration.folderMillis
) {
for (const stmt of migration.sql) {
session.run(sql.raw(stmt));
}
session.run(
sql`INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
);
}
}
session.run(sql`COMMIT`);
} catch (e) {
session.run(sql`ROLLBACK`);
throw e;
}
}
};
_a55 = entityKind;
__publicField(SQLiteSyncDialect, _a55, "SQLiteSyncDialect");
var _a56;
var SQLiteAsyncDialect = class extends SQLiteDialect {
async migrate(migrations, session) {
const migrationTableCreate = sql`
CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
id SERIAL PRIMARY KEY,
hash text NOT NULL,
created_at numeric
)
`;
await session.run(migrationTableCreate);
const dbMigrations = await session.values(
sql`SELECT id, hash, created_at FROM "__drizzle_migrations" ORDER BY created_at DESC LIMIT 1`
);
const lastDbMigration = dbMigrations[0] ?? void 0;
await session.transaction(async (tx) => {
for (const migration of migrations) {
if (
!lastDbMigration ||
Number(lastDbMigration[2]) < migration.folderMillis
) {
for (const stmt of migration.sql) {
await tx.run(sql.raw(stmt));
}
await tx.run(
sql`INSERT INTO "__drizzle_migrations" ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
);
}
}
});
}
};
_a56 = entityKind;
__publicField(SQLiteAsyncDialect, _a56, "SQLiteAsyncDialect");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/query-builders/query-builder.js
var _a57;
var TypedQueryBuilder = class {
/** @internal */
getSelectedFields() {
return this._.selectedFields;
}
};
_a57 = entityKind;
__publicField(TypedQueryBuilder, _a57, "TypedQueryBuilder");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/select.js
var _a58;
var SQLiteSelectBuilder = class {
fields;
session;
dialect;
withList;
distinct;
constructor(config) {
this.fields = config.fields;
this.session = config.session;
this.dialect = config.dialect;
this.withList = config.withList;
this.distinct = config.distinct;
}
from(source) {
const isPartialSelect = !!this.fields;
let fields;
if (this.fields) {
fields = this.fields;
} else if (is(source, Subquery)) {
fields = Object.fromEntries(
Object.keys(source[SubqueryConfig].selection).map((key) => [
key,
source[key],
])
);
} else if (is(source, SQLiteViewBase)) {
fields = source[ViewBaseConfig].selectedFields;
} else if (is(source, SQL)) {
fields = {};
} else {
fields = getTableColumns(source);
}
return new SQLiteSelectBase({
table: source,
fields,
isPartialSelect,
session: this.session,
dialect: this.dialect,
withList: this.withList,
distinct: this.distinct,
});
}
};
_a58 = entityKind;
__publicField(SQLiteSelectBuilder, _a58, "SQLiteSelectBuilder");
var _a59;
var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder {
_;
/** @internal */
config;
joinsNotNullableMap;
tableName;
isPartialSelect;
session;
dialect;
constructor({
table,
fields,
isPartialSelect,
session,
dialect,
withList,
distinct,
}) {
super();
this.config = {
withList,
table,
fields: { ...fields },
distinct,
setOperators: [],
};
this.isPartialSelect = isPartialSelect;
this.session = session;
this.dialect = dialect;
this._ = {
selectedFields: fields,
};
this.tableName = getTableLikeName(table);
this.joinsNotNullableMap =
typeof this.tableName === "string" ? { [this.tableName]: true } : {};
}
createJoin(joinType) {
return (table, on) => {
const baseTableName = this.tableName;
const tableName = getTableLikeName(table);
if (
typeof tableName === "string" &&
this.config.joins?.some((join) => join.alias === tableName)
) {
throw new Error(`Alias "${tableName}" is already used in this query`);
}
if (!this.isPartialSelect) {
if (
Object.keys(this.joinsNotNullableMap).length === 1 &&
typeof baseTableName === "string"
) {
this.config.fields = {
[baseTableName]: this.config.fields,
};
}
if (typeof tableName === "string" && !is(table, SQL)) {
const selection = is(table, Subquery)
? table[SubqueryConfig].selection
: is(table, View)
? table[ViewBaseConfig].selectedFields
: table[Table.Symbol.Columns];
this.config.fields[tableName] = selection;
}
}
if (typeof on === "function") {
on = on(
new Proxy(
this.config.fields,
new SelectionProxyHandler({
sqlAliasedBehavior: "sql",
sqlBehavior: "sql",
})
)
);
}
if (!this.config.joins) {
this.config.joins = [];
}
this.config.joins.push({ on, table, joinType, alias: tableName });
if (typeof tableName === "string") {
switch (joinType) {
case "left": {
this.joinsNotNullableMap[tableName] = false;
break;
}
case "right": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [
key,
false,
])
);
this.joinsNotNullableMap[tableName] = true;
break;
}
case "inner": {
this.joinsNotNullableMap[tableName] = true;
break;
}
case "full": {
this.joinsNotNullableMap = Object.fromEntries(
Object.entries(this.joinsNotNullableMap).map(([key]) => [
key,
false,
])
);
this.joinsNotNullableMap[tableName] = false;
break;
}
}
}
return this;
};
}
/**
* Executes a `left join` operation by adding another table to the current query.
*
* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet | null }[] = await db.select()
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .leftJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
leftJoin = this.createJoin("left");
/**
* Executes a `right join` operation by adding another table to the current query.
*
* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet }[] = await db.select()
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .rightJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
rightJoin = this.createJoin("right");
/**
* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
*
* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User; pets: Pet }[] = await db.select()
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number; petId: number }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .innerJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
innerJoin = this.createJoin("inner");
/**
* Executes a `full join` operation by combining rows from two tables into a new table.
*
* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
*
* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
*
* @param table the table to join.
* @param on the `on` clause.
*
* @example
*
* ```ts
* // Select all users and their pets
* const usersWithPets: { user: User | null; pets: Pet | null }[] = await db.select()
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
*
* // Select userId and petId
* const usersIdsAndPetIds: { userId: number | null; petId: number | null }[] = await db.select({
* userId: users.id,
* petId: pets.id,
* })
* .from(users)
* .fullJoin(pets, eq(users.id, pets.ownerId))
* ```
*/
fullJoin = this.createJoin("full");
createSetOperator(type, isAll) {
return (rightSelection) => {
const rightSelect =
typeof rightSelection === "function"
? rightSelection(getSQLiteSetOperators())
: rightSelection;
if (
!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())
) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
this.config.setOperators.push({ type, isAll, rightSelect });
return this;
};
}
/**
* Adds `union` set operator to the query.
*
* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
*
* @example
*
* ```ts
* // Select all unique names from customers and users tables
* await db.select({ name: users.name })
* .from(users)
* .union(
* db.select({ name: customers.name }).from(customers)
* );
* // or
* import { union } from 'drizzle-orm/sqlite-core'
*
* await union(
* db.select({ name: users.name }).from(users),
* db.select({ name: customers.name }).from(customers)
* );
* ```
*/
union = this.createSetOperator("union", false);
/**
* Adds `union all` set operator to the query.
*
* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
*
* @example
*
* ```ts
* // Select all transaction ids from both online and in-store sales
* await db.select({ transaction: onlineSales.transactionId })
* .from(onlineSales)
* .unionAll(
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* // or
* import { unionAll } from 'drizzle-orm/sqlite-core'
*
* await unionAll(
* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
* );
* ```
*/
unionAll = this.createSetOperator("union", true);
/**
* Adds `intersect` set operator to the query.
*
* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
*
* @example
*
* ```ts
* // Select course names that are offered in both departments A and B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .intersect(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { intersect } from 'drizzle-orm/sqlite-core'
*
* await intersect(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
intersect = this.createSetOperator("intersect", false);
/**
* Adds `except` set operator to the query.
*
* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
*
* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
*
* @example
*
* ```ts
* // Select all courses offered in department A but not in department B
* await db.select({ courseName: depA.courseName })
* .from(depA)
* .except(
* db.select({ courseName: depB.courseName }).from(depB)
* );
* // or
* import { except } from 'drizzle-orm/sqlite-core'
*
* await except(
* db.select({ courseName: depA.courseName }).from(depA),
* db.select({ courseName: depB.courseName }).from(depB)
* );
* ```
*/
except = this.createSetOperator("except", false);
/** @internal */
addSetOperators(setOperators) {
this.config.setOperators.push(...setOperators);
return this;
}
/**
* Adds a `where` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#filtering}
*
* @param where the `where` clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be selected.
*
* ```ts
* // Select all cars with green color
* await db.select().from(cars).where(eq(cars.color, 'green'));
* // or
* await db.select().from(cars).where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Select all BMW cars with a green color
* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Select all cars with the green or blue color
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
if (typeof where === "function") {
where = where(
new Proxy(
this.config.fields,
new SelectionProxyHandler({
sqlAliasedBehavior: "sql",
sqlBehavior: "sql",
})
)
);
}
this.config.where = where;
return this;
}
/**
* Adds a `having` clause to the query.
*
* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
*
* @param having the `having` clause.
*
* @example
*
* ```ts
* // Select all brands with more than one car
* await db.select({
* brand: cars.brand,
* count: sql<number>`cast(count(${cars.id}) as int)`,
* })
* .from(cars)
* .groupBy(cars.brand)
* .having(({ count }) => gt(count, 1));
* ```
*/
having(having) {
if (typeof having === "function") {
having = having(
new Proxy(
this.config.fields,
new SelectionProxyHandler({
sqlAliasedBehavior: "sql",
sqlBehavior: "sql",
})
)
);
}
this.config.having = having;
return this;
}
groupBy(...columns) {
if (typeof columns[0] === "function") {
const groupBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({
sqlAliasedBehavior: "alias",
sqlBehavior: "sql",
})
)
);
this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
} else {
this.config.groupBy = columns;
}
return this;
}
orderBy(...columns) {
if (typeof columns[0] === "function") {
const orderBy = columns[0](
new Proxy(
this.config.fields,
new SelectionProxyHandler({
sqlAliasedBehavior: "alias",
sqlBehavior: "sql",
})
)
);
const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
} else {
const orderByArray = columns;
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).orderBy = orderByArray;
} else {
this.config.orderBy = orderByArray;
}
}
return this;
}
/**
* Adds a `limit` clause to the query.
*
* Calling this method will set the maximum number of rows that will be returned by this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param limit the `limit` clause.
*
* @example
*
* ```ts
* // Get the first 10 people from this query.
* await db.select().from(people).limit(10);
* ```
*/
limit(limit) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).limit = limit;
} else {
this.config.limit = limit;
}
return this;
}
/**
* Adds an `offset` clause to the query.
*
* Calling this method will skip a number of rows when returning results from this query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
*
* @param offset the `offset` clause.
*
* @example
*
* ```ts
* // Get the 10th-20th people from this query.
* await db.select().from(people).offset(10).limit(10);
* ```
*/
offset(offset) {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1).offset = offset;
} else {
this.config.offset = offset;
}
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildSelectQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(
this.getSQL()
);
return rest;
}
as(alias) {
return new Proxy(
new Subquery(this.getSQL(), this.config.fields, alias),
new SelectionProxyHandler({
alias,
sqlAliasedBehavior: "alias",
sqlBehavior: "error",
})
);
}
/** @internal */
getSelectedFields() {
return new Proxy(
this.config.fields,
new SelectionProxyHandler({
alias: this.tableName,
sqlAliasedBehavior: "alias",
sqlBehavior: "error",
})
);
}
$dynamic() {
return this;
}
};
_a59 = entityKind;
__publicField(SQLiteSelectQueryBuilderBase, _a59, "SQLiteSelectQueryBuilder");
var _a60;
var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase {
prepare(isOneTimeQuery) {
if (!this.session) {
throw new Error(
"Cannot execute a query on a query builder. Please use a database instance instead."
);
}
const fieldsList = orderSelectedFields(this.config.fields);
const query = this.session[
isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"
](this.dialect.sqlToQuery(this.getSQL()), fieldsList, "all");
query.joinsNotNullableMap = this.joinsNotNullableMap;
return query;
}
run = (placeholderValues) => {
return this.prepare(true).run(placeholderValues);
};
all = (placeholderValues) => {
return this.prepare(true).all(placeholderValues);
};
get = (placeholderValues) => {
return this.prepare(true).get(placeholderValues);
};
values = (placeholderValues) => {
return this.prepare(true).values(placeholderValues);
};
async execute() {
return this.all();
}
};
_a60 = entityKind;
__publicField(SQLiteSelectBase, _a60, "SQLiteSelect");
applyMixins(SQLiteSelectBase, [QueryPromise]);
function createSetOperator(type, isAll) {
return (leftSelect, rightSelect, ...restSelects) => {
const setOperators = [rightSelect, ...restSelects].map((select) => ({
type,
isAll,
rightSelect: select,
}));
for (const setOperator of setOperators) {
if (
!haveSameKeys(
leftSelect.getSelectedFields(),
setOperator.rightSelect.getSelectedFields()
)
) {
throw new Error(
"Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
);
}
}
return leftSelect.addSetOperators(setOperators);
};
}
var getSQLiteSetOperators = () => ({
union,
unionAll,
intersect,
except,
});
var union = createSetOperator("union", false);
var unionAll = createSetOperator("union", true);
var intersect = createSetOperator("intersect", false);
var except = createSetOperator("except", false);
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js
var _a61;
var QueryBuilder = class {
dialect;
$with(alias) {
const queryBuilder = this;
return {
as(qb) {
if (typeof qb === "function") {
qb = qb(queryBuilder);
}
return new Proxy(
new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
new SelectionProxyHandler({
alias,
sqlAliasedBehavior: "alias",
sqlBehavior: "error",
})
);
},
};
}
with(...queries) {
const self2 = this;
function select(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self2.getDialect(),
withList: queries,
});
}
function selectDistinct(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: self2.getDialect(),
withList: queries,
distinct: true,
});
}
return { select, selectDistinct };
}
select(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
});
}
selectDistinct(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: void 0,
dialect: this.getDialect(),
distinct: true,
});
}
// Lazy load dialect to avoid circular dependency
getDialect() {
if (!this.dialect) {
this.dialect = new SQLiteSyncDialect();
}
return this.dialect;
}
};
_a61 = entityKind;
__publicField(QueryBuilder, _a61, "SQLiteQueryBuilder");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/update.js
var _a62;
var SQLiteUpdateBuilder = class {
constructor(table, session, dialect) {
this.table = table;
this.session = session;
this.dialect = dialect;
}
set(values) {
return new SQLiteUpdateBase(
this.table,
mapUpdateSet(this.table, values),
this.session,
this.dialect
);
}
};
_a62 = entityKind;
__publicField(SQLiteUpdateBuilder, _a62, "SQLiteUpdateBuilder");
var _a63;
var SQLiteUpdateBase = class extends QueryPromise {
constructor(table, set, session, dialect) {
super();
this.session = session;
this.dialect = dialect;
this.config = { set, table };
}
/** @internal */
config;
/**
* Adds a 'where' clause to the query.
*
* Calling this method will update only those rows that fulfill a specified condition.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param where the 'where' clause.
*
* @example
* You can use conditional operators and `sql function` to filter the rows to be updated.
*
* ```ts
* // Update all cars with green color
* db.update(cars).set({ color: 'red' })
* .where(eq(cars.color, 'green'));
* // or
* db.update(cars).set({ color: 'red' })
* .where(sql`${cars.color} = 'green'`)
* ```
*
* You can logically combine conditional operators with `and()` and `or()` operators:
*
* ```ts
* // Update all BMW cars with a green color
* db.update(cars).set({ color: 'red' })
* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
*
* // Update all cars with the green or blue color
* db.update(cars).set({ color: 'red' })
* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
where(where) {
this.config.where = where;
return this;
}
returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
this.config.returning = orderSelectedFields(fields);
return this;
}
/** @internal */
getSQL() {
return this.dialect.buildUpdateQuery(this.config);
}
toSQL() {
const { typings: _typings, ...rest } = this.dialect.sqlToQuery(
this.getSQL()
);
return rest;
}
prepare(isOneTimeQuery) {
return this.session[
isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"
](
this.dialect.sqlToQuery(this.getSQL()),
this.config.returning,
this.config.returning ? "all" : "run"
);
}
run = (placeholderValues) => {
return this.prepare(true).run(placeholderValues);
};
all = (placeholderValues) => {
return this.prepare(true).all(placeholderValues);
};
get = (placeholderValues) => {
return this.prepare(true).get(placeholderValues);
};
values = (placeholderValues) => {
return this.prepare(true).values(placeholderValues);
};
async execute() {
return this.config.returning ? this.all() : this.run();
}
$dynamic() {
return this;
}
};
_a63 = entityKind;
__publicField(SQLiteUpdateBase, _a63, "SQLiteUpdate");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/query.js
var _a64;
var RelationalQueryBuilder = class {
constructor(
mode,
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
dialect,
session
) {
this.mode = mode;
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
}
findMany(config) {
return this.mode === "sync"
? new SQLiteSyncRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
)
: new SQLiteRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? config : {},
"many"
);
}
findFirst(config) {
return this.mode === "sync"
? new SQLiteSyncRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
)
: new SQLiteRelationalQuery(
this.fullSchema,
this.schema,
this.tableNamesMap,
this.table,
this.tableConfig,
this.dialect,
this.session,
config ? { ...config, limit: 1 } : { limit: 1 },
"first"
);
}
};
_a64 = entityKind;
__publicField(
RelationalQueryBuilder,
_a64,
"SQLiteAsyncRelationalQueryBuilder"
);
var _a65;
var SQLiteRelationalQuery = class extends QueryPromise {
constructor(
fullSchema,
schema,
tableNamesMap,
table,
tableConfig,
dialect,
session,
config,
mode
) {
super();
this.fullSchema = fullSchema;
this.schema = schema;
this.tableNamesMap = tableNamesMap;
this.table = table;
this.tableConfig = tableConfig;
this.dialect = dialect;
this.session = session;
this.config = config;
this.mode = mode;
}
/** @internal */
mode;
/** @internal */
getSQL() {
return this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
}).sql;
}
prepare() {
const { query, builtQuery } = this._toSQL();
return this.session.prepareQuery(
builtQuery,
void 0,
this.mode === "first" ? "get" : "all",
(rawRows, mapColumnValue) => {
const rows = rawRows.map((row) =>
mapRelationalRow(
this.schema,
this.tableConfig,
row,
query.selection,
mapColumnValue
)
);
if (this.mode === "first") {
return rows[0];
}
return rows;
}
);
}
_toSQL() {
const query = this.dialect.buildRelationalQuery({
fullSchema: this.fullSchema,
schema: this.schema,
tableNamesMap: this.tableNamesMap,
table: this.table,
tableConfig: this.tableConfig,
queryConfig: this.config,
tableAlias: this.tableConfig.tsName,
});
const builtQuery = this.dialect.sqlToQuery(query.sql);
return { query, builtQuery };
}
toSQL() {
return this._toSQL().builtQuery;
}
/** @internal */
executeRaw() {
if (this.mode === "first") {
return this.prepare().get();
}
return this.prepare().all();
}
async execute() {
return this.executeRaw();
}
};
_a65 = entityKind;
__publicField(SQLiteRelationalQuery, _a65, "SQLiteAsyncRelationalQuery");
var _a66;
var SQLiteSyncRelationalQuery = class extends SQLiteRelationalQuery {
sync() {
return this.executeRaw();
}
};
_a66 = entityKind;
__publicField(SQLiteSyncRelationalQuery, _a66, "SQLiteSyncRelationalQuery");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js
var _a67;
var SQLiteRaw = class extends QueryPromise {
constructor(cb, getSQLCb, action, dialect, mapBatchResult) {
super();
this.cb = cb;
this.getSQLCb = getSQLCb;
this.dialect = dialect;
this.mapBatchResult = mapBatchResult;
this.config = { action };
}
/** @internal */
config;
/** @internal */
getSQL() {
return this.getSQLCb();
}
async execute() {
return this.cb();
}
prepare() {
return {
getQuery: () => {
return this.dialect.sqlToQuery(this.getSQL());
},
mapResult: (result, isFromBatch) => {
return isFromBatch ? this.mapBatchResult(result) : result;
},
};
}
};
_a67 = entityKind;
__publicField(SQLiteRaw, _a67, "SQLiteRaw");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/db.js
var _a68;
var BaseSQLiteDatabase = class {
constructor(resultKind, dialect, session, schema) {
this.resultKind = resultKind;
this.dialect = dialect;
this.session = session;
this._ = schema
? { schema: schema.schema, tableNamesMap: schema.tableNamesMap }
: { schema: void 0, tableNamesMap: {} };
this.query = {};
if (this._.schema) {
for (const [tableName, columns] of Object.entries(this._.schema)) {
this.query[tableName] = new RelationalQueryBuilder(
resultKind,
schema.fullSchema,
this._.schema,
this._.tableNamesMap,
schema.fullSchema[tableName],
columns,
dialect,
session
);
}
}
}
query;
/**
* Creates a subquery that defines a temporary named result set as a CTE.
*
* It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
*
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
*
* @param alias The alias for the subquery.
*
* Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
*
* @example
*
* ```ts
* // Create a subquery with alias 'sq' and use it in the select query
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
*
* const result = await db.with(sq).select().from(sq);
* ```
*
* To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
*
* ```ts
* // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
* const sq = db.$with('sq').as(db.select({
* name: sql<string>`upper(${users.name})`.as('name'),
* })
* .from(users));
*
* const result = await db.with(sq).select({ name: sq.name }).from(sq);
* ```
*/
$with(alias) {
return {
as(qb) {
if (typeof qb === "function") {
qb = qb(new QueryBuilder());
}
return new Proxy(
new WithSubquery(qb.getSQL(), qb.getSelectedFields(), alias, true),
new SelectionProxyHandler({
alias,
sqlAliasedBehavior: "alias",
sqlBehavior: "error",
})
);
},
};
}
/**
* Incorporates a previously defined CTE (using `$with`) into the main query.
*
* This method allows the main query to reference a temporary named result set.
*
* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
*
* @param queries The CTEs to incorporate into the main query.
*
* @example
*
* ```ts
* // Define a subquery 'sq' as a CTE using $with
* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
*
* // Incorporate the CTE 'sq' into the main query and select from it
* const result = await db.with(sq).select().from(sq);
* ```
*/
with(...queries) {
const self2 = this;
function select(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: self2.session,
dialect: self2.dialect,
withList: queries,
});
}
function selectDistinct(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: self2.session,
dialect: self2.dialect,
withList: queries,
distinct: true,
});
}
return { select, selectDistinct };
}
select(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: this.session,
dialect: this.dialect,
});
}
selectDistinct(fields) {
return new SQLiteSelectBuilder({
fields: fields ?? void 0,
session: this.session,
dialect: this.dialect,
distinct: true,
});
}
/**
* Creates an update query.
*
* Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
*
* Use `.set()` method to specify which values to update.
*
* See docs: {@link https://orm.drizzle.team/docs/update}
*
* @param table The table to update.
*
* @example
*
* ```ts
* // Update all rows in the 'cars' table
* await db.update(cars).set({ color: 'red' });
*
* // Update rows with filters and conditions
* await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
*
* // Update with returning clause
* const updatedCar: Car[] = await db.update(cars)
* .set({ color: 'red' })
* .where(eq(cars.id, 1))
* .returning();
* ```
*/
update(table) {
return new SQLiteUpdateBuilder(table, this.session, this.dialect);
}
/**
* Creates an insert query.
*
* Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
*
* See docs: {@link https://orm.drizzle.team/docs/insert}
*
* @param table The table to insert into.
*
* @example
*
* ```ts
* // Insert one row
* await db.insert(cars).values({ brand: 'BMW' });
*
* // Insert multiple rows
* await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
*
* // Insert with returning clause
* const insertedCar: Car[] = await db.insert(cars)
* .values({ brand: 'BMW' })
* .returning();
* ```
*/
insert(into) {
return new SQLiteInsertBuilder(into, this.session, this.dialect);
}
/**
* Creates a delete query.
*
* Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
*
* See docs: {@link https://orm.drizzle.team/docs/delete}
*
* @param table The table to delete from.
*
* @example
*
* ```ts
* // Delete all rows in the 'cars' table
* await db.delete(cars);
*
* // Delete rows with filters and conditions
* await db.delete(cars).where(eq(cars.color, 'green'));
*
* // Delete with returning clause
* const deletedCar: Car[] = await db.delete(cars)
* .where(eq(cars.id, 1))
* .returning();
* ```
*/
delete(from) {
return new SQLiteDeleteBase(from, this.session, this.dialect);
}
run(query) {
const sql2 = query.getSQL();
if (this.resultKind === "async") {
return new SQLiteRaw(
async () => this.session.run(sql2),
() => sql2,
"run",
this.dialect,
this.session.extractRawRunValueFromBatchResult.bind(this.session)
);
}
return this.session.run(sql2);
}
all(query) {
const sql2 = query.getSQL();
if (this.resultKind === "async") {
return new SQLiteRaw(
async () => this.session.all(sql2),
() => sql2,
"all",
this.dialect,
this.session.extractRawAllValueFromBatchResult.bind(this.session)
);
}
return this.session.all(sql2);
}
get(query) {
const sql2 = query.getSQL();
if (this.resultKind === "async") {
return new SQLiteRaw(
async () => this.session.get(sql2),
() => sql2,
"get",
this.dialect,
this.session.extractRawGetValueFromBatchResult.bind(this.session)
);
}
return this.session.get(sql2);
}
values(query) {
const sql2 = query.getSQL();
if (this.resultKind === "async") {
return new SQLiteRaw(
async () => this.session.values(sql2),
() => sql2,
"values",
this.dialect,
this.session.extractRawValuesValueFromBatchResult.bind(this.session)
);
}
return this.session.values(sql2);
}
transaction(transaction, config) {
return this.session.transaction(transaction, config);
}
};
_a68 = entityKind;
__publicField(BaseSQLiteDatabase, _a68, "BaseSQLiteDatabase");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/sqlite-core/session.js
var _a69;
var ExecuteResultSync = class extends QueryPromise {
constructor(resultCb) {
super();
this.resultCb = resultCb;
}
async execute() {
return this.resultCb();
}
sync() {
return this.resultCb();
}
};
_a69 = entityKind;
__publicField(ExecuteResultSync, _a69, "ExecuteResultSync");
var _a70;
var SQLitePreparedQuery = class {
constructor(mode, executeMethod, query) {
this.mode = mode;
this.executeMethod = executeMethod;
this.query = query;
}
/** @internal */
joinsNotNullableMap;
getQuery() {
return this.query;
}
mapRunResult(result, _isFromBatch) {
return result;
}
mapAllResult(_result, _isFromBatch) {
throw new Error("Not implemented");
}
mapGetResult(_result, _isFromBatch) {
throw new Error("Not implemented");
}
execute(placeholderValues) {
if (this.mode === "async") {
return this[this.executeMethod](placeholderValues);
}
return new ExecuteResultSync(() =>
this[this.executeMethod](placeholderValues)
);
}
mapResult(response, isFromBatch) {
switch (this.executeMethod) {
case "run": {
return this.mapRunResult(response, isFromBatch);
}
case "all": {
return this.mapAllResult(response, isFromBatch);
}
case "get": {
return this.mapGetResult(response, isFromBatch);
}
}
}
};
_a70 = entityKind;
__publicField(SQLitePreparedQuery, _a70, "PreparedQuery");
var _a71;
var SQLiteSession = class {
constructor(dialect) {
this.dialect = dialect;
}
prepareOneTimeQuery(query, fields, executeMethod) {
return this.prepareQuery(query, fields, executeMethod);
}
run(query) {
const staticQuery = this.dialect.sqlToQuery(query);
try {
return this.prepareOneTimeQuery(staticQuery, void 0, "run").run();
} catch (err) {
throw new DrizzleError({
cause: err,
message: `Failed to run the query '${staticQuery.sql}'`,
});
}
}
/** @internal */
extractRawRunValueFromBatchResult(result) {
return result;
}
all(query) {
return this.prepareOneTimeQuery(
this.dialect.sqlToQuery(query),
void 0,
"run"
).all();
}
/** @internal */
extractRawAllValueFromBatchResult(_result) {
throw new Error("Not implemented");
}
get(query) {
return this.prepareOneTimeQuery(
this.dialect.sqlToQuery(query),
void 0,
"run"
).get();
}
/** @internal */
extractRawGetValueFromBatchResult(_result) {
throw new Error("Not implemented");
}
values(query) {
return this.prepareOneTimeQuery(
this.dialect.sqlToQuery(query),
void 0,
"run"
).values();
}
/** @internal */
extractRawValuesValueFromBatchResult(_result) {
throw new Error("Not implemented");
}
};
_a71 = entityKind;
__publicField(SQLiteSession, _a71, "SQLiteSession");
var _a72;
var SQLiteTransaction = class extends BaseSQLiteDatabase {
constructor(resultType, dialect, session, schema, nestedIndex = 0) {
super(resultType, dialect, session, schema);
this.schema = schema;
this.nestedIndex = nestedIndex;
}
rollback() {
throw new TransactionRollbackError();
}
};
_a72 = entityKind;
__publicField(SQLiteTransaction, _a72, "SQLiteTransaction");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/table.js
var InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
var _a73;
var MySqlTable = class extends Table {
/** @internal */
[((_a73 = entityKind), Table.Symbol.Columns)];
/** @internal */
[InlineForeignKeys3] = [];
/** @internal */
[Table.Symbol.ExtraConfigBuilder] = void 0;
};
__publicField(MySqlTable, _a73, "MySqlTable");
/** @internal */
__publicField(
MySqlTable,
"Symbol",
Object.assign({}, Table.Symbol, {
InlineForeignKeys: InlineForeignKeys3,
})
);
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/foreign-keys.js
var _a74;
var ForeignKeyBuilder2 = class {
/** @internal */
reference;
/** @internal */
_onUpdate;
/** @internal */
_onDelete;
constructor(config, actions) {
this.reference = () => {
const { name, columns, foreignColumns } = config();
return {
name,
columns,
foreignTable: foreignColumns[0].table,
foreignColumns,
};
};
if (actions) {
this._onUpdate = actions.onUpdate;
this._onDelete = actions.onDelete;
}
}
onUpdate(action) {
this._onUpdate = action;
return this;
}
onDelete(action) {
this._onDelete = action;
return this;
}
/** @internal */
build(table) {
return new ForeignKey2(table, this);
}
};
_a74 = entityKind;
__publicField(ForeignKeyBuilder2, _a74, "MySqlForeignKeyBuilder");
var _a75;
var ForeignKey2 = class {
constructor(table, builder) {
this.table = table;
this.reference = builder.reference;
this.onUpdate = builder._onUpdate;
this.onDelete = builder._onDelete;
}
reference;
onUpdate;
onDelete;
getName() {
const { name, columns, foreignColumns } = this.reference();
const columnNames = columns.map((column) => column.name);
const foreignColumnNames = foreignColumns.map((column) => column.name);
const chunks = [
this.table[MySqlTable.Symbol.Name],
...columnNames,
foreignColumns[0].table[MySqlTable.Symbol.Name],
...foreignColumnNames,
];
return name ?? `${chunks.join("_")}_fk`;
}
};
_a75 = entityKind;
__publicField(ForeignKey2, _a75, "MySqlForeignKey");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/unique-constraint.js
function uniqueKeyName2(table, columns) {
return `${table[MySqlTable.Symbol.Name]}_${columns.join("_")}_unique`;
}
var _a76;
var UniqueConstraintBuilder2 = class {
constructor(columns, name) {
this.name = name;
this.columns = columns;
}
/** @internal */
columns;
/** @internal */
build(table) {
return new UniqueConstraint2(table, this.columns, this.name);
}
};
_a76 = entityKind;
__publicField(UniqueConstraintBuilder2, _a76, "MySqlUniqueConstraintBuilder");
var _a77;
var UniqueOnConstraintBuilder2 = class {
/** @internal */
name;
constructor(name) {
this.name = name;
}
on(...columns) {
return new UniqueConstraintBuilder2(columns, this.name);
}
};
_a77 = entityKind;
__publicField(
UniqueOnConstraintBuilder2,
_a77,
"MySqlUniqueOnConstraintBuilder"
);
var _a78;
var UniqueConstraint2 = class {
constructor(table, columns, name) {
this.table = table;
this.columns = columns;
this.name =
name ??
uniqueKeyName2(
this.table,
this.columns.map((column) => column.name)
);
}
columns;
name;
nullsNotDistinct = false;
getName() {
return this.name;
}
};
_a78 = entityKind;
__publicField(UniqueConstraint2, _a78, "MySqlUniqueConstraint");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/columns/common.js
var _a79;
var MySqlColumnBuilder = class extends ColumnBuilder {
foreignKeyConfigs = [];
references(ref, actions = {}) {
this.foreignKeyConfigs.push({ ref, actions });
return this;
}
unique(name) {
this.config.isUnique = true;
this.config.uniqueName = name;
return this;
}
/** @internal */
buildForeignKeys(column, table) {
return this.foreignKeyConfigs.map(({ ref, actions }) => {
return ((ref2, actions2) => {
const builder = new ForeignKeyBuilder2(() => {
const foreignColumn = ref2();
return { columns: [column], foreignColumns: [foreignColumn] };
});
if (actions2.onUpdate) {
builder.onUpdate(actions2.onUpdate);
}
if (actions2.onDelete) {
builder.onDelete(actions2.onDelete);
}
return builder.build(table);
})(ref, actions);
});
}
};
_a79 = entityKind;
__publicField(MySqlColumnBuilder, _a79, "MySqlColumnBuilder");
var _a80;
var MySqlColumn = class extends Column {
constructor(table, config) {
if (!config.uniqueName) {
config.uniqueName = uniqueKeyName2(table, [config.name]);
}
super(table, config);
this.table = table;
}
};
_a80 = entityKind;
__publicField(MySqlColumn, _a80, "MySqlColumn");
var _a81;
var MySqlColumnBuilderWithAutoIncrement = class extends MySqlColumnBuilder {
constructor(name, dataType, columnType) {
super(name, dataType, columnType);
this.config.autoIncrement = false;
}
autoincrement() {
this.config.autoIncrement = true;
this.config.hasDefault = true;
return this;
}
};
_a81 = entityKind;
__publicField(
MySqlColumnBuilderWithAutoIncrement,
_a81,
"MySqlColumnBuilderWithAutoIncrement"
);
var _a82;
var MySqlColumnWithAutoIncrement = class extends MySqlColumn {
autoIncrement = this.config.autoIncrement;
};
_a82 = entityKind;
__publicField(
MySqlColumnWithAutoIncrement,
_a82,
"MySqlColumnWithAutoIncrement"
);
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/columns/char.js
var _a83;
var MySqlCharBuilder = class extends MySqlColumnBuilder {
constructor(name, config) {
super(name, "string", "MySqlChar");
this.config.length = config.length;
this.config.enum = config.enum;
}
/** @internal */
build(table) {
return new MySqlChar(table, this.config);
}
};
_a83 = entityKind;
__publicField(MySqlCharBuilder, _a83, "MySqlCharBuilder");
var _a84;
var MySqlChar = class extends MySqlColumn {
length = this.config.length;
enumValues = this.config.enum;
getSQLType() {
return this.length === void 0 ? `char` : `char(${this.length})`;
}
};
_a84 = entityKind;
__publicField(MySqlChar, _a84, "MySqlChar");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/columns/varbinary.js
var _a85;
var MySqlVarBinaryBuilder = class extends MySqlColumnBuilder {
/** @internal */
constructor(name, config) {
super(name, "string", "MySqlVarBinary");
this.config.length = config?.length;
}
/** @internal */
build(table) {
return new MySqlVarBinary(table, this.config);
}
};
_a85 = entityKind;
__publicField(MySqlVarBinaryBuilder, _a85, "MySqlVarBinaryBuilder");
var _a86;
var MySqlVarBinary = class extends MySqlColumn {
length = this.config.length;
getSQLType() {
return this.length === void 0 ? `varbinary` : `varbinary(${this.length})`;
}
};
_a86 = entityKind;
__publicField(MySqlVarBinary, _a86, "MySqlVarBinary");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/mysql-core/columns/varchar.js
var _a87;
var MySqlVarCharBuilder = class extends MySqlColumnBuilder {
/** @internal */
constructor(name, config) {
super(name, "string", "MySqlVarChar");
this.config.length = config.length;
this.config.enum = config.enum;
}
/** @internal */
build(table) {
return new MySqlVarChar(table, this.config);
}
};
_a87 = entityKind;
__publicField(MySqlVarCharBuilder, _a87, "MySqlVarCharBuilder");
var _a88;
var MySqlVarChar = class extends MySqlColumn {
length = this.config.length;
enumValues = this.config.enum;
getSQLType() {
return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
}
};
_a88 = entityKind;
__publicField(MySqlVarChar, _a88, "MySqlVarChar");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/foreign-keys.js
var _a89;
var ForeignKeyBuilder3 = class {
/** @internal */
reference;
/** @internal */
_onUpdate = "no action";
/** @internal */
_onDelete = "no action";
constructor(config, actions) {
this.reference = () => {
const { name, columns, foreignColumns } = config();
return {
name,
columns,
foreignTable: foreignColumns[0].table,
foreignColumns,
};
};
if (actions) {
this._onUpdate = actions.onUpdate;
this._onDelete = actions.onDelete;
}
}
onUpdate(action) {
this._onUpdate = action === void 0 ? "no action" : action;
return this;
}
onDelete(action) {
this._onDelete = action === void 0 ? "no action" : action;
return this;
}
/** @internal */
build(table) {
return new ForeignKey3(table, this);
}
};
_a89 = entityKind;
__publicField(ForeignKeyBuilder3, _a89, "PgForeignKeyBuilder");
var _a90;
var ForeignKey3 = class {
constructor(table, builder) {
this.table = table;
this.reference = builder.reference;
this.onUpdate = builder._onUpdate;
this.onDelete = builder._onDelete;
}
reference;
onUpdate;
onDelete;
getName() {
const { name, columns, foreignColumns } = this.reference();
const columnNames = columns.map((column) => column.name);
const foreignColumnNames = foreignColumns.map((column) => column.name);
const chunks = [
this.table[PgTable.Symbol.Name],
...columnNames,
foreignColumns[0].table[PgTable.Symbol.Name],
...foreignColumnNames,
];
return name ?? `${chunks.join("_")}_fk`;
}
};
_a90 = entityKind;
__publicField(ForeignKey3, _a90, "PgForeignKey");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/unique-constraint.js
function uniqueKeyName3(table, columns) {
return `${table[PgTable.Symbol.Name]}_${columns.join("_")}_unique`;
}
var _a91;
var UniqueConstraintBuilder3 = class {
constructor(columns, name) {
this.name = name;
this.columns = columns;
}
/** @internal */
columns;
/** @internal */
nullsNotDistinctConfig = false;
nullsNotDistinct() {
this.nullsNotDistinctConfig = true;
return this;
}
/** @internal */
build(table) {
return new UniqueConstraint3(
table,
this.columns,
this.nullsNotDistinctConfig,
this.name
);
}
};
_a91 = entityKind;
__publicField(UniqueConstraintBuilder3, _a91, "PgUniqueConstraintBuilder");
var _a92;
var UniqueOnConstraintBuilder3 = class {
/** @internal */
name;
constructor(name) {
this.name = name;
}
on(...columns) {
return new UniqueConstraintBuilder3(columns, this.name);
}
};
_a92 = entityKind;
__publicField(UniqueOnConstraintBuilder3, _a92, "PgUniqueOnConstraintBuilder");
var _a93;
var UniqueConstraint3 = class {
constructor(table, columns, nullsNotDistinct, name) {
this.table = table;
this.columns = columns;
this.name =
name ??
uniqueKeyName3(
this.table,
this.columns.map((column) => column.name)
);
this.nullsNotDistinct = nullsNotDistinct;
}
columns;
name;
nullsNotDistinct = false;
getName() {
return this.name;
}
};
_a93 = entityKind;
__publicField(UniqueConstraint3, _a93, "PgUniqueConstraint");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/utils/array.js
function parsePgArrayValue(arrayString, startFrom, inQuotes) {
for (let i = startFrom; i < arrayString.length; i++) {
const char = arrayString[i];
if (char === "\\") {
i++;
continue;
}
if (char === '"') {
return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
}
if (inQuotes) {
continue;
}
if (char === "," || char === "}") {
return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
}
}
return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
}
function parsePgNestedArray(arrayString, startFrom = 0) {
const result = [];
let i = startFrom;
let lastCharIsComma = false;
while (i < arrayString.length) {
const char = arrayString[i];
if (char === ",") {
if (lastCharIsComma || i === startFrom) {
result.push("");
}
lastCharIsComma = true;
i++;
continue;
}
lastCharIsComma = false;
if (char === "\\") {
i += 2;
continue;
}
if (char === '"') {
const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
result.push(value2);
i = startFrom2;
continue;
}
if (char === "}") {
return [result, i + 1];
}
if (char === "{") {
const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
result.push(value2);
i = startFrom2;
continue;
}
const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
result.push(value);
i = newStartFrom;
}
return [result, i];
}
function parsePgArray(arrayString) {
const [result] = parsePgNestedArray(arrayString, 1);
return result;
}
function makePgArray(array2) {
return `{${array2
.map((item) => {
if (Array.isArray(item)) {
return makePgArray(item);
}
if (typeof item === "string") {
return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
return `${item}`;
})
.join(",")}}`;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/columns/common.js
var _a94;
var PgColumnBuilder = class extends ColumnBuilder {
foreignKeyConfigs = [];
array(size) {
return new PgArrayBuilder(this.config.name, this, size);
}
references(ref, actions = {}) {
this.foreignKeyConfigs.push({ ref, actions });
return this;
}
unique(name, config) {
this.config.isUnique = true;
this.config.uniqueName = name;
this.config.uniqueType = config?.nulls;
return this;
}
/** @internal */
buildForeignKeys(column, table) {
return this.foreignKeyConfigs.map(({ ref, actions }) => {
return iife(
(ref2, actions2) => {
const builder = new ForeignKeyBuilder3(() => {
const foreignColumn = ref2();
return { columns: [column], foreignColumns: [foreignColumn] };
});
if (actions2.onUpdate) {
builder.onUpdate(actions2.onUpdate);
}
if (actions2.onDelete) {
builder.onDelete(actions2.onDelete);
}
return builder.build(table);
},
ref,
actions
);
});
}
};
_a94 = entityKind;
__publicField(PgColumnBuilder, _a94, "PgColumnBuilder");
var _a95;
var PgColumn = class extends Column {
constructor(table, config) {
if (!config.uniqueName) {
config.uniqueName = uniqueKeyName3(table, [config.name]);
}
super(table, config);
this.table = table;
}
};
_a95 = entityKind;
__publicField(PgColumn, _a95, "PgColumn");
var _a96;
var PgArrayBuilder = class extends PgColumnBuilder {
constructor(name, baseBuilder, size) {
super(name, "array", "PgArray");
this.config.baseBuilder = baseBuilder;
this.config.size = size;
}
/** @internal */
build(table) {
const baseColumn = this.config.baseBuilder.build(table);
return new PgArray(table, this.config, baseColumn);
}
};
_a96 = entityKind;
__publicField(PgArrayBuilder, _a96, "PgArrayBuilder");
var _a97;
var _PgArray = class extends PgColumn {
constructor(table, config, baseColumn, range) {
super(table, config);
this.baseColumn = baseColumn;
this.range = range;
this.size = config.size;
}
size;
getSQLType() {
return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
}
mapFromDriverValue(value) {
if (typeof value === "string") {
value = parsePgArray(value);
}
return value.map((v) => this.baseColumn.mapFromDriverValue(v));
}
mapToDriverValue(value, isNestedArray = false) {
const a = value.map((v) =>
v === null
? null
: is(this.baseColumn, _PgArray)
? this.baseColumn.mapToDriverValue(v, true)
: this.baseColumn.mapToDriverValue(v)
);
if (isNestedArray) return a;
return makePgArray(a);
}
};
var PgArray = _PgArray;
_a97 = entityKind;
__publicField(PgArray, _a97, "PgArray");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/columns/char.js
var _a98;
var PgCharBuilder = class extends PgColumnBuilder {
constructor(name, config) {
super(name, "string", "PgChar");
this.config.length = config.length;
this.config.enumValues = config.enum;
}
/** @internal */
build(table) {
return new PgChar(table, this.config);
}
};
_a98 = entityKind;
__publicField(PgCharBuilder, _a98, "PgCharBuilder");
var _a99;
var PgChar = class extends PgColumn {
length = this.config.length;
enumValues = this.config.enumValues;
getSQLType() {
return this.length === void 0 ? `char` : `char(${this.length})`;
}
};
_a99 = entityKind;
__publicField(PgChar, _a99, "PgChar");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/columns/uuid.js
var _a100;
var PgUUIDBuilder = class extends PgColumnBuilder {
constructor(name) {
super(name, "string", "PgUUID");
}
/**
* Adds `default gen_random_uuid()` to the column definition.
*/
defaultRandom() {
return this.default(sql`gen_random_uuid()`);
}
/** @internal */
build(table) {
return new PgUUID(table, this.config);
}
};
_a100 = entityKind;
__publicField(PgUUIDBuilder, _a100, "PgUUIDBuilder");
var _a101;
var PgUUID = class extends PgColumn {
getSQLType() {
return "uuid";
}
};
_a101 = entityKind;
__publicField(PgUUID, _a101, "PgUUID");
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/pg-core/columns/varchar.js
var _a102;
var PgVarcharBuilder = class extends PgColumnBuilder {
constructor(name, config) {
super(name, "string", "PgVarchar");
this.config.length = config.length;
this.config.enumValues = config.enum;
}
/** @internal */
build(table) {
return new PgVarchar(table, this.config);
}
};
_a102 = entityKind;
__publicField(PgVarcharBuilder, _a102, "PgVarcharBuilder");
var _a103;
var PgVarchar = class extends PgColumn {
length = this.config.length;
enumValues = this.config.enumValues;
getSQLType() {
return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
}
};
_a103 = entityKind;
__publicField(PgVarchar, _a103, "PgVarchar");
// ../../node_modules/.pnpm/zod@3.22.4/node_modules/zod/lib/index.mjs
var util;
(function (util2) {
util2.assertEqual = (val) => val;
function assertIs(_arg) {}
util2.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util2.assertNever = assertNever;
util2.arrayToEnum = (items) => {
const obj = {};
for (const item of items) {
obj[item] = item;
}
return obj;
};
util2.getValidEnumValues = (obj) => {
const validKeys = util2
.objectKeys(obj)
.filter((k) => typeof obj[obj[k]] !== "number");
const filtered = {};
for (const k of validKeys) {
filtered[k] = obj[k];
}
return util2.objectValues(filtered);
};
util2.objectValues = (obj) => {
return util2.objectKeys(obj).map(function (e) {
return obj[e];
});
};
util2.objectKeys =
typeof Object.keys === "function"
? (obj) => Object.keys(obj)
: (object2) => {
const keys = [];
for (const key in object2) {
if (Object.prototype.hasOwnProperty.call(object2, key)) {
keys.push(key);
}
}
return keys;
};
util2.find = (arr, checker) => {
for (const item of arr) {
if (checker(item)) return item;
}
return void 0;
};
util2.isInteger =
typeof Number.isInteger === "function"
? (val) => Number.isInteger(val)
: (val) =>
typeof val === "number" && isFinite(val) && Math.floor(val) === val;
function joinValues(array2, separator = " | ") {
return array2
.map((val) => (typeof val === "string" ? `'${val}'` : val))
.join(separator);
}
util2.joinValues = joinValues;
util2.jsonStringifyReplacer = (_, value) => {
if (typeof value === "bigint") {
return value.toString();
}
return value;
};
})(util || (util = {}));
var objectUtil;
(function (objectUtil2) {
objectUtil2.mergeShapes = (first, second) => {
return {
...first,
...second,
// second overwrites first
};
};
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set",
]);
var getParsedType = (data) => {
const t = typeof data;
switch (t) {
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) {
return ZodParsedType.array;
}
if (data === null) {
return ZodParsedType.null;
}
if (
data.then &&
typeof data.then === "function" &&
data.catch &&
typeof data.catch === "function"
) {
return ZodParsedType.promise;
}
if (typeof Map !== "undefined" && data instanceof Map) {
return ZodParsedType.map;
}
if (typeof Set !== "undefined" && data instanceof Set) {
return ZodParsedType.set;
}
if (typeof Date !== "undefined" && data instanceof Date) {
return ZodParsedType.date;
}
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
var ZodIssueCode = util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite",
]);
var quotelessJson = (obj) => {
const json = JSON.stringify(obj, null, 2);
return json.replace(/"([^"]+)":/g, "$1:");
};
var ZodError = class extends Error {
constructor(issues) {
super();
this.issues = [];
this.addIssue = (sub) => {
this.issues = [...this.issues, sub];
};
this.addIssues = (subs = []) => {
this.issues = [...this.issues, ...subs];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) {
Object.setPrototypeOf(this, actualProto);
} else {
this.__proto__ = actualProto;
}
this.name = "ZodError";
this.issues = issues;
}
get errors() {
return this.issues;
}
format(_mapper) {
const mapper =
_mapper ||
function (issue) {
return issue.message;
};
const fieldErrors = { _errors: [] };
const processError = (error) => {
for (const issue of error.issues) {
if (issue.code === "invalid_union") {
issue.unionErrors.map(processError);
} else if (issue.code === "invalid_return_type") {
processError(issue.returnTypeError);
} else if (issue.code === "invalid_arguments") {
processError(issue.argumentsError);
} else if (issue.path.length === 0) {
fieldErrors._errors.push(mapper(issue));
} else {
let curr = fieldErrors;
let i = 0;
while (i < issue.path.length) {
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (!terminal) {
curr[el] = curr[el] || { _errors: [] };
} else {
curr[el] = curr[el] || { _errors: [] };
curr[el]._errors.push(mapper(issue));
}
curr = curr[el];
i++;
}
}
}
};
processError(this);
return fieldErrors;
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return this.issues.length === 0;
}
flatten(mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues) {
if (sub.path.length > 0) {
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
fieldErrors[sub.path[0]].push(mapper(sub));
} else {
formErrors.push(mapper(sub));
}
}
return { formErrors, fieldErrors };
}
get formErrors() {
return this.flatten();
}
};
ZodError.create = (issues) => {
const error = new ZodError(issues);
return error;
};
var errorMap = (issue, _ctx) => {
let message;
switch (issue.code) {
case ZodIssueCode.invalid_type:
if (issue.received === ZodParsedType.undefined) {
message = "Required";
} else {
message = `Expected ${issue.expected}, received ${issue.received}`;
}
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = `Invalid function arguments`;
break;
case ZodIssueCode.invalid_return_type:
message = `Invalid function return type`;
break;
case ZodIssueCode.invalid_date:
message = `Invalid date`;
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
} else {
util.assertNever(issue.validation);
}
} else if (issue.validation !== "regex") {
message = `Invalid ${issue.validation}`;
} else {
message = "Invalid";
}
break;
case ZodIssueCode.too_small:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
if (issue.type === "array")
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
else if (issue.type === "string")
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
else if (issue.type === "number")
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "bigint")
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
message = `Invalid input`;
break;
case ZodIssueCode.invalid_intersection_types:
message = `Intersection results could not be merged`;
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util.assertNever(issue);
}
return { message };
};
var overrideErrorMap = errorMap;
function setErrorMap(map) {
overrideErrorMap = map;
}
function getErrorMap() {
return overrideErrorMap;
}
var makeIssue = (params) => {
const { data, path, errorMaps, issueData } = params;
const fullPath = [...path, ...(issueData.path || [])];
const fullIssue = {
...issueData,
path: fullPath,
};
let errorMessage = "";
const maps = errorMaps
.filter((m2) => !!m2)
.slice()
.reverse();
for (const map of maps) {
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
}
return {
...issueData,
path: fullPath,
message: issueData.message || errorMessage,
};
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
const issue = makeIssue({
issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap,
// then global default map
].filter((x) => !!x),
});
ctx.common.issues.push(issue);
}
var ParseStatus = class {
constructor() {
this.value = "valid";
}
dirty() {
if (this.value === "valid") this.value = "dirty";
}
abort() {
if (this.value !== "aborted") this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results) {
if (s.status === "aborted") return INVALID;
if (s.status === "dirty") status.dirty();
arrayValue.push(s.value);
}
return { status: status.value, value: arrayValue };
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs) {
syncPairs.push({
key: await pair.key,
value: await pair.value,
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs) {
const { key, value } = pair;
if (key.status === "aborted") return INVALID;
if (value.status === "aborted") return INVALID;
if (key.status === "dirty") status.dirty();
if (value.status === "dirty") status.dirty();
if (
key.value !== "__proto__" &&
(typeof value.value !== "undefined" || pair.alwaysSet)
) {
finalObject[key.value] = value.value;
}
}
return { status: status.value, value: finalObject };
}
};
var INVALID = Object.freeze({
status: "aborted",
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
var errorUtil;
(function (errorUtil2) {
errorUtil2.errToObj = (message) =>
typeof message === "string" ? { message } : message || {};
errorUtil2.toString = (message) =>
typeof message === "string"
? message
: message === null || message === void 0
? void 0
: message.message;
})(errorUtil || (errorUtil = {}));
var ParseInputLazyPath = class {
constructor(parent, value, path, key) {
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) {
if (this._key instanceof Array) {
this._cachedPath.push(...this._path, ...this._key);
} else {
this._cachedPath.push(...this._path, this._key);
}
}
return this._cachedPath;
}
};
var handleResult = (ctx, result) => {
if (isValid(result)) {
return { success: true, data: result.value };
} else {
if (!ctx.common.issues.length) {
throw new Error("Validation failed but no issues detected.");
}
return {
success: false,
get error() {
if (this._error) return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
},
};
}
};
function processCreateParams(params) {
if (!params) return {};
const {
errorMap: errorMap2,
invalid_type_error,
required_error,
description,
} = params;
if (errorMap2 && (invalid_type_error || required_error)) {
throw new Error(
`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`
);
}
if (errorMap2) return { errorMap: errorMap2, description };
const customMap = (iss, ctx) => {
if (iss.code !== "invalid_type") return { message: ctx.defaultError };
if (typeof ctx.data === "undefined") {
return {
message:
required_error !== null && required_error !== void 0
? required_error
: ctx.defaultError,
};
}
return {
message:
invalid_type_error !== null && invalid_type_error !== void 0
? invalid_type_error
: ctx.defaultError,
};
};
return { errorMap: customMap, description };
}
var ZodType = class {
constructor(def) {
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
}
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return (
ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent,
}
);
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent,
},
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) {
throw new Error("Synchronous parse encountered promise.");
}
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data, params) {
var _a108;
const ctx = {
common: {
issues: [],
async:
(_a108 =
params === null || params === void 0 ? void 0 : params.async) !==
null && _a108 !== void 0
? _a108
: false,
contextualErrorMap:
params === null || params === void 0 ? void 0 : params.errorMap,
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};
const result = this._parseSync({ data, path: ctx.path, parent: ctx });
return handleResult(ctx, result);
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap:
params === null || params === void 0 ? void 0 : params.errorMap,
async: true,
},
path: (params === null || params === void 0 ? void 0 : params.path) || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data),
};
const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
const result = await (isAsync(maybeAsyncResult)
? maybeAsyncResult
: Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val) => {
if (typeof message === "string" || typeof message === "undefined") {
return { message };
} else if (typeof message === "function") {
return message(val);
} else {
return message;
}
};
return this._refinement((val, ctx) => {
const result = check(val);
const setError = () =>
ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val),
});
if (typeof Promise !== "undefined" && result instanceof Promise) {
return result.then((data) => {
if (!data) {
setError();
return false;
} else {
return true;
}
});
}
if (!result) {
setError();
return false;
} else {
return true;
}
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx) => {
if (!check(val)) {
ctx.addIssue(
typeof refinementData === "function"
? refinementData(val, ctx)
: refinementData
);
return false;
} else {
return true;
}
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "refinement", refinement },
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this, this._def);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([this, option], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect: { type: "transform", transform },
});
}
default(def) {
const defaultValueFunc = typeof def === "function" ? def : () => def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: ZodFirstPartyTypeKind.ZodDefault,
});
}
brand() {
return new ZodBranded({
typeName: ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def),
});
}
catch(def) {
const catchValueFunc = typeof def === "function" ? def : () => def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: ZodFirstPartyTypeKind.ZodCatch,
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description,
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[a-z][a-z0-9]*$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
var uuidRegex =
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var emailRegex =
/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex =
/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
var ipv6Regex =
/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
var datetimeRegex = (args) => {
if (args.precision) {
if (args.offset) {
return new RegExp(
`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
);
} else {
return new RegExp(
`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`
);
}
} else if (args.precision === 0) {
if (args.offset) {
return new RegExp(
`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`
);
} else {
return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
}
} else {
if (args.offset) {
return new RegExp(
`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`
);
} else {
return new RegExp(
`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`
);
}
}
};
function isValidIP(ip, version3) {
if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
return true;
}
if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
return true;
}
return false;
}
var ZodString = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = String(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(
ctx2,
{
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx2.parsedType,
}
//
);
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "length") {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message,
});
} else if (tooSmall) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message,
});
}
status.dirty();
}
} else if (check.kind === "email") {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "emoji") {
if (!emojiRegex) {
emojiRegex = new RegExp(_emojiRegex, "u");
}
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "uuid") {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "cuid") {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "cuid2") {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "ulid") {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "url") {
try {
new URL(input.data);
} catch (_a108) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "regex") {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message,
});
status.dirty();
}
} else if (check.kind === "toLowerCase") {
input.data = input.data.toLowerCase();
} else if (check.kind === "toUpperCase") {
input.data = input.data.toUpperCase();
} else if (check.kind === "startsWith") {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { startsWith: check.value },
message: check.message,
});
status.dirty();
}
} else if (check.kind === "endsWith") {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { endsWith: check.value },
message: check.message,
});
status.dirty();
}
} else if (check.kind === "datetime") {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message,
});
status.dirty();
}
} else if (check.kind === "ip") {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message,
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
_regex(regex, validation, message) {
return this.refinement((data) => regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil.errToObj(message),
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [...this._def.checks, check],
});
}
email(message) {
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
}
url(message) {
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
}
emoji(message) {
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
}
uuid(message) {
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
}
cuid(message) {
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
}
cuid2(message) {
return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
}
ulid(message) {
return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
}
ip(options) {
return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
}
datetime(options) {
var _a108;
if (typeof options === "string") {
return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
message: options,
});
}
return this._addCheck({
kind: "datetime",
precision:
typeof (options === null || options === void 0
? void 0
: options.precision) === "undefined"
? null
: options === null || options === void 0
? void 0
: options.precision,
offset:
(_a108 =
options === null || options === void 0 ? void 0 : options.offset) !==
null && _a108 !== void 0
? _a108
: false,
...errorUtil.errToObj(
options === null || options === void 0 ? void 0 : options.message
),
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex,
...errorUtil.errToObj(message),
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value,
position:
options === null || options === void 0 ? void 0 : options.position,
...errorUtil.errToObj(
options === null || options === void 0 ? void 0 : options.message
),
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value,
...errorUtil.errToObj(message),
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value,
...errorUtil.errToObj(message),
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil.errToObj(message),
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil.errToObj(message),
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil.errToObj(message),
});
}
/**
* @deprecated Use z.string().min(1) instead.
* @see {@link ZodString.min}
*/
nonempty(message) {
return this.min(1, errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "trim" }],
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toLowerCase" }],
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [...this._def.checks, { kind: "toUpperCase" }],
});
}
get isDatetime() {
return !!this._def.checks.find((ch) => ch.kind === "datetime");
}
get isEmail() {
return !!this._def.checks.find((ch) => ch.kind === "email");
}
get isURL() {
return !!this._def.checks.find((ch) => ch.kind === "url");
}
get isEmoji() {
return !!this._def.checks.find((ch) => ch.kind === "emoji");
}
get isUUID() {
return !!this._def.checks.find((ch) => ch.kind === "uuid");
}
get isCUID() {
return !!this._def.checks.find((ch) => ch.kind === "cuid");
}
get isCUID2() {
return !!this._def.checks.find((ch) => ch.kind === "cuid2");
}
get isULID() {
return !!this._def.checks.find((ch) => ch.kind === "ulid");
}
get isIP() {
return !!this._def.checks.find((ch) => ch.kind === "ip");
}
get minLength() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
}
return max;
}
};
ZodString.create = (params) => {
var _a108;
return new ZodString({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodString,
coerce:
(_a108 =
params === null || params === void 0 ? void 0 : params.coerce) !==
null && _a108 !== void 0
? _a108
: false,
...processCreateParams(params),
});
};
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / Math.pow(10, decCount);
}
var ZodNumber = class extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) {
input.data = Number(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx2.parsedType,
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "int") {
if (!util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message,
});
status.dirty();
}
} else if (check.kind === "min") {
const tooSmall = check.inclusive
? input.data < check.value
: input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive
? input.data > check.value
: input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (floatSafeRemainder(input.data, check.value) !== 0) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "finite") {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message,
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message),
},
],
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [...this._def.checks, check],
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil.toString(message),
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil.toString(message),
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil.toString(message),
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil.toString(message),
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil.toString(message),
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message),
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil.toString(message),
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil.toString(message),
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil.toString(message),
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
}
return max;
}
get isInt() {
return !!this._def.checks.find(
(ch) =>
ch.kind === "int" ||
(ch.kind === "multipleOf" && util.isInteger(ch.value))
);
}
get isFinite() {
let max = null,
min = null;
for (const ch of this._def.checks) {
if (
ch.kind === "finite" ||
ch.kind === "int" ||
ch.kind === "multipleOf"
) {
return true;
} else if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
} else if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
}
return Number.isFinite(min) && Number.isFinite(max);
}
};
ZodNumber.create = (params) => {
return new ZodNumber({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodNumber,
coerce:
(params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params),
});
};
var ZodBigInt = class extends ZodType {
constructor() {
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) {
input.data = BigInt(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx2.parsedType,
});
return INVALID;
}
let ctx = void 0;
const status = new ParseStatus();
for (const check of this._def.checks) {
if (check.kind === "min") {
const tooSmall = check.inclusive
? input.data < check.value
: input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "max") {
const tooBig = check.inclusive
? input.data > check.value
: input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message,
});
status.dirty();
}
} else if (check.kind === "multipleOf") {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message,
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return { status: status.value, value: input.data };
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil.toString(message),
},
],
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [...this._def.checks, check],
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message),
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil.toString(message),
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message),
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil.toString(message),
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil.toString(message),
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
}
return max;
}
};
ZodBigInt.create = (params) => {
var _a108;
return new ZodBigInt({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodBigInt,
coerce:
(_a108 =
params === null || params === void 0 ? void 0 : params.coerce) !==
null && _a108 !== void 0
? _a108
: false,
...processCreateParams(params),
});
};
var ZodBoolean = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = Boolean(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
};
ZodBoolean.create = (params) => {
return new ZodBoolean({
typeName: ZodFirstPartyTypeKind.ZodBoolean,
coerce:
(params === null || params === void 0 ? void 0 : params.coerce) || false,
...processCreateParams(params),
});
};
var ZodDate = class extends ZodType {
_parse(input) {
if (this._def.coerce) {
input.data = new Date(input.data);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx2.parsedType,
});
return INVALID;
}
if (isNaN(input.data.getTime())) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_date,
});
return INVALID;
}
const status = new ParseStatus();
let ctx = void 0;
for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date",
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date",
});
status.dirty();
}
} else {
util.assertNever(check);
}
}
return {
status: status.value,
value: new Date(input.data.getTime()),
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check],
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message),
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message),
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks) {
if (ch.kind === "min") {
if (min === null || ch.value > min) min = ch.value;
}
}
return min != null ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks) {
if (ch.kind === "max") {
if (max === null || ch.value < max) max = ch.value;
}
}
return max != null ? new Date(max) : null;
}
};
ZodDate.create = (params) => {
return new ZodDate({
checks: [],
coerce:
(params === null || params === void 0 ? void 0 : params.coerce) || false,
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params),
});
};
var ZodSymbol = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
};
ZodSymbol.create = (params) => {
return new ZodSymbol({
typeName: ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params),
});
};
var ZodUndefined = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
};
ZodUndefined.create = (params) => {
return new ZodUndefined({
typeName: ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params),
});
};
var ZodNull = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.null) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.null,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
};
ZodNull.create = (params) => {
return new ZodNull({
typeName: ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params),
});
};
var ZodAny = class extends ZodType {
constructor() {
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodAny.create = (params) => {
return new ZodAny({
typeName: ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params),
});
};
var ZodUnknown = class extends ZodType {
constructor() {
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
};
ZodUnknown.create = (params) => {
return new ZodUnknown({
typeName: ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params),
});
};
var ZodNever = class extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType,
});
return INVALID;
}
};
ZodNever.create = (params) => {
return new ZodNever({
typeName: ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params),
});
};
var ZodVoid = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.void,
received: ctx.parsedType,
});
return INVALID;
}
return OK(input.data);
}
};
ZodVoid.create = (params) => {
return new ZodVoid({
typeName: ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params),
});
};
var ZodArray = class extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType,
});
return INVALID;
}
if (def.exactLength !== null) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message,
});
status.dirty();
}
}
if (def.minLength !== null) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message,
});
status.dirty();
}
}
if (def.maxLength !== null) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message,
});
status.dirty();
}
}
if (ctx.common.async) {
return Promise.all(
[...ctx.data].map((item, i) => {
return def.type._parseAsync(
new ParseInputLazyPath(ctx, item, ctx.path, i)
);
})
).then((result2) => {
return ParseStatus.mergeArray(status, result2);
});
}
const result = [...ctx.data].map((item, i) => {
return def.type._parseSync(
new ParseInputLazyPath(ctx, item, ctx.path, i)
);
});
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: { value: minLength, message: errorUtil.toString(message) },
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: { value: maxLength, message: errorUtil.toString(message) },
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: { value: len, message: errorUtil.toString(message) },
});
}
nonempty(message) {
return this.min(1, message);
}
};
ZodArray.create = (schema, params) => {
return new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params),
});
};
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for (const key in schema.shape) {
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: () => newShape,
});
} else if (schema instanceof ZodArray) {
return new ZodArray({
...schema._def,
type: deepPartialify(schema.element),
});
} else if (schema instanceof ZodOptional) {
return ZodOptional.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodNullable) {
return ZodNullable.create(deepPartialify(schema.unwrap()));
} else if (schema instanceof ZodTuple) {
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
} else {
return schema;
}
}
var ZodObject = class extends ZodType {
constructor() {
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (this._cached !== null) return this._cached;
const shape = this._def.shape();
const keys = util.objectKeys(shape);
return (this._cached = { shape, keys });
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx2 = this._getOrReturnCtx(input);
addIssueToContext(ctx2, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx2.parsedType,
});
return INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (
!(
this._def.catchall instanceof ZodNever &&
this._def.unknownKeys === "strip"
)
) {
for (const key in ctx.data) {
if (!shapeKeys.includes(key)) {
extraKeys.push(key);
}
}
}
const pairs = [];
for (const key of shapeKeys) {
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: keyValidator._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
),
alwaysSet: key in ctx.data,
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if (unknownKeys === "passthrough") {
for (const key of extraKeys) {
pairs.push({
key: { status: "valid", value: key },
value: { status: "valid", value: ctx.data[key] },
});
}
} else if (unknownKeys === "strict") {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys,
});
status.dirty();
}
} else if (unknownKeys === "strip");
else {
throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
}
} else {
const catchall = this._def.catchall;
for (const key of extraKeys) {
const value = ctx.data[key];
pairs.push({
key: { status: "valid", value: key },
value: catchall._parse(
new ParseInputLazyPath(ctx, value, ctx.path, key)
//, ctx.child(key), value, getParsedType(value)
),
alwaysSet: key in ctx.data,
});
}
}
if (ctx.common.async) {
return Promise.resolve()
.then(async () => {
const syncPairs = [];
for (const pair of pairs) {
const key = await pair.key;
syncPairs.push({
key,
value: await pair.value,
alwaysSet: pair.alwaysSet,
});
}
return syncPairs;
})
.then((syncPairs) => {
return ParseStatus.mergeObjectSync(status, syncPairs);
});
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...(message !== void 0
? {
errorMap: (issue, ctx) => {
var _a108, _b, _c, _d;
const defaultError =
(_c =
(_b = (_a108 = this._def).errorMap) === null || _b === void 0
? void 0
: _b.call(_a108, issue, ctx).message) !== null &&
_c !== void 0
? _c
: ctx.defaultError;
if (issue.code === "unrecognized_keys")
return {
message:
(_d = errorUtil.errToObj(message).message) !== null &&
_d !== void 0
? _d
: defaultError,
};
return {
message: defaultError,
};
},
}
: {}),
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip",
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough",
});
}
// const AugmentFactory =
// <Def extends ZodObjectDef>(def: Def) =>
// <Augmentation extends ZodRawShape>(
// augmentation: Augmentation
// ): ZodObject<
// extendShape<ReturnType<Def["shape"]>, Augmentation>,
// Def["unknownKeys"],
// Def["catchall"]
// > => {
// return new ZodObject({
// ...def,
// shape: () => ({
// ...def.shape(),
// ...augmentation,
// }),
// }) as any;
// };
extend(augmentation) {
return new ZodObject({
...this._def,
shape: () => ({
...this._def.shape(),
...augmentation,
}),
});
}
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: () => ({
...this._def.shape(),
...merging._def.shape(),
}),
typeName: ZodFirstPartyTypeKind.ZodObject,
});
return merged;
}
// merge<
// Incoming extends AnyZodObject,
// Augmentation extends Incoming["shape"],
// NewOutput extends {
// [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
// ? Augmentation[k]["_output"]
// : k extends keyof Output
// ? Output[k]
// : never;
// },
// NewInput extends {
// [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
// ? Augmentation[k]["_input"]
// : k extends keyof Input
// ? Input[k]
// : never;
// }
// >(
// merging: Incoming
// ): ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"],
// NewOutput,
// NewInput
// > {
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
setKey(key, schema) {
return this.augment({ [key]: schema });
}
// merge<Incoming extends AnyZodObject>(
// merging: Incoming
// ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
// ZodObject<
// extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
// Incoming["_def"]["unknownKeys"],
// Incoming["_def"]["catchall"]
// > {
// // const mergedShape = objectUtil.mergeShapes(
// // this._def.shape(),
// // merging._def.shape()
// // );
// const merged: any = new ZodObject({
// unknownKeys: merging._def.unknownKeys,
// catchall: merging._def.catchall,
// shape: () =>
// objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
// typeName: ZodFirstPartyTypeKind.ZodObject,
// }) as any;
// return merged;
// }
catchall(index) {
return new ZodObject({
...this._def,
catchall: index,
});
}
pick(mask) {
const shape = {};
util.objectKeys(mask).forEach((key) => {
if (mask[key] && this.shape[key]) {
shape[key] = this.shape[key];
}
});
return new ZodObject({
...this._def,
shape: () => shape,
});
}
omit(mask) {
const shape = {};
util.objectKeys(this.shape).forEach((key) => {
if (!mask[key]) {
shape[key] = this.shape[key];
}
});
return new ZodObject({
...this._def,
shape: () => shape,
});
}
/**
* @deprecated
*/
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
const fieldSchema = this.shape[key];
if (mask && !mask[key]) {
newShape[key] = fieldSchema;
} else {
newShape[key] = fieldSchema.optional();
}
});
return new ZodObject({
...this._def,
shape: () => newShape,
});
}
required(mask) {
const newShape = {};
util.objectKeys(this.shape).forEach((key) => {
if (mask && !mask[key]) {
newShape[key] = this.shape[key];
} else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while (newField instanceof ZodOptional) {
newField = newField._def.innerType;
}
newShape[key] = newField;
}
});
return new ZodObject({
...this._def,
shape: () => newShape,
});
}
keyof() {
return createZodEnum(util.objectKeys(this.shape));
}
};
ZodObject.create = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
ZodObject.strictCreate = (shape, params) => {
return new ZodObject({
shape: () => shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
ZodObject.lazycreate = (shape, params) => {
return new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params),
});
};
var ZodUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results) {
if (result.result.status === "valid") {
return result.result;
}
}
for (const result of results) {
if (result.result.status === "dirty") {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
}
const unionErrors = results.map(
(result) => new ZodError(result.ctx.common.issues)
);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors,
});
return INVALID;
}
if (ctx.common.async) {
return Promise.all(
options.map(async (option) => {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
parent: null,
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx,
}),
ctx: childCtx,
};
})
).then(handleResults);
} else {
let dirty = void 0;
const issues = [];
for (const option of options) {
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
parent: null,
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx,
});
if (result.status === "valid") {
return result;
} else if (result.status === "dirty" && !dirty) {
dirty = { result, ctx: childCtx };
}
if (childCtx.common.issues.length) {
issues.push(childCtx.common.issues);
}
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues2) => new ZodError(issues2));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors,
});
return INVALID;
}
}
get options() {
return this._def.options;
}
};
ZodUnion.create = (types, params) => {
return new ZodUnion({
options: types,
typeName: ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params),
});
};
var getDiscriminator = (type) => {
if (type instanceof ZodLazy) {
return getDiscriminator(type.schema);
} else if (type instanceof ZodEffects) {
return getDiscriminator(type.innerType());
} else if (type instanceof ZodLiteral) {
return [type.value];
} else if (type instanceof ZodEnum) {
return type.options;
} else if (type instanceof ZodNativeEnum) {
return Object.keys(type.enum);
} else if (type instanceof ZodDefault) {
return getDiscriminator(type._def.innerType);
} else if (type instanceof ZodUndefined) {
return [void 0];
} else if (type instanceof ZodNull) {
return [null];
} else {
return null;
}
};
var ZodDiscriminatedUnion = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType,
});
return INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [discriminator],
});
return INVALID;
}
if (ctx.common.async) {
return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
} else {
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
}
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
/**
* The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
* However, it only allows a union of objects, all of which need to share a discriminator property. This property must
* have a different value for each object in the union.
* @param discriminator the name of the discriminator property
* @param types an array of object schemas
* @param params
*/
static create(discriminator, options, params) {
const optionsMap = /* @__PURE__ */ new Map();
for (const type of options) {
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues) {
throw new Error(
`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`
);
}
for (const value of discriminatorValues) {
if (optionsMap.has(value)) {
throw new Error(
`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`
);
}
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params),
});
}
};
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) {
return { valid: true, data: a };
} else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util.objectKeys(b);
const sharedKeys = util
.objectKeys(a)
.filter((key) => bKeys.indexOf(key) !== -1);
const newObj = { ...a, ...b };
for (const key of sharedKeys) {
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) {
return { valid: false };
}
newObj[key] = sharedValue.data;
}
return { valid: true, data: newObj };
} else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) {
return { valid: false };
}
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) {
return { valid: false };
}
newArray.push(sharedValue.data);
}
return { valid: true, data: newArray };
} else if (
aType === ZodParsedType.date &&
bType === ZodParsedType.date &&
+a === +b
) {
return { valid: true, data: a };
} else {
return { valid: false };
}
}
var ZodIntersection = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight) => {
if (isAborted(parsedLeft) || isAborted(parsedRight)) {
return INVALID;
}
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types,
});
return INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) {
status.dirty();
}
return { status: status.value, value: merged.data };
};
if (ctx.common.async) {
return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}),
]).then(([left, right]) => handleParsed(left, right));
} else {
return handleParsed(
this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
}),
this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
})
);
}
}
};
ZodIntersection.create = (left, right, params) => {
return new ZodIntersection({
left,
right,
typeName: ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params),
});
};
var ZodTuple = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType,
});
return INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array",
});
return INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array",
});
status.dirty();
}
const items = [...ctx.data]
.map((item, itemIndex) => {
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(
new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)
);
})
.filter((x) => !!x);
if (ctx.common.async) {
return Promise.all(items).then((results) => {
return ParseStatus.mergeArray(status, results);
});
} else {
return ParseStatus.mergeArray(status, items);
}
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest,
});
}
};
ZodTuple.create = (schemas, params) => {
if (!Array.isArray(schemas)) {
throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
}
return new ZodTuple({
items: schemas,
typeName: ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params),
});
};
var ZodRecord = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType,
});
return INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for (const key in ctx.data) {
pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(
new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)
),
});
}
if (ctx.common.async) {
return ParseStatus.mergeObjectAsync(status, pairs);
} else {
return ParseStatus.mergeObjectSync(status, pairs);
}
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) {
return new ZodRecord({
keyType: first,
valueType: second,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third),
});
}
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second),
});
}
};
var ZodMap = class extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType,
});
return INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [...ctx.data.entries()].map(([key, value], index) => {
return {
key: keyType._parse(
new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])
),
value: valueType._parse(
new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])
),
};
});
if (ctx.common.async) {
const finalMap = /* @__PURE__ */ new Map();
return Promise.resolve().then(async () => {
for (const pair of pairs) {
const key = await pair.key;
const value = await pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
});
} else {
const finalMap = /* @__PURE__ */ new Map();
for (const pair of pairs) {
const key = pair.key;
const value = pair.value;
if (key.status === "aborted" || value.status === "aborted") {
return INVALID;
}
if (key.status === "dirty" || value.status === "dirty") {
status.dirty();
}
finalMap.set(key.value, value.value);
}
return { status: status.value, value: finalMap };
}
}
};
ZodMap.create = (keyType, valueType, params) => {
return new ZodMap({
valueType,
keyType,
typeName: ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params),
});
};
var ZodSet = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType,
});
return INVALID;
}
const def = this._def;
if (def.minSize !== null) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message,
});
status.dirty();
}
}
if (def.maxSize !== null) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message,
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements2) {
const parsedSet = /* @__PURE__ */ new Set();
for (const element of elements2) {
if (element.status === "aborted") return INVALID;
if (element.status === "dirty") status.dirty();
parsedSet.add(element.value);
}
return { status: status.value, value: parsedSet };
}
const elements = [...ctx.data.values()].map((item, i) =>
valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))
);
if (ctx.common.async) {
return Promise.all(elements).then((elements2) => finalizeSet(elements2));
} else {
return finalizeSet(elements);
}
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: { value: minSize, message: errorUtil.toString(message) },
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: { value: maxSize, message: errorUtil.toString(message) },
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
};
ZodSet.create = (valueType, params) => {
return new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params),
});
};
var ZodFunction = class extends ZodType {
constructor() {
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.function) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.function,
received: ctx.parsedType,
});
return INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap,
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error,
},
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
errorMap,
].filter((x) => !!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error,
},
});
}
const params = { errorMap: ctx.common.contextualErrorMap };
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function (...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args
.parseAsync(args, params)
.catch((e) => {
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type
.parseAsync(result, params)
.catch((e) => {
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
} else {
const me = this;
return OK(function (...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) {
throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
}
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) {
throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
}
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create()),
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType,
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params),
});
}
};
var ZodLazy = class extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
}
};
ZodLazy.create = (getter, params) => {
return new ZodLazy({
getter,
typeName: ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params),
});
};
var ZodLiteral = class extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value,
});
return INVALID;
}
return { status: "valid", value: input.data };
}
get value() {
return this._def.value;
}
};
ZodLiteral.create = (value, params) => {
return new ZodLiteral({
value,
typeName: ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params),
});
};
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params),
});
}
var ZodEnum = class extends ZodType {
_parse(input) {
if (typeof input.data !== "string") {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type,
});
return INVALID;
}
if (this._def.values.indexOf(input.data) === -1) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues,
});
return INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values) {
enumValues[val] = val;
}
return enumValues;
}
extract(values) {
return ZodEnum.create(values);
}
exclude(values) {
return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
}
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
_parse(input) {
const nativeEnumValues = util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (
ctx.parsedType !== ZodParsedType.string &&
ctx.parsedType !== ZodParsedType.number
) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type,
});
return INVALID;
}
if (nativeEnumValues.indexOf(input.data) === -1) {
const expectedValues = util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues,
});
return INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
};
ZodNativeEnum.create = (values, params) => {
return new ZodNativeEnum({
values,
typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params),
});
};
var ZodPromise = class extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (
ctx.parsedType !== ZodParsedType.promise &&
ctx.common.async === false
) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType,
});
return INVALID;
}
const promisified =
ctx.parsedType === ZodParsedType.promise
? ctx.data
: Promise.resolve(ctx.data);
return OK(
promisified.then((data) => {
return this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap,
});
})
);
}
};
ZodPromise.create = (schema, params) => {
return new ZodPromise({
type: schema,
typeName: ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params),
});
};
var ZodEffects = class extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
? this._def.schema.sourceType()
: this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg) => {
addIssueToContext(ctx, arg);
if (arg.fatal) {
status.abort();
} else {
status.dirty();
}
},
get path() {
return ctx.path;
},
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if (effect.type === "preprocess") {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.issues.length) {
return {
status: "dirty",
value: ctx.data,
};
}
if (ctx.common.async) {
return Promise.resolve(processed).then((processed2) => {
return this._def.schema._parseAsync({
data: processed2,
path: ctx.path,
parent: ctx,
});
});
} else {
return this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx,
});
}
}
if (effect.type === "refinement") {
const executeRefinement = (acc) => {
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) {
return Promise.resolve(result);
}
if (result instanceof Promise) {
throw new Error(
"Async refinement encountered during synchronous parse operation. Use .parseAsync instead."
);
}
return acc;
};
if (ctx.common.async === false) {
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
executeRefinement(inner.value);
return { status: status.value, value: inner.value };
} else {
return this._def.schema
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
.then((inner) => {
if (inner.status === "aborted") return INVALID;
if (inner.status === "dirty") status.dirty();
return executeRefinement(inner.value).then(() => {
return { status: status.value, value: inner.value };
});
});
}
}
if (effect.type === "transform") {
if (ctx.common.async === false) {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (!isValid(base)) return base;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) {
throw new Error(
`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`
);
}
return { status: status.value, value: result };
} else {
return this._def.schema
._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
.then((base) => {
if (!isValid(base)) return base;
return Promise.resolve(effect.transform(base.value, checkCtx)).then(
(result) => ({ status: status.value, value: result })
);
});
}
}
util.assertNever(effect);
}
};
ZodEffects.create = (schema, effect, params) => {
return new ZodEffects({
schema,
typeName: ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params),
});
};
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
return new ZodEffects({
schema,
effect: { type: "preprocess", transform: preprocess },
typeName: ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params),
});
};
var ZodOptional = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) {
return OK(void 0);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodOptional.create = (type, params) => {
return new ZodOptional({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params),
});
};
var ZodNullable = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.null) {
return OK(null);
}
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
};
ZodNullable.create = (type, params) => {
return new ZodNullable({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params),
});
};
var ZodDefault = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) {
data = this._def.defaultValue();
}
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx,
});
}
removeDefault() {
return this._def.innerType;
}
};
ZodDefault.create = (type, params) => {
return new ZodDefault({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodDefault,
defaultValue:
typeof params.default === "function"
? params.default
: () => params.default,
...processCreateParams(params),
});
};
var ZodCatch = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: [],
},
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx,
},
});
if (isAsync(result)) {
return result.then((result2) => {
return {
status: "valid",
value:
result2.status === "valid"
? result2.value
: this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data,
}),
};
});
} else {
return {
status: "valid",
value:
result.status === "valid"
? result.value
: this._def.catchValue({
get error() {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data,
}),
};
}
}
removeCatch() {
return this._def.innerType;
}
};
ZodCatch.create = (type, params) => {
return new ZodCatch({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodCatch,
catchValue:
typeof params.catch === "function" ? params.catch : () => params.catch,
...processCreateParams(params),
});
};
var ZodNaN = class extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType,
});
return INVALID;
}
return { status: "valid", value: input.data };
}
};
ZodNaN.create = (params) => {
return new ZodNaN({
typeName: ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params),
});
};
var BRAND = Symbol("zod_brand");
var ZodBranded = class extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx,
});
}
unwrap() {
return this._def.type;
}
};
var ZodPipeline = class extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async () => {
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return DIRTY(inResult.value);
} else {
return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx,
});
}
};
return handleAsync();
} else {
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx,
});
if (inResult.status === "aborted") return INVALID;
if (inResult.status === "dirty") {
status.dirty();
return {
status: "dirty",
value: inResult.value,
};
} else {
return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx,
});
}
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: ZodFirstPartyTypeKind.ZodPipeline,
});
}
};
var ZodReadonly = class extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
if (isValid(result)) {
result.value = Object.freeze(result.value);
}
return result;
}
};
ZodReadonly.create = (type, params) => {
return new ZodReadonly({
innerType: type,
typeName: ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params),
});
};
var custom = (check, params = {}, fatal) => {
if (check)
return ZodAny.create().superRefine((data, ctx) => {
var _a108, _b;
if (!check(data)) {
const p2 =
typeof params === "function"
? params(data)
: typeof params === "string"
? { message: params }
: params;
const _fatal =
(_b =
(_a108 = p2.fatal) !== null && _a108 !== void 0 ? _a108 : fatal) !==
null && _b !== void 0
? _b
: true;
const p22 = typeof p2 === "string" ? { message: p2 } : p2;
ctx.addIssue({ code: "custom", ...p22, fatal: _fatal });
}
});
return ZodAny.create();
};
var late = {
object: ZodObject.lazycreate,
};
var ZodFirstPartyTypeKind;
(function (ZodFirstPartyTypeKind2) {
ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var instanceOfType = (
cls,
params = {
message: `Input not instance of ${cls.name}`,
}
) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var coerce = {
string: (arg) => ZodString.create({ ...arg, coerce: true }),
number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
boolean: (arg) =>
ZodBoolean.create({
...arg,
coerce: true,
}),
bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
date: (arg) => ZodDate.create({ ...arg, coerce: true }),
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
__proto__: null,
defaultErrorMap: errorMap,
setErrorMap,
getErrorMap,
makeIssue,
EMPTY_PATH,
addIssueToContext,
ParseStatus,
INVALID,
DIRTY,
OK,
isAborted,
isDirty,
isValid,
isAsync,
get util() {
return util;
},
get objectUtil() {
return objectUtil;
},
ZodParsedType,
getParsedType,
ZodType,
ZodString,
ZodNumber,
ZodBigInt,
ZodBoolean,
ZodDate,
ZodSymbol,
ZodUndefined,
ZodNull,
ZodAny,
ZodUnknown,
ZodNever,
ZodVoid,
ZodArray,
ZodObject,
ZodUnion,
ZodDiscriminatedUnion,
ZodIntersection,
ZodTuple,
ZodRecord,
ZodMap,
ZodSet,
ZodFunction,
ZodLazy,
ZodLiteral,
ZodEnum,
ZodNativeEnum,
ZodPromise,
ZodEffects,
ZodTransformer: ZodEffects,
ZodOptional,
ZodNullable,
ZodDefault,
ZodCatch,
ZodNaN,
BRAND,
ZodBranded,
ZodPipeline,
ZodReadonly,
custom,
Schema: ZodType,
ZodSchema: ZodType,
late,
get ZodFirstPartyTypeKind() {
return ZodFirstPartyTypeKind;
},
coerce,
any: anyType,
array: arrayType,
bigint: bigIntType,
boolean: booleanType,
date: dateType,
discriminatedUnion: discriminatedUnionType,
effect: effectsType,
enum: enumType,
function: functionType,
instanceof: instanceOfType,
intersection: intersectionType,
lazy: lazyType,
literal: literalType,
map: mapType,
nan: nanType,
nativeEnum: nativeEnumType,
never: neverType,
null: nullType,
nullable: nullableType,
number: numberType,
object: objectType,
oboolean,
onumber,
optional: optionalType,
ostring,
pipeline: pipelineType,
preprocess: preprocessType,
promise: promiseType,
record: recordType,
set: setType,
strictObject: strictObjectType,
string: stringType,
symbol: symbolType,
transformer: effectsType,
tuple: tupleType,
undefined: undefinedType,
union: unionType,
unknown: unknownType,
void: voidType,
NEVER,
ZodIssueCode,
quotelessJson,
ZodError,
});
// ../../node_modules/.pnpm/drizzle-zod@0.5.1_drizzle-orm@0.29.3_zod@3.22.4/node_modules/drizzle-zod/index.mjs
var m = z.union([z.string(), z.number(), z.boolean(), z.null()]);
var f = z.lazy(() => z.union([m, z.array(f), z.record(f)]));
function c(t, n) {
const r = getTableColumns(t),
o = Object.entries(r);
let i = Object.fromEntries(o.map(([e, t2]) => [e, p(t2)]));
n &&
(i = Object.assign(
i,
Object.fromEntries(
Object.entries(n).map(([e, t2]) => [
e,
"function" == typeof t2 ? t2(i) : t2,
])
)
));
for (const [e, t2] of o)
t2.notNull
? t2.hasDefault && (i[e] = i[e].optional())
: (i[e] = i[e].nullable().optional());
return z.object(i);
}
function p(e) {
let m2;
if (
((function (e2) {
return (
"enumValues" in e2 &&
Array.isArray(e2.enumValues) &&
e2.enumValues.length > 0
);
})(e) && (m2 = e.enumValues.length ? z.enum(e.enumValues) : z.string()),
!m2)
) {
if (is(e, PgUUID)) m2 = z.string().uuid();
else if ("custom" === e.dataType) m2 = z.any();
else if ("json" === e.dataType) m2 = f;
else if ("array" === e.dataType) m2 = z.array(p(e.baseColumn));
else if ("number" === e.dataType) m2 = z.number();
else if ("bigint" === e.dataType) m2 = z.bigint();
else if ("boolean" === e.dataType) m2 = z.boolean();
else if ("date" === e.dataType) m2 = z.date();
else if ("string" === e.dataType) {
let i = z.string();
(is(e, PgChar) ||
is(e, PgVarchar) ||
is(e, MySqlVarChar) ||
is(e, MySqlVarBinary) ||
is(e, MySqlChar) ||
is(e, SQLiteText)) &&
"number" == typeof e.length &&
(i = i.max(e.length)),
(m2 = i);
}
}
return m2 || (m2 = z.any()), m2;
}
// ../../packages/database/schema.ts
var emails = sqliteTable("emails", {
id: text("id").primaryKey(),
messageFrom: text("message_from").notNull(),
messageTo: text("message_to").notNull(),
headers: text("headers", { mode: "json" }).$type().notNull(),
from: text("from", { mode: "json" }).$type().notNull(),
sender: text("sender", { mode: "json" }).$type(),
replyTo: text("reply_to", { mode: "json" }).$type(),
deliveredTo: text("delivered_to"),
returnPath: text("return_path"),
to: text("to", { mode: "json" }).$type(),
cc: text("cc", { mode: "json" }).$type(),
bcc: text("bcc", { mode: "json" }).$type(),
subject: text("subject"),
messageId: text("message_id").notNull(),
inReplyTo: text("in_reply_to"),
references: text("references"),
date: text("date"),
html: text("html"),
text: text("text"),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
});
var AddressSchema = objectType({
address: stringType(),
name: stringType(),
});
var insertEmailSchema = c(emails, {
headers: arrayType(recordType(stringType())),
from: AddressSchema,
sender: AddressSchema.optional(),
replyTo: arrayType(AddressSchema).optional(),
to: arrayType(AddressSchema).optional(),
cc: arrayType(AddressSchema).optional(),
bcc: arrayType(AddressSchema).optional(),
});
// ../../packages/database/dao.ts
async function insertEmail(db, email) {
try {
await db.insert(emails).values(email).execute();
} catch (e) {
console.error(e);
}
}
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/api.js
var LibsqlError = class extends Error {
/** Machine-readable error code. */
code;
/** Raw numeric error code */
rawCode;
constructor(message, code, rawCode, cause) {
if (code !== void 0) {
message = `${code}: ${message}`;
}
super(message, { cause });
this.code = code;
this.rawCode = rawCode;
this.name = "LibsqlError";
}
};
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/uri.js
function parseUri(text2) {
const match = URI_RE.exec(text2);
if (match === null) {
throw new LibsqlError("The URL is not in a valid format", "URL_INVALID");
}
const groups = match.groups;
const scheme = groups["scheme"];
const authority =
groups["authority"] !== void 0
? parseAuthority(groups["authority"])
: void 0;
const path = percentDecode(groups["path"]);
const query =
groups["query"] !== void 0 ? parseQuery(groups["query"]) : void 0;
const fragment =
groups["fragment"] !== void 0 ? percentDecode(groups["fragment"]) : void 0;
return { scheme, authority, path, query, fragment };
}
var 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(text2) {
const match = AUTHORITY_RE.exec(text2);
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) : void 0;
const userinfo =
groups["username"] !== void 0
? {
username: percentDecode(groups["username"]),
password:
groups["password"] !== void 0
? percentDecode(groups["password"])
: void 0,
}
: void 0;
return { host, port, userinfo };
}
var AUTHORITY_RE = (() => {
const USERINFO = "(?<username>[^:]*)(:(?<password>.*))?";
const HOST = "((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))";
const PORT = "(?<port>[0-9]*)";
return new RegExp(`^(${USERINFO}@)?${HOST}(:${PORT})?$`, "su");
})();
function parseQuery(text2) {
const sequences = text2.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(text2) {
try {
return decodeURIComponent(text2);
} catch (e) {
if (e instanceof URIError) {
throw new LibsqlError(
`URL component has invalid percent encoding: ${e}`,
"URL_INVALID",
void 0,
e
);
}
throw e;
}
}
function encodeBaseUrl(scheme, authority, path) {
if (authority === void 0) {
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 !== void 0 ? `:${port}` : "";
}
function encodeUserinfo(userinfo) {
if (userinfo === void 0) {
return "";
}
const usernameText = encodeURIComponent(userinfo.username);
const passwordText =
userinfo.password !== void 0
? `:${encodeURIComponent(userinfo.password)}`
: "";
return `${usernameText}${passwordText}@`;
}
// ../../node_modules/.pnpm/js-base64@3.7.5/node_modules/js-base64/base64.mjs
var version2 = "3.7.5";
var VERSION = version2;
var _hasatob = typeof atob === "function";
var _hasbtoa = typeof btoa === "function";
var _hasBuffer = typeof Buffer === "function";
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var b64chs = Array.prototype.slice.call(b64ch);
var b64tab = ((a) => {
let tab = {};
a.forEach((c2, i) => (tab[c2] = i));
return tab;
})(b64chs);
var b64re =
/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
var _fromCC = String.fromCharCode.bind(String);
var _U8Afrom =
typeof Uint8Array.from === "function"
? Uint8Array.from.bind(Uint8Array)
: (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
var _mkUriSafe = (src) =>
src.replace(/=/g, "").replace(/[+\/]/g, (m0) => (m0 == "+" ? "-" : "_"));
var _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, "");
var btoaPolyfill = (bin) => {
let u32,
c0,
c1,
c2,
asc2 = "";
const pad = bin.length % 3;
for (let i = 0; i < bin.length; ) {
if (
(c0 = bin.charCodeAt(i++)) > 255 ||
(c1 = bin.charCodeAt(i++)) > 255 ||
(c2 = bin.charCodeAt(i++)) > 255
)
throw new TypeError("invalid character found");
u32 = (c0 << 16) | (c1 << 8) | c2;
asc2 +=
b64chs[(u32 >> 18) & 63] +
b64chs[(u32 >> 12) & 63] +
b64chs[(u32 >> 6) & 63] +
b64chs[u32 & 63];
}
return pad ? asc2.slice(0, pad - 3) + "===".substring(pad) : asc2;
};
var _btoa = _hasbtoa
? (bin) => btoa(bin)
: _hasBuffer
? (bin) => Buffer.from(bin, "binary").toString("base64")
: btoaPolyfill;
var _fromUint8Array = _hasBuffer
? (u8a) => Buffer.from(u8a).toString("base64")
: (u8a) => {
const maxargs = 4096;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(""));
};
var fromUint8Array = (u8a, urlsafe = false) =>
urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
var cb_utob = (c2) => {
if (c2.length < 2) {
var cc = c2.charCodeAt(0);
return cc < 128
? c2
: cc < 2048
? _fromCC(192 | (cc >>> 6)) + _fromCC(128 | (cc & 63))
: _fromCC(224 | ((cc >>> 12) & 15)) +
_fromCC(128 | ((cc >>> 6) & 63)) +
_fromCC(128 | (cc & 63));
} else {
var cc =
65536 + (c2.charCodeAt(0) - 55296) * 1024 + (c2.charCodeAt(1) - 56320);
return (
_fromCC(240 | ((cc >>> 18) & 7)) +
_fromCC(128 | ((cc >>> 12) & 63)) +
_fromCC(128 | ((cc >>> 6) & 63)) +
_fromCC(128 | (cc & 63))
);
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = (u) => u.replace(re_utob, cb_utob);
var _encode = _hasBuffer
? (s) => Buffer.from(s, "utf8").toString("base64")
: _TE
? (s) => _fromUint8Array(_TE.encode(s))
: (s) => _btoa(utob(s));
var encode = (src, urlsafe = false) =>
urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
var encodeURI2 = (src) => encode(src, true);
var re_btou =
/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var cb_btou = (cccc) => {
switch (cccc.length) {
case 4:
var cp =
((7 & cccc.charCodeAt(0)) << 18) |
((63 & cccc.charCodeAt(1)) << 12) |
((63 & cccc.charCodeAt(2)) << 6) |
(63 & cccc.charCodeAt(3)),
offset = cp - 65536;
return (
_fromCC((offset >>> 10) + 55296) + _fromCC((offset & 1023) + 56320)
);
case 3:
return _fromCC(
((15 & cccc.charCodeAt(0)) << 12) |
((63 & cccc.charCodeAt(1)) << 6) |
(63 & cccc.charCodeAt(2))
);
default:
return _fromCC(
((31 & cccc.charCodeAt(0)) << 6) | (63 & cccc.charCodeAt(1))
);
}
};
var btou = (b) => b.replace(re_btou, cb_btou);
var atobPolyfill = (asc2) => {
asc2 = asc2.replace(/\s+/g, "");
if (!b64re.test(asc2)) throw new TypeError("malformed base64.");
asc2 += "==".slice(2 - (asc2.length & 3));
let u24,
bin = "",
r1,
r2;
for (let i = 0; i < asc2.length; ) {
u24 =
(b64tab[asc2.charAt(i++)] << 18) |
(b64tab[asc2.charAt(i++)] << 12) |
((r1 = b64tab[asc2.charAt(i++)]) << 6) |
(r2 = b64tab[asc2.charAt(i++)]);
bin +=
r1 === 64
? _fromCC((u24 >> 16) & 255)
: r2 === 64
? _fromCC((u24 >> 16) & 255, (u24 >> 8) & 255)
: _fromCC((u24 >> 16) & 255, (u24 >> 8) & 255, u24 & 255);
}
return bin;
};
var _atob = _hasatob
? (asc2) => atob(_tidyB64(asc2))
: _hasBuffer
? (asc2) => Buffer.from(asc2, "base64").toString("binary")
: atobPolyfill;
var _toUint8Array = _hasBuffer
? (a) => _U8Afrom(Buffer.from(a, "base64"))
: (a) =>
_U8Afrom(
_atob(a)
.split("")
.map((c2) => c2.charCodeAt(0))
);
var toUint8Array = (a) => _toUint8Array(_unURI(a));
var _decode = _hasBuffer
? (a) => Buffer.from(a, "base64").toString("utf8")
: _TD
? (a) => _TD.decode(_toUint8Array(a))
: (a) => btou(_atob(a));
var _unURI = (a) =>
_tidyB64(a.replace(/[-_]/g, (m0) => (m0 == "-" ? "+" : "/")));
var decode = (src) => _decode(_unURI(src));
var isValid2 = (src) => {
if (typeof src !== "string") return false;
const s = src.replace(/\s+/g, "").replace(/={0,2}$/, "");
return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s);
};
var _noEnum = (v) => {
return {
value: v,
enumerable: false,
writable: true,
configurable: true,
};
};
var extendString = function () {
const _add = (name, body) =>
Object.defineProperty(String.prototype, name, _noEnum(body));
_add("fromBase64", function () {
return decode(this);
});
_add("toBase64", function (urlsafe) {
return encode(this, urlsafe);
});
_add("toBase64URI", function () {
return encode(this, true);
});
_add("toBase64URL", function () {
return encode(this, true);
});
_add("toUint8Array", function () {
return toUint8Array(this);
});
};
var extendUint8Array = function () {
const _add = (name, body) =>
Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
_add("toBase64", function (urlsafe) {
return fromUint8Array(this, urlsafe);
});
_add("toBase64URI", function () {
return fromUint8Array(this, true);
});
_add("toBase64URL", function () {
return fromUint8Array(this, true);
});
};
var extendBuiltins = () => {
extendString();
extendUint8Array();
};
var gBase64 = {
version: version2,
VERSION,
atob: _atob,
atobPolyfill,
btoa: _btoa,
btoaPolyfill,
fromBase64: decode,
toBase64: encode,
encode,
encodeURI: encodeURI2,
encodeURL: encodeURI2,
utob,
btou,
decode,
isValid: isValid2,
fromUint8Array,
toUint8Array,
extendString,
extendUint8Array,
extendBuiltins,
};
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/util.js
var 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"'
);
}
}
var ResultSetImpl = class {
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 !== void 0 ? "" + 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 gBase64.fromUint8Array(new Uint8Array(value));
} else {
return value;
}
}
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/config.js
function expandConfig(config, preferHttp) {
if (typeof config !== "object") {
throw new TypeError(
`Expected client configuration as object, got ${typeof config}`
);
}
let tls = config.tls;
let authToken = config.authToken;
let syncUrl = config.syncUrl;
const intMode = "" + (config.intMode ?? "number");
if (intMode !== "number" && intMode !== "bigint" && intMode !== "string") {
throw new TypeError(
`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(intMode)}`
);
}
if (config.url === ":memory:") {
return {
path: ":memory:",
scheme: "file",
syncUrl,
intMode,
fetch: config.fetch,
tls: false,
authToken: void 0,
authority: void 0,
};
}
const uri = parseUri(config.url);
for (const { key, value } of uri.query?.pairs ?? []) {
if (key === "authToken") {
authToken = value ? value : void 0;
} else if (key === "tls") {
if (value === "0") {
tls = false;
} else if (value === "1") {
tls = true;
} else {
throw new LibsqlError(
`Unknown value for the "tls" query argument: ${JSON.stringify(value)}. Supported values are "0" and "1"`,
"URL_INVALID"
);
}
} else {
throw new LibsqlError(
`Unknown URL query parameter ${JSON.stringify(key)}`,
"URL_PARAM_NOT_SUPPORTED"
);
}
}
const uriScheme = uri.scheme.toLowerCase();
let scheme;
if (uriScheme === "libsql") {
if (tls === false) {
if (uri.authority?.port === void 0) {
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 if (uriScheme === "http" || uriScheme === "ws") {
scheme = uriScheme;
tls ??= false;
} else if (
uriScheme === "https" ||
uriScheme === "wss" ||
uriScheme === "file"
) {
scheme = uriScheme;
} else {
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 (uri.fragment !== void 0) {
throw new LibsqlError(
`URL fragments are not supported: ${JSON.stringify("#" + uri.fragment)}`,
"URL_INVALID"
);
}
return {
scheme,
tls: tls ?? true,
authority: uri.authority,
path: uri.path,
authToken,
syncUrl,
intMode,
fetch: config.fetch,
};
}
// ../../node_modules/.pnpm/@libsql+isomorphic-ws@0.1.5/node_modules/@libsql/isomorphic-ws/web.mjs
var _WebSocket;
if (typeof WebSocket !== "undefined") {
_WebSocket = WebSocket;
} else if (typeof global !== "undefined") {
_WebSocket = global.WebSocket;
} else if (typeof window !== "undefined") {
_WebSocket = window.WebSocket;
} else if (typeof self !== "undefined") {
_WebSocket = self.WebSocket;
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/client.js
var Client = class {
/** @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;
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/errors.js
var ClientError = class extends Error {
/** @private */
constructor(message) {
super(message);
this.name = "ClientError";
}
};
var ProtoError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "ProtoError";
}
};
var ResponseError = class extends ClientError {
code;
/** @internal */
proto;
/** @private */
constructor(message, protoError) {
super(message);
this.name = "ResponseError";
this.code = protoError.code;
this.proto = protoError;
this.stack = void 0;
}
};
var ClosedError = class extends ClientError {
/** @private */
constructor(message, cause) {
if (cause !== void 0) {
super(`${message}: ${cause}`);
this.cause = cause;
} else {
super(message);
}
this.name = "ClosedError";
}
};
var WebSocketUnsupportedError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "WebSocketUnsupportedError";
}
};
var WebSocketError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "WebSocketError";
}
};
var HttpServerError = class extends ClientError {
status;
/** @private */
constructor(message, status) {
super(message);
this.status = status;
this.name = "HttpServerError";
}
};
var ProtocolVersionError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "ProtocolVersionError";
}
};
var InternalError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "InternalError";
}
};
var MisuseError = class extends ClientError {
/** @private */
constructor(message) {
super(message);
this.name = "MisuseError";
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/encoding/json/decode.js
function string(value) {
if (typeof value === "string") {
return value;
}
throw typeError(value, "string");
}
function stringOpt(value) {
if (value === null || value === void 0) {
return void 0;
} else if (typeof value === "string") {
return value;
}
throw typeError(value, "string or null");
}
function number(value) {
if (typeof value === "number") {
return value;
}
throw typeError(value, "number");
}
function boolean(value) {
if (typeof value === "boolean") {
return value;
}
throw typeError(value, "boolean");
}
function array(value) {
if (Array.isArray(value)) {
return value;
}
throw typeError(value, "array");
}
function object(value) {
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
return value;
}
throw typeError(value, "object");
}
function arrayObjectsMap(value, fun) {
return array(value).map((elemValue) => fun(object(elemValue)));
}
function typeError(value, expected) {
if (value === void 0) {
return new 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 ProtoError(`Expected ${expected}, received ${received}`);
}
function readJsonObject(value, fun) {
return fun(object(value));
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/encoding/json/encode.js
var ObjectWriter = class {
#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("]");
}
};
function writeJsonObject(value, fun) {
const output = [];
const writer = new ObjectWriter(output);
writer.begin();
fun(writer, value);
writer.end();
return output.join("");
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/util.js
var VARINT = 0;
var FIXED_64 = 1;
var LENGTH_DELIMITED = 2;
var FIXED_32 = 5;
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/decode.js
var MessageReader = class {
#array;
#view;
#pos;
constructor(array2) {
this.#array = array2;
this.#view = new DataView(
array2.buffer,
array2.byteOffset,
array2.byteLength
);
this.#pos = 0;
}
varint() {
let value = 0;
for (let shift = 0; ; shift += 7) {
const byte = this.#array[this.#pos++];
value |= (byte & 127) << shift;
if (!(byte & 128)) {
break;
}
}
return value;
}
varintBig() {
let value = 0n;
for (let shift = 0n; ; shift += 7n) {
const byte = this.#array[this.#pos++];
value |= BigInt(byte & 127) << shift;
if (!(byte & 128)) {
break;
}
}
return value;
}
bytes(length) {
const array2 = new Uint8Array(
this.#array.buffer,
this.#array.byteOffset + this.#pos,
length
);
this.#pos += length;
return array2;
}
double() {
const value = this.#view.getFloat64(this.#pos, true);
this.#pos += 8;
return value;
}
skipVarint() {
for (;;) {
const byte = this.#array[this.#pos++];
if (!(byte & 128)) {
break;
}
}
}
skip(count) {
this.#pos += count;
}
eof() {
return this.#pos >= this.#array.byteLength;
}
};
var FieldReader = class {
#reader;
#wireType;
constructor(reader) {
this.#reader = reader;
this.#wireType = -1;
}
setup(wireType) {
this.#wireType = wireType;
}
#expect(expectedWireType) {
if (this.#wireType !== expectedWireType) {
throw new ProtoError(
`Expected wire type ${expectedWireType}, got ${this.#wireType}`
);
}
this.#wireType = -1;
}
bytes() {
this.#expect(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(VARINT);
return this.#reader.varint();
}
uint32() {
return this.int32();
}
bool() {
return this.int32() !== 0;
}
uint64() {
this.#expect(VARINT);
return this.#reader.varintBig();
}
sint64() {
const value = this.uint64();
return (value >> 1n) ^ -(value & 1n);
}
double() {
this.#expect(FIXED_64);
return this.#reader.double();
}
maybeSkip() {
if (this.#wireType < 0) {
return;
} else if (this.#wireType === VARINT) {
this.#reader.skipVarint();
} else if (this.#wireType === FIXED_64) {
this.#reader.skip(8);
} else if (this.#wireType === LENGTH_DELIMITED) {
const length = this.#reader.varint();
this.#reader.skip(length);
} else if (this.#wireType === FIXED_32) {
this.#reader.skip(4);
} else {
throw new ProtoError(`Unexpected wire type ${this.#wireType}`);
}
this.#wireType = -1;
}
};
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 & 7;
fieldReader.setup(wireType);
const tagFun = def[tag];
if (tagFun !== void 0) {
const returnedValue = tagFun(fieldReader, value);
if (returnedValue !== void 0) {
value = returnedValue;
}
}
fieldReader.maybeSkip();
}
return value;
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/encoding/protobuf/encode.js
var MessageWriter = class {
#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 & 127;
value >>>= 7;
byte |= value ? 128 : 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 ? 128 : 0;
this.#array[this.#pos++] = byte;
} while (value);
}
#tag(tag, wireType) {
this.#varint((tag << 3) | wireType);
}
bytes(tag, value) {
this.#tag(tag, 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, 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, VARINT);
this.#varintBig((value << 1n) ^ (value >> 63n));
}
double(tag, value) {
this.#tag(tag, FIXED_64);
this.#ensure(8);
this.#view.setFloat64(this.#pos, value, true);
this.#pos += 8;
}
data() {
return new Uint8Array(this.#buf, 0, this.#pos);
}
};
function writeProtobufMessage(value, fun) {
const w = new MessageWriter();
fun(w, value);
return w.data();
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/id_alloc.js
var IdAlloc = class {
// Set of all allocated ids
#usedIds;
// Set of all free ids lower than `#usedIds.size`
#freeIds;
constructor() {
this.#usedIds = /* @__PURE__ */ new Set();
this.#freeIds = /* @__PURE__ */ new Set();
}
// Returns an id that was free, and marks it as used.
alloc() {
for (const freeId2 of this.#freeIds) {
this.#freeIds.delete(freeId2);
this.#usedIds.add(freeId2);
if (!this.#usedIds.has(this.#usedIds.size - 1)) {
this.#freeIds.add(this.#usedIds.size - 1);
}
return freeId2;
}
const freeId = this.#usedIds.size;
this.#usedIds.add(freeId);
return freeId;
}
free(id) {
if (!this.#usedIds.delete(id)) {
throw new InternalError("Freeing an id that is not allocated");
}
this.#freeIds.delete(this.#usedIds.size);
if (id < this.#usedIds.size) {
this.#freeIds.add(id);
}
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/util.js
function impossible(value, message) {
throw new InternalError(message);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/value.js
function valueToProto(value) {
if (value === null) {
return null;
} else if (typeof value === "string") {
return value;
} else 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(
"This bigint value is too large to be represented as a 64-bit integer and passed as argument"
);
}
return value;
} else if (typeof value === "boolean") {
return value ? 1n : 0n;
} else if (value instanceof ArrayBuffer) {
return new Uint8Array(value);
} else if (value instanceof Uint8Array) {
return value;
} else if (value instanceof Date) {
return +value.valueOf();
} else if (typeof value === "object") {
return "" + value.toString();
} else {
throw new TypeError("Unsupported type of value");
}
}
var minInteger = -9223372036854775808n;
var maxInteger = 9223372036854775807n;
function valueFromProto(value, intMode) {
if (value === null) {
return null;
} else if (typeof value === "number") {
return value;
} else if (typeof value === "string") {
return value;
} else if (typeof value === "bigint") {
if (intMode === "number") {
const num = Number(value);
if (!Number.isSafeInteger(num)) {
throw new RangeError(
"Received integer which is too large to be safely represented as a JavaScript number"
);
}
return num;
} else if (intMode === "bigint") {
return value;
} else if (intMode === "string") {
return "" + value;
} else {
throw new MisuseError("Invalid value for IntMode");
}
} else if (value instanceof Uint8Array) {
return value.slice().buffer;
} else if (value === void 0) {
throw new ProtoError("Received unrecognized type of Value");
} else {
throw impossible(value, "Impossible type of Value");
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/result.js
function stmtResultFromProto(result) {
return {
affectedRowCount: result.affectedRowCount,
lastInsertRowid: result.lastInsertRowid,
columnNames: result.cols.map((col) => col.name),
columnDecltypes: result.cols.map((col) => col.decltype),
};
}
function rowsResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
const rows = result.rows.map((row) =>
rowFromProto(stmtResult.columnNames, row, intMode)
);
return { ...stmtResult, rows };
}
function rowResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
let row;
if (result.rows.length > 0) {
row = rowFromProto(stmtResult.columnNames, result.rows[0], intMode);
}
return { ...stmtResult, row };
}
function valueResultFromProto(result, intMode) {
const stmtResult = stmtResultFromProto(result);
let value;
if (result.rows.length > 0 && stmtResult.columnNames.length > 0) {
value = valueFromProto(result.rows[0][0], intMode);
}
return { ...stmtResult, value };
}
function rowFromProto(colNames, values, intMode) {
const row = {};
Object.defineProperty(row, "length", { value: values.length });
for (let i = 0; i < values.length; ++i) {
const value = valueFromProto(values[i], intMode);
Object.defineProperty(row, i, { value });
const colName = colNames[i];
if (colName !== void 0 && !Object.hasOwn(row, colName)) {
Object.defineProperty(row, colName, { value, enumerable: true });
}
}
return row;
}
function errorFromProto(error) {
return new ResponseError(error.message, error);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/sql.js
var Sql = class {
#owner;
#sqlId;
#closed;
/** @private */
constructor(owner, sqlId) {
this.#owner = owner;
this.#sqlId = sqlId;
this.#closed = void 0;
}
/** @private */
_getSqlId(owner) {
if (this.#owner !== owner) {
throw new MisuseError(
"Attempted to use SQL text opened with other object"
);
} else if (this.#closed !== void 0) {
throw new ClosedError("SQL text is closed", this.#closed);
}
return this.#sqlId;
}
/** Remove the SQL text from the server, releasing resouces. */
close() {
this._setClosed(new ClientError("SQL text was manually closed"));
}
/** @private */
_setClosed(error) {
if (this.#closed === void 0) {
this.#closed = error;
this.#owner._closeSql(this.#sqlId);
}
}
/** True if the SQL text is closed (removed from the server). */
get closed() {
return this.#closed !== void 0;
}
};
function sqlToProto(owner, sql2) {
if (sql2 instanceof Sql) {
return { sqlId: sql2._getSqlId(owner) };
} else {
return { sql: "" + sql2 };
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/queue.js
var Queue = class {
#pushStack;
#shiftStack;
constructor() {
this.#pushStack = [];
this.#shiftStack = [];
}
get length() {
return this.#pushStack.length + this.#shiftStack.length;
}
push(elem) {
this.#pushStack.push(elem);
}
shift() {
if (this.#shiftStack.length === 0 && this.#pushStack.length > 0) {
this.#shiftStack = this.#pushStack.reverse();
this.#pushStack = [];
}
return this.#shiftStack.pop();
}
first() {
return this.#shiftStack.length !== 0
? this.#shiftStack[this.#shiftStack.length - 1]
: this.#pushStack[0];
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/stmt.js
var Stmt = class {
/** The SQL statement text. */
sql;
/** @private */
_args;
/** @private */
_namedArgs;
/** Initialize the statement with given SQL text. */
constructor(sql2) {
this.sql = sql2;
this._args = [];
this._namedArgs = /* @__PURE__ */ new Map();
}
/** Binds positional parameters from the given `values`. All previous positional bindings are cleared. */
bindIndexes(values) {
this._args.length = 0;
for (const value of values) {
this._args.push(valueToProto(value));
}
return this;
}
/** Binds a parameter by a 1-based index. */
bindIndex(index, value) {
if (index !== (index | 0) || index <= 0) {
throw new RangeError(
"Index of a positional argument must be positive integer"
);
}
while (this._args.length < index) {
this._args.push(null);
}
this._args[index - 1] = valueToProto(value);
return this;
}
/** Binds a parameter by name. */
bindName(name, value) {
this._namedArgs.set(name, valueToProto(value));
return this;
}
/** Clears all bindings. */
unbindAll() {
this._args.length = 0;
this._namedArgs.clear();
return this;
}
};
function stmtToProto(sqlOwner, stmt, wantRows) {
let inSql;
let args = [];
let namedArgs = [];
if (stmt instanceof Stmt) {
inSql = stmt.sql;
args = stmt._args;
for (const [name, value] of stmt._namedArgs.entries()) {
namedArgs.push({ name, value });
}
} else if (Array.isArray(stmt)) {
inSql = stmt[0];
if (Array.isArray(stmt[1])) {
args = stmt[1].map((arg) => valueToProto(arg));
} else {
namedArgs = Object.entries(stmt[1]).map(([name, value]) => {
return { name, value: valueToProto(value) };
});
}
} else {
inSql = stmt;
}
const { sql: sql2, sqlId } = sqlToProto(sqlOwner, inSql);
return { sql: sql2, sqlId, args, namedArgs, wantRows };
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/batch.js
var Batch = class {
/** @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 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);
}
}
};
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 = void 0;
let rows = [];
for (;;) {
const entry = await cursor.next();
if (entry === void 0) {
break;
}
if (entry.type === "step_begin") {
if (entry.step < nextStep || entry.step >= steps.length) {
throw new ProtoError(
"Server produced StepBeginEntry for unexpected step"
);
} else if (beginEntry !== void 0) {
throw new ProtoError(
"Server produced StepBeginEntry before terminating previous step"
);
}
for (let step = nextStep; step < entry.step; ++step) {
steps[step].callback(void 0, void 0);
}
nextStep = entry.step + 1;
beginEntry = entry;
rows = [];
} else if (entry.type === "step_end") {
if (beginEntry === void 0) {
throw new 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, void 0);
beginEntry = void 0;
rows = [];
} else if (entry.type === "step_error") {
if (beginEntry === void 0) {
if (entry.step >= steps.length) {
throw new ProtoError(
"Server produced StepErrorEntry for unexpected step"
);
}
for (let step = nextStep; step < entry.step; ++step) {
steps[step].callback(void 0, void 0);
}
} else {
if (entry.step !== beginEntry.step) {
throw new ProtoError(
"Server produced StepErrorEntry for unexpected step"
);
}
beginEntry = void 0;
rows = [];
}
steps[entry.step].callback(void 0, entry.error);
nextStep = entry.step + 1;
} else if (entry.type === "row") {
if (beginEntry === void 0) {
throw new ProtoError(
"Server produced RowEntry but no step is active"
);
}
rows.push(entry.row);
} else if (entry.type === "error") {
throw errorFromProto(entry.error);
} else if (entry.type === "none") {
throw new ProtoError("Server produced unrecognized CursorEntry");
} else {
throw impossible(entry, "Impossible CursorEntry");
}
}
if (beginEntry !== void 0) {
throw new ProtoError(
"Server closed Cursor before terminating active step"
);
}
for (let step = nextStep; step < steps.length; ++step) {
steps[step].callback(void 0, void 0);
}
} finally {
cursor.close();
}
}
var BatchStep = class {
/** @private */
_batch;
#conds;
/** @private */
_index;
/** @private */
constructor(batch) {
this._batch = batch;
this.#conds = [];
this._index = void 0;
}
/** 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, rowsResultFromProto);
}
/** Add a statement that returns at most a single row. */
queryRow(stmt) {
return this.#add(stmt, true, rowResultFromProto);
}
/** Add a statement that returns at most a single value. */
queryValue(stmt) {
return this.#add(stmt, true, valueResultFromProto);
}
/** Add a statement without returning rows. */
run(stmt) {
return this.#add(stmt, false, stmtResultFromProto);
}
#add(inStmt, wantRows, fromProto) {
if (this._index !== void 0) {
throw new MisuseError(
"This BatchStep has already been added to the batch"
);
}
const stmt = stmtToProto(this._batch._stream._sqlOwner(), inStmt, wantRows);
let condition;
if (this.#conds.length === 0) {
condition = void 0;
} 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 !== void 0 && stepError !== void 0) {
errorCallback(
new ProtoError("Server returned both result and error")
);
} else if (stepError !== void 0) {
errorCallback(errorFromProto(stepError));
} else if (stepResult !== void 0) {
outputCallback(fromProto(stepResult, this._batch._stream.intMode));
} else {
outputCallback(void 0);
}
};
this._index = this._batch._steps.length;
this._batch._steps.push({ proto, callback });
});
}
};
var BatchCond = class {
/** @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" });
}
};
function stepIndex(step) {
if (step._index === void 0) {
throw new 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 MisuseError(
"Cannot mix BatchCond objects for different Batch objects"
);
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/describe.js
function describeResultFromProto(result) {
return {
paramNames: result.params.map((p2) => p2.name),
columns: result.cols,
isExplain: result.isExplain,
isReadonly: result.isReadonly,
};
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/stream.js
var Stream = class {
/** @private */
constructor(intMode) {
this.intMode = intMode;
}
/** Execute a statement and return rows. */
query(stmt) {
return this.#execute(stmt, true, rowsResultFromProto);
}
/** Execute a statement and return at most a single row. */
queryRow(stmt) {
return this.#execute(stmt, true, rowResultFromProto);
}
/** Execute a statement and return at most a single value. */
queryValue(stmt) {
return this.#execute(stmt, true, valueResultFromProto);
}
/** Execute a statement without returning rows. */
run(stmt) {
return this.#execute(stmt, false, stmtResultFromProto);
}
#execute(inStmt, wantRows, fromProto) {
const stmt = stmtToProto(this._sqlOwner(), inStmt, wantRows);
return this._execute(stmt).then((r) => fromProto(r, this.intMode));
}
/** Return a builder for creating and executing a batch.
*
* If `useCursor` is true, the batch will be executed using a Hrana cursor, which will stream results from
* the server to the client, which consumes less memory on the server. This requires protocol version 3 or
* higher.
*/
batch(useCursor = false) {
return new Batch(this, useCursor);
}
/** Parse and analyze a statement. This requires protocol version 2 or higher. */
describe(inSql) {
const protoSql = sqlToProto(this._sqlOwner(), inSql);
return this._describe(protoSql).then(describeResultFromProto);
}
/** Execute a sequence of statements separated by semicolons. This requires protocol version 2 or higher.
* */
sequence(inSql) {
const protoSql = sqlToProto(this._sqlOwner(), inSql);
return this._sequence(protoSql);
}
/** Representation of integers returned from the database. See {@link IntMode}.
*
* This value affects the results of all operations on this stream.
*/
intMode;
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/cursor.js
var Cursor = class {};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/cursor.js
var fetchChunkSize = 1e3;
var fetchQueueSize = 10;
var WsCursor = class extends Cursor {
#client;
#stream;
#cursorId;
#entryQueue;
#fetchQueue;
#closed;
#done;
/** @private */
constructor(client, stream, cursorId) {
super();
this.#client = client;
this.#stream = stream;
this.#cursorId = cursorId;
this.#entryQueue = new Queue();
this.#fetchQueue = new Queue();
this.#closed = void 0;
this.#done = false;
}
/** Fetch the next entry from the cursor. */
async next() {
for (;;) {
if (this.#closed !== void 0) {
throw new ClosedError("Cursor is closed", this.#closed);
}
while (!this.#done && this.#fetchQueue.length < fetchQueueSize) {
this.#fetchQueue.push(this.#fetch());
}
const entry = this.#entryQueue.shift();
if (this.#done || entry !== void 0) {
return entry;
}
await this.#fetchQueue.shift().then((response) => {
if (response === void 0) {
return;
}
for (const entry2 of response.entries) {
this.#entryQueue.push(entry2);
}
this.#done ||= response.done;
});
}
}
#fetch() {
return this.#stream
._sendCursorRequest(this, {
type: "fetch_cursor",
cursorId: this.#cursorId,
maxCount: fetchChunkSize,
})
.then(
(resp) => resp,
(error) => {
this._setClosed(error);
return void 0;
}
);
}
/** @private */
_setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
this.#stream
._sendCursorRequest(this, {
type: "close_cursor",
cursorId: this.#cursorId,
})
.catch(() => void 0);
this.#stream._cursorClosed(this);
}
/** Close the cursor. */
close() {
this._setClosed(new ClientError("Cursor was manually closed"));
}
/** True if the cursor is closed. */
get closed() {
return this.#closed !== void 0;
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/stream.js
var WsStream = class extends Stream {
#client;
#streamId;
#queue;
#cursor;
#closing;
#closed;
/** @private */
static open(client) {
const streamId = client._streamIdAlloc.alloc();
const stream = new WsStream(client, streamId);
const responseCallback = () => void 0;
const errorCallback = (e) => stream.#setClosed(e);
const request = { type: "open_stream", streamId };
client._sendRequest(request, { responseCallback, errorCallback });
return stream;
}
/** @private */
constructor(client, streamId) {
super(client.intMode);
this.#client = client;
this.#streamId = streamId;
this.#queue = new Queue();
this.#cursor = void 0;
this.#closing = false;
this.#closed = void 0;
}
/** Get the {@link WsClient} object that this stream belongs to. */
client() {
return this.#client;
}
/** @private */
_sqlOwner() {
return this.#client;
}
/** @private */
_execute(stmt) {
return this.#sendStreamRequest({
type: "execute",
streamId: this.#streamId,
stmt,
}).then((response) => {
return response.result;
});
}
/** @private */
_batch(batch) {
return this.#sendStreamRequest({
type: "batch",
streamId: this.#streamId,
batch,
}).then((response) => {
return response.result;
});
}
/** @private */
_describe(protoSql) {
this.#client._ensureVersion(2, "describe()");
return this.#sendStreamRequest({
type: "describe",
streamId: this.#streamId,
sql: protoSql.sql,
sqlId: protoSql.sqlId,
}).then((response) => {
return response.result;
});
}
/** @private */
_sequence(protoSql) {
this.#client._ensureVersion(2, "sequence()");
return this.#sendStreamRequest({
type: "sequence",
streamId: this.#streamId,
sql: protoSql.sql,
sqlId: protoSql.sqlId,
}).then((_response) => {
return void 0;
});
}
/** 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",
streamId: this.#streamId,
}).then((response) => {
return response.isAutocommit;
});
}
#sendStreamRequest(request) {
return new Promise((responseCallback, errorCallback) => {
this.#pushToQueue({
type: "request",
request,
responseCallback,
errorCallback,
});
});
}
/** @private */
_openCursor(batch) {
this.#client._ensureVersion(3, "cursor");
return new Promise((cursorCallback, errorCallback) => {
this.#pushToQueue({
type: "cursor",
batch,
cursorCallback,
errorCallback,
});
});
}
/** @private */
_sendCursorRequest(cursor, request) {
if (cursor !== this.#cursor) {
throw new InternalError(
"Cursor not associated with the stream attempted to execute a request"
);
}
return new Promise((responseCallback, errorCallback) => {
if (this.#closed !== void 0) {
errorCallback(new ClosedError("Stream is closed", this.#closed));
} else {
this.#client._sendRequest(request, { responseCallback, errorCallback });
}
});
}
/** @private */
_cursorClosed(cursor) {
if (cursor !== this.#cursor) {
throw new InternalError(
"Cursor was closed, but it was not associated with the stream"
);
}
this.#cursor = void 0;
this.#flushQueue();
}
#pushToQueue(entry) {
if (this.#closed !== void 0) {
entry.errorCallback(new ClosedError("Stream is closed", this.#closed));
} else if (this.#closing) {
entry.errorCallback(new ClosedError("Stream is closing", void 0));
} else {
this.#queue.push(entry);
this.#flushQueue();
}
}
#flushQueue() {
for (;;) {
const entry = this.#queue.first();
if (entry === void 0 && this.#cursor === void 0 && this.#closing) {
this.#setClosed(new ClientError("Stream was gracefully closed"));
break;
} else if (entry?.type === "request" && this.#cursor === void 0) {
const { request, responseCallback, errorCallback } = entry;
this.#queue.shift();
this.#client._sendRequest(request, { responseCallback, errorCallback });
} else if (entry?.type === "cursor" && this.#cursor === void 0) {
const { batch, cursorCallback } = entry;
this.#queue.shift();
const cursorId = this.#client._cursorIdAlloc.alloc();
const cursor = new WsCursor(this.#client, this, cursorId);
const request = {
type: "open_cursor",
streamId: this.#streamId,
cursorId,
batch,
};
const responseCallback = () => void 0;
const errorCallback = (e) => cursor._setClosed(e);
this.#client._sendRequest(request, { responseCallback, errorCallback });
this.#cursor = cursor;
cursorCallback(cursor);
} else {
break;
}
}
}
#setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
if (this.#cursor !== void 0) {
this.#cursor._setClosed(error);
}
for (;;) {
const entry = this.#queue.shift();
if (entry !== void 0) {
entry.errorCallback(error);
} else {
break;
}
}
const request = { type: "close_stream", streamId: this.#streamId };
const responseCallback = () =>
this.#client._streamIdAlloc.free(this.#streamId);
const errorCallback = () => void 0;
this.#client._sendRequest(request, { responseCallback, errorCallback });
}
/** Immediately close the stream. */
close() {
this.#setClosed(new ClientError("Stream was manually closed"));
}
/** Gracefully close the stream. */
closeGracefully() {
this.#closing = true;
this.#flushQueue();
}
/** True if the stream is closed or closing. */
get closed() {
return this.#closed !== void 0 || this.#closing;
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/shared/json_encode.js
function Stmt2(w, msg) {
if (msg.sql !== void 0) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== void 0) {
w.number("sql_id", msg.sqlId);
}
w.arrayObjects("args", msg.args, Value);
w.arrayObjects("named_args", msg.namedArgs, NamedArg);
w.boolean("want_rows", msg.wantRows);
}
function NamedArg(w, msg) {
w.string("name", msg.name);
w.object("value", msg.value, Value);
}
function Batch2(w, msg) {
w.arrayObjects("steps", msg.steps, BatchStep2);
}
function BatchStep2(w, msg) {
if (msg.condition !== void 0) {
w.object("condition", msg.condition, BatchCond2);
}
w.object("stmt", msg.stmt, Stmt2);
}
function BatchCond2(w, msg) {
w.stringRaw("type", msg.type);
if (msg.type === "ok" || msg.type === "error") {
w.number("step", msg.step);
} else if (msg.type === "not") {
w.object("cond", msg.cond, BatchCond2);
} else if (msg.type === "and" || msg.type === "or") {
w.arrayObjects("conds", msg.conds, BatchCond2);
} else if (msg.type === "is_autocommit") {
} else {
throw impossible(msg, "Impossible type of BatchCond");
}
}
function Value(w, msg) {
if (msg === null) {
w.stringRaw("type", "null");
} else if (typeof msg === "bigint") {
w.stringRaw("type", "integer");
w.stringRaw("value", "" + msg);
} else if (typeof msg === "number") {
w.stringRaw("type", "float");
w.number("value", msg);
} else if (typeof msg === "string") {
w.stringRaw("type", "text");
w.string("value", msg);
} else if (msg instanceof Uint8Array) {
w.stringRaw("type", "blob");
w.stringRaw("base64", gBase64.fromUint8Array(msg));
} else if (msg === void 0) {
} else {
throw impossible(msg, "Impossible type of Value");
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/json_encode.js
function ClientMsg(w, msg) {
w.stringRaw("type", msg.type);
if (msg.type === "hello") {
if (msg.jwt !== void 0) {
w.string("jwt", msg.jwt);
}
} else if (msg.type === "request") {
w.number("request_id", msg.requestId);
w.object("request", msg.request, Request2);
} else {
throw impossible(msg, "Impossible type of ClientMsg");
}
}
function Request2(w, msg) {
w.stringRaw("type", msg.type);
if (msg.type === "open_stream") {
w.number("stream_id", msg.streamId);
} else if (msg.type === "close_stream") {
w.number("stream_id", msg.streamId);
} else if (msg.type === "execute") {
w.number("stream_id", msg.streamId);
w.object("stmt", msg.stmt, Stmt2);
} else if (msg.type === "batch") {
w.number("stream_id", msg.streamId);
w.object("batch", msg.batch, Batch2);
} else if (msg.type === "open_cursor") {
w.number("stream_id", msg.streamId);
w.number("cursor_id", msg.cursorId);
w.object("batch", msg.batch, Batch2);
} else if (msg.type === "close_cursor") {
w.number("cursor_id", msg.cursorId);
} else if (msg.type === "fetch_cursor") {
w.number("cursor_id", msg.cursorId);
w.number("max_count", msg.maxCount);
} else if (msg.type === "sequence") {
w.number("stream_id", msg.streamId);
if (msg.sql !== void 0) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== void 0) {
w.number("sql_id", msg.sqlId);
}
} else if (msg.type === "describe") {
w.number("stream_id", msg.streamId);
if (msg.sql !== void 0) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== void 0) {
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") {
w.number("stream_id", msg.streamId);
} else {
throw impossible(msg, "Impossible type of Request");
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/shared/protobuf_encode.js
function Stmt3(w, msg) {
if (msg.sql !== void 0) {
w.string(1, msg.sql);
}
if (msg.sqlId !== void 0) {
w.int32(2, msg.sqlId);
}
for (const arg of msg.args) {
w.message(3, arg, Value2);
}
for (const arg of msg.namedArgs) {
w.message(4, arg, NamedArg2);
}
w.bool(5, msg.wantRows);
}
function NamedArg2(w, msg) {
w.string(1, msg.name);
w.message(2, msg.value, Value2);
}
function Batch3(w, msg) {
for (const step of msg.steps) {
w.message(1, step, BatchStep3);
}
}
function BatchStep3(w, msg) {
if (msg.condition !== void 0) {
w.message(1, msg.condition, BatchCond3);
}
w.message(2, msg.stmt, Stmt3);
}
function BatchCond3(w, msg) {
if (msg.type === "ok") {
w.uint32(1, msg.step);
} else if (msg.type === "error") {
w.uint32(2, msg.step);
} else if (msg.type === "not") {
w.message(3, msg.cond, BatchCond3);
} else if (msg.type === "and") {
w.message(4, msg.conds, BatchCondList);
} else if (msg.type === "or") {
w.message(5, msg.conds, BatchCondList);
} else if (msg.type === "is_autocommit") {
w.message(6, void 0, Empty);
} else {
throw impossible(msg, "Impossible type of BatchCond");
}
}
function BatchCondList(w, msg) {
for (const cond of msg) {
w.message(1, cond, BatchCond3);
}
}
function Value2(w, msg) {
if (msg === null) {
w.message(1, void 0, Empty);
} else if (typeof msg === "bigint") {
w.sint64(2, msg);
} else if (typeof msg === "number") {
w.double(3, msg);
} else if (typeof msg === "string") {
w.string(4, msg);
} else if (msg instanceof Uint8Array) {
w.bytes(5, msg);
} else if (msg === void 0) {
} else {
throw impossible(msg, "Impossible type of Value");
}
}
function Empty(_w, _msg) {}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/protobuf_encode.js
function ClientMsg2(w, msg) {
if (msg.type === "hello") {
w.message(1, msg, HelloMsg);
} else if (msg.type === "request") {
w.message(2, msg, RequestMsg);
} else {
throw impossible(msg, "Impossible type of ClientMsg");
}
}
function HelloMsg(w, msg) {
if (msg.jwt !== void 0) {
w.string(1, msg.jwt);
}
}
function RequestMsg(w, msg) {
w.int32(1, msg.requestId);
const request = msg.request;
if (request.type === "open_stream") {
w.message(2, request, OpenStreamReq);
} else if (request.type === "close_stream") {
w.message(3, request, CloseStreamReq);
} else if (request.type === "execute") {
w.message(4, request, ExecuteReq);
} else if (request.type === "batch") {
w.message(5, request, BatchReq);
} else if (request.type === "open_cursor") {
w.message(6, request, OpenCursorReq);
} else if (request.type === "close_cursor") {
w.message(7, request, CloseCursorReq);
} else if (request.type === "fetch_cursor") {
w.message(8, request, FetchCursorReq);
} else if (request.type === "sequence") {
w.message(9, request, SequenceReq);
} else if (request.type === "describe") {
w.message(10, request, DescribeReq);
} else if (request.type === "store_sql") {
w.message(11, request, StoreSqlReq);
} else if (request.type === "close_sql") {
w.message(12, request, CloseSqlReq);
} else if (request.type === "get_autocommit") {
w.message(13, request, GetAutocommitReq);
} else {
throw impossible(request, "Impossible type of Request");
}
}
function OpenStreamReq(w, msg) {
w.int32(1, msg.streamId);
}
function CloseStreamReq(w, msg) {
w.int32(1, msg.streamId);
}
function ExecuteReq(w, msg) {
w.int32(1, msg.streamId);
w.message(2, msg.stmt, Stmt3);
}
function BatchReq(w, msg) {
w.int32(1, msg.streamId);
w.message(2, msg.batch, Batch3);
}
function OpenCursorReq(w, msg) {
w.int32(1, msg.streamId);
w.int32(2, msg.cursorId);
w.message(3, msg.batch, Batch3);
}
function CloseCursorReq(w, msg) {
w.int32(1, msg.cursorId);
}
function FetchCursorReq(w, msg) {
w.int32(1, msg.cursorId);
w.uint32(2, msg.maxCount);
}
function SequenceReq(w, msg) {
w.int32(1, msg.streamId);
if (msg.sql !== void 0) {
w.string(2, msg.sql);
}
if (msg.sqlId !== void 0) {
w.int32(3, msg.sqlId);
}
}
function DescribeReq(w, msg) {
w.int32(1, msg.streamId);
if (msg.sql !== void 0) {
w.string(2, msg.sql);
}
if (msg.sqlId !== void 0) {
w.int32(3, msg.sqlId);
}
}
function StoreSqlReq(w, msg) {
w.int32(1, msg.sqlId);
w.string(2, msg.sql);
}
function CloseSqlReq(w, msg) {
w.int32(1, msg.sqlId);
}
function GetAutocommitReq(w, msg) {
w.int32(1, msg.streamId);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/shared/json_decode.js
function Error2(obj) {
const message = string(obj["message"]);
const code = stringOpt(obj["code"]);
return { message, code };
}
function StmtResult(obj) {
const cols = arrayObjectsMap(obj["cols"], Col);
const rows = array(obj["rows"]).map((rowObj) =>
arrayObjectsMap(rowObj, Value3)
);
const affectedRowCount = number(obj["affected_row_count"]);
const lastInsertRowidStr = stringOpt(obj["last_insert_rowid"]);
const lastInsertRowid =
lastInsertRowidStr !== void 0 ? BigInt(lastInsertRowidStr) : void 0;
return { cols, rows, affectedRowCount, lastInsertRowid };
}
function Col(obj) {
const name = stringOpt(obj["name"]);
const decltype = stringOpt(obj["decltype"]);
return { name, decltype };
}
function BatchResult(obj) {
const stepResults = /* @__PURE__ */ new Map();
array(obj["step_results"]).forEach((value, i) => {
if (value !== null) {
stepResults.set(i, StmtResult(object(value)));
}
});
const stepErrors = /* @__PURE__ */ new Map();
array(obj["step_errors"]).forEach((value, i) => {
if (value !== null) {
stepErrors.set(i, Error2(object(value)));
}
});
return { stepResults, stepErrors };
}
function CursorEntry(obj) {
const type = string(obj["type"]);
if (type === "step_begin") {
const step = number(obj["step"]);
const cols = arrayObjectsMap(obj["cols"], Col);
return { type: "step_begin", step, cols };
} else if (type === "step_end") {
const affectedRowCount = number(obj["affected_row_count"]);
const lastInsertRowidStr = stringOpt(obj["last_insert_rowid"]);
const lastInsertRowid =
lastInsertRowidStr !== void 0 ? BigInt(lastInsertRowidStr) : void 0;
return { type: "step_end", affectedRowCount, lastInsertRowid };
} else if (type === "step_error") {
const step = number(obj["step"]);
const error = Error2(object(obj["error"]));
return { type: "step_error", step, error };
} else if (type === "row") {
const row = arrayObjectsMap(obj["row"], Value3);
return { type: "row", row };
} else if (type === "error") {
const error = Error2(object(obj["error"]));
return { type: "error", error };
} else {
throw new ProtoError("Unexpected type of CursorEntry");
}
}
function DescribeResult(obj) {
const params = arrayObjectsMap(obj["params"], DescribeParam);
const cols = arrayObjectsMap(obj["cols"], DescribeCol);
const isExplain = boolean(obj["is_explain"]);
const isReadonly = boolean(obj["is_readonly"]);
return { params, cols, isExplain, isReadonly };
}
function DescribeParam(obj) {
const name = stringOpt(obj["name"]);
return { name };
}
function DescribeCol(obj) {
const name = string(obj["name"]);
const decltype = stringOpt(obj["decltype"]);
return { name, decltype };
}
function Value3(obj) {
const type = string(obj["type"]);
if (type === "null") {
return null;
} else if (type === "integer") {
const value = string(obj["value"]);
return BigInt(value);
} else if (type === "float") {
return number(obj["value"]);
} else if (type === "text") {
return string(obj["value"]);
} else if (type === "blob") {
return gBase64.toUint8Array(string(obj["base64"]));
} else {
throw new ProtoError("Unexpected type of Value");
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/json_decode.js
function ServerMsg(obj) {
const type = string(obj["type"]);
if (type === "hello_ok") {
return { type: "hello_ok" };
} else if (type === "hello_error") {
const error = Error2(object(obj["error"]));
return { type: "hello_error", error };
} else if (type === "response_ok") {
const requestId = number(obj["request_id"]);
const response = Response2(object(obj["response"]));
return { type: "response_ok", requestId, response };
} else if (type === "response_error") {
const requestId = number(obj["request_id"]);
const error = Error2(object(obj["error"]));
return { type: "response_error", requestId, error };
} else {
throw new ProtoError("Unexpected type of ServerMsg");
}
}
function Response2(obj) {
const type = string(obj["type"]);
if (type === "open_stream") {
return { type: "open_stream" };
} else if (type === "close_stream") {
return { type: "close_stream" };
} else if (type === "execute") {
const result = StmtResult(object(obj["result"]));
return { type: "execute", result };
} else if (type === "batch") {
const result = BatchResult(object(obj["result"]));
return { type: "batch", result };
} else if (type === "open_cursor") {
return { type: "open_cursor" };
} else if (type === "close_cursor") {
return { type: "close_cursor" };
} else if (type === "fetch_cursor") {
const entries = arrayObjectsMap(obj["entries"], CursorEntry);
const done = boolean(obj["done"]);
return { type: "fetch_cursor", entries, done };
} else if (type === "sequence") {
return { type: "sequence" };
} else if (type === "describe") {
const result = DescribeResult(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 = boolean(obj["is_autocommit"]);
return { type: "get_autocommit", isAutocommit };
} else {
throw new ProtoError("Unexpected type of Response");
}
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/shared/protobuf_decode.js
var Error3 = {
default() {
return { message: "", code: void 0 };
},
1(r, msg) {
msg.message = r.string();
},
2(r, msg) {
msg.code = r.string();
},
};
var StmtResult2 = {
default() {
return {
cols: [],
rows: [],
affectedRowCount: 0,
lastInsertRowid: void 0,
};
},
1(r, msg) {
msg.cols.push(r.message(Col2));
},
2(r, msg) {
msg.rows.push(r.message(Row));
},
3(r, msg) {
msg.affectedRowCount = Number(r.uint64());
},
4(r, msg) {
msg.lastInsertRowid = r.sint64();
},
};
var Col2 = {
default() {
return { name: void 0, decltype: void 0 };
},
1(r, msg) {
msg.name = r.string();
},
2(r, msg) {
msg.decltype = r.string();
},
};
var Row = {
default() {
return [];
},
1(r, msg) {
msg.push(r.message(Value4));
},
};
var BatchResult2 = {
default() {
return {
stepResults: /* @__PURE__ */ new Map(),
stepErrors: /* @__PURE__ */ new Map(),
};
},
1(r, msg) {
const [key, value] = r.message(BatchResultStepResult);
msg.stepResults.set(key, value);
},
2(r, msg) {
const [key, value] = r.message(BatchResultStepError);
msg.stepErrors.set(key, value);
},
};
var BatchResultStepResult = {
default() {
return [0, StmtResult2.default()];
},
1(r, msg) {
msg[0] = r.uint32();
},
2(r, msg) {
msg[1] = r.message(StmtResult2);
},
};
var BatchResultStepError = {
default() {
return [0, Error3.default()];
},
1(r, msg) {
msg[0] = r.uint32();
},
2(r, msg) {
msg[1] = r.message(Error3);
},
};
var CursorEntry2 = {
default() {
return { type: "none" };
},
1(r) {
return r.message(StepBeginEntry);
},
2(r) {
return r.message(StepEndEntry);
},
3(r) {
return r.message(StepErrorEntry);
},
4(r) {
return { type: "row", row: r.message(Row) };
},
5(r) {
return { type: "error", error: r.message(Error3) };
},
};
var StepBeginEntry = {
default() {
return { type: "step_begin", step: 0, cols: [] };
},
1(r, msg) {
msg.step = r.uint32();
},
2(r, msg) {
msg.cols.push(r.message(Col2));
},
};
var StepEndEntry = {
default() {
return {
type: "step_end",
affectedRowCount: 0,
lastInsertRowid: void 0,
};
},
1(r, msg) {
msg.affectedRowCount = r.uint32();
},
2(r, msg) {
msg.lastInsertRowid = r.uint64();
},
};
var StepErrorEntry = {
default() {
return {
type: "step_error",
step: 0,
error: Error3.default(),
};
},
1(r, msg) {
msg.step = r.uint32();
},
2(r, msg) {
msg.error = r.message(Error3);
},
};
var DescribeResult2 = {
default() {
return {
params: [],
cols: [],
isExplain: false,
isReadonly: false,
};
},
1(r, msg) {
msg.params.push(r.message(DescribeParam2));
},
2(r, msg) {
msg.cols.push(r.message(DescribeCol2));
},
3(r, msg) {
msg.isExplain = r.bool();
},
4(r, msg) {
msg.isReadonly = r.bool();
},
};
var DescribeParam2 = {
default() {
return { name: void 0 };
},
1(r, msg) {
msg.name = r.string();
},
};
var DescribeCol2 = {
default() {
return { name: "", decltype: void 0 };
},
1(r, msg) {
msg.name = r.string();
},
2(r, msg) {
msg.decltype = r.string();
},
};
var Value4 = {
default() {
return void 0;
},
1(r) {
return null;
},
2(r) {
return r.sint64();
},
3(r) {
return r.double();
},
4(r) {
return r.string();
},
5(r) {
return r.bytes();
},
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/protobuf_decode.js
var ServerMsg2 = {
default() {
return { type: "none" };
},
1(r) {
return { type: "hello_ok" };
},
2(r) {
return r.message(HelloErrorMsg);
},
3(r) {
return r.message(ResponseOkMsg);
},
4(r) {
return r.message(ResponseErrorMsg);
},
};
var HelloErrorMsg = {
default() {
return { type: "hello_error", error: Error3.default() };
},
1(r, msg) {
msg.error = r.message(Error3);
},
};
var ResponseErrorMsg = {
default() {
return { type: "response_error", requestId: 0, error: Error3.default() };
},
1(r, msg) {
msg.requestId = r.int32();
},
2(r, msg) {
msg.error = r.message(Error3);
},
};
var ResponseOkMsg = {
default() {
return {
type: "response_ok",
requestId: 0,
response: { type: "none" },
};
},
1(r, msg) {
msg.requestId = r.int32();
},
2(r, msg) {
msg.response = { type: "open_stream" };
},
3(r, msg) {
msg.response = { type: "close_stream" };
},
4(r, msg) {
msg.response = r.message(ExecuteResp);
},
5(r, msg) {
msg.response = r.message(BatchResp);
},
6(r, msg) {
msg.response = { type: "open_cursor" };
},
7(r, msg) {
msg.response = { type: "close_cursor" };
},
8(r, msg) {
msg.response = r.message(FetchCursorResp);
},
9(r, msg) {
msg.response = { type: "sequence" };
},
10(r, msg) {
msg.response = r.message(DescribeResp);
},
11(r, msg) {
msg.response = { type: "store_sql" };
},
12(r, msg) {
msg.response = { type: "close_sql" };
},
13(r, msg) {
msg.response = r.message(GetAutocommitResp);
},
};
var ExecuteResp = {
default() {
return { type: "execute", result: StmtResult2.default() };
},
1(r, msg) {
msg.result = r.message(StmtResult2);
},
};
var BatchResp = {
default() {
return { type: "batch", result: BatchResult2.default() };
},
1(r, msg) {
msg.result = r.message(BatchResult2);
},
};
var FetchCursorResp = {
default() {
return { type: "fetch_cursor", entries: [], done: false };
},
1(r, msg) {
msg.entries.push(r.message(CursorEntry2));
},
2(r, msg) {
msg.done = r.bool();
},
};
var DescribeResp = {
default() {
return { type: "describe", result: DescribeResult2.default() };
},
1(r, msg) {
msg.result = r.message(DescribeResult2);
},
};
var GetAutocommitResp = {
default() {
return { type: "get_autocommit", isAutocommit: false };
},
1(r, msg) {
msg.isAutocommit = r.bool();
},
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/ws/client.js
var subprotocolsV2 = /* @__PURE__ */ new Map([
["hrana2", { version: 2, encoding: "json" }],
["hrana1", { version: 1, encoding: "json" }],
]);
var subprotocolsV3 = /* @__PURE__ */ new Map([
["hrana3-protobuf", { version: 3, encoding: "protobuf" }],
["hrana3", { version: 3, encoding: "json" }],
["hrana2", { version: 2, encoding: "json" }],
["hrana1", { version: 1, encoding: "json" }],
]);
var WsClient = class extends Client {
#socket;
// List of callbacks that we queue until the socket transitions from the CONNECTING to the OPEN state.
#openCallbacks;
// Have we already transitioned from CONNECTING to OPEN and fired the callbacks in #openCallbacks?
#opened;
// Stores the error that caused us to close the client (and the socket). If we are not closed, this is
// `undefined`.
#closed;
// Have we received a response to our "hello" from the server?
#recvdHello;
// Subprotocol negotiated with the server. It is only available after the socket transitions to the OPEN
// state.
#subprotocol;
// Has the `getVersion()` function been called? This is only used to validate that the API is used
// correctly.
#getVersionCalled;
// A map from request id to the responses that we expect to receive from the server.
#responseMap;
// An allocator of request ids.
#requestIdAlloc;
// An allocator of stream ids.
/** @private */
_streamIdAlloc;
// An allocator of cursor ids.
/** @private */
_cursorIdAlloc;
// An allocator of SQL text ids.
#sqlIdAlloc;
/** @private */
constructor(socket, jwt) {
super();
this.#socket = socket;
this.#openCallbacks = [];
this.#opened = false;
this.#closed = void 0;
this.#recvdHello = false;
this.#subprotocol = void 0;
this.#getVersionCalled = false;
this.#responseMap = /* @__PURE__ */ new Map();
this.#requestIdAlloc = new IdAlloc();
this._streamIdAlloc = new IdAlloc();
this._cursorIdAlloc = new IdAlloc();
this.#sqlIdAlloc = new IdAlloc();
this.#socket.binaryType = "arraybuffer";
this.#socket.addEventListener("open", () => this.#onSocketOpen());
this.#socket.addEventListener("close", (event) =>
this.#onSocketClose(event)
);
this.#socket.addEventListener("error", (event) =>
this.#onSocketError(event)
);
this.#socket.addEventListener("message", (event) =>
this.#onSocketMessage(event)
);
this.#send({ type: "hello", jwt });
}
// Send (or enqueue to send) a message to the server.
#send(msg) {
if (this.#closed !== void 0) {
throw new InternalError("Trying to send a message on a closed client");
}
if (this.#opened) {
this.#sendToSocket(msg);
} else {
const openCallback = () => this.#sendToSocket(msg);
const errorCallback = () => void 0;
this.#openCallbacks.push({ openCallback, errorCallback });
}
}
// The socket transitioned from CONNECTING to OPEN
#onSocketOpen() {
const protocol = this.#socket.protocol;
if (protocol === void 0) {
this.#setClosed(
new ClientError(
"The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."
)
);
return;
} else if (protocol === "") {
this.#subprotocol = { version: 1, encoding: "json" };
} else {
this.#subprotocol = subprotocolsV3.get(protocol);
if (this.#subprotocol === void 0) {
this.#setClosed(
new ProtoError(
`Unrecognized WebSocket subprotocol: ${JSON.stringify(protocol)}`
)
);
return;
}
}
for (const callbacks of this.#openCallbacks) {
callbacks.openCallback();
}
this.#openCallbacks.length = 0;
this.#opened = true;
}
#sendToSocket(msg) {
const encoding = this.#subprotocol.encoding;
if (encoding === "json") {
const jsonMsg = writeJsonObject(msg, ClientMsg);
this.#socket.send(jsonMsg);
} else if (encoding === "protobuf") {
const protobufMsg = writeProtobufMessage(msg, ClientMsg2);
this.#socket.send(protobufMsg);
} else {
throw impossible(encoding, "Impossible encoding");
}
}
/** Get the protocol version negotiated with the server, possibly waiting until the socket is open. */
getVersion() {
return new Promise((versionCallback, errorCallback) => {
this.#getVersionCalled = true;
if (this.#closed !== void 0) {
errorCallback(this.#closed);
} else if (!this.#opened) {
const openCallback = () => versionCallback(this.#subprotocol.version);
this.#openCallbacks.push({ openCallback, errorCallback });
} else {
versionCallback(this.#subprotocol.version);
}
});
}
// Make sure that the negotiated version is at least `minVersion`.
/** @private */
_ensureVersion(minVersion, feature) {
if (this.#subprotocol === void 0 || !this.#getVersionCalled) {
throw new ProtocolVersionError(
`${feature} is supported only on protocol version ${minVersion} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`
);
} else if (this.#subprotocol.version < minVersion) {
throw new ProtocolVersionError(
`${feature} is supported on protocol version ${minVersion} and higher, but the WebSocket server only supports version ${this.#subprotocol.version}`
);
}
}
// Send a request to the server and invoke a callback when we get the response.
/** @private */
_sendRequest(request, callbacks) {
if (this.#closed !== void 0) {
callbacks.errorCallback(
new ClosedError("Client is closed", this.#closed)
);
return;
}
const requestId = this.#requestIdAlloc.alloc();
this.#responseMap.set(requestId, { ...callbacks, type: request.type });
this.#send({ type: "request", requestId, request });
}
// The socket encountered an error.
#onSocketError(event) {
const eventMessage = event.message;
const message = eventMessage ?? "WebSocket was closed due to an error";
this.#setClosed(new WebSocketError(message));
}
// The socket was closed.
#onSocketClose(event) {
let message = `WebSocket was closed with code ${event.code}`;
if (event.reason) {
message += `: ${event.reason}`;
}
this.#setClosed(new WebSocketError(message));
}
// Close the client with the given error.
#setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
for (const callbacks of this.#openCallbacks) {
callbacks.errorCallback(error);
}
this.#openCallbacks.length = 0;
for (const [requestId, responseState] of this.#responseMap.entries()) {
responseState.errorCallback(error);
this.#requestIdAlloc.free(requestId);
}
this.#responseMap.clear();
this.#socket.close();
}
// We received a message from the socket.
#onSocketMessage(event) {
if (this.#closed !== void 0) {
return;
}
try {
let msg;
const encoding = this.#subprotocol.encoding;
if (encoding === "json") {
if (typeof event.data !== "string") {
this.#socket.close(
3003,
"Only text messages are accepted with JSON encoding"
);
this.#setClosed(
new ProtoError(
"Received non-text message from server with JSON encoding"
)
);
return;
}
msg = readJsonObject(JSON.parse(event.data), ServerMsg);
} else if (encoding === "protobuf") {
if (!(event.data instanceof ArrayBuffer)) {
this.#socket.close(
3003,
"Only binary messages are accepted with Protobuf encoding"
);
this.#setClosed(
new ProtoError(
"Received non-binary message from server with Protobuf encoding"
)
);
return;
}
msg = readProtobufMessage(new Uint8Array(event.data), ServerMsg2);
} else {
throw impossible(encoding, "Impossible encoding");
}
this.#handleMsg(msg);
} catch (e) {
this.#socket.close(3007, "Could not handle message");
this.#setClosed(e);
}
}
// Handle a message from the server.
#handleMsg(msg) {
if (msg.type === "none") {
throw new ProtoError("Received an unrecognized ServerMsg");
} else if (msg.type === "hello_ok" || msg.type === "hello_error") {
if (this.#recvdHello) {
throw new ProtoError("Received a duplicated hello response");
}
this.#recvdHello = true;
if (msg.type === "hello_error") {
throw errorFromProto(msg.error);
}
return;
} else if (!this.#recvdHello) {
throw new ProtoError(
"Received a non-hello message before a hello response"
);
}
if (msg.type === "response_ok") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === void 0) {
throw new ProtoError("Received unexpected OK response");
}
this.#requestIdAlloc.free(requestId);
try {
if (responseState.type !== msg.response.type) {
console.dir({ responseState, msg });
throw new ProtoError("Received unexpected type of response");
}
responseState.responseCallback(msg.response);
} catch (e) {
responseState.errorCallback(e);
throw e;
}
} else if (msg.type === "response_error") {
const requestId = msg.requestId;
const responseState = this.#responseMap.get(requestId);
this.#responseMap.delete(requestId);
if (responseState === void 0) {
throw new ProtoError("Received unexpected error response");
}
this.#requestIdAlloc.free(requestId);
responseState.errorCallback(errorFromProto(msg.error));
} else {
throw impossible(msg, "Impossible ServerMsg type");
}
}
/** Open a {@link WsStream}, a stream for executing SQL statements. */
openStream() {
return WsStream.open(this);
}
/** Cache a SQL text on the server. This requires protocol version 2 or higher. */
storeSql(sql2) {
this._ensureVersion(2, "storeSql()");
const sqlId = this.#sqlIdAlloc.alloc();
const sqlObj = new Sql(this, sqlId);
const responseCallback = () => void 0;
const errorCallback = (e) => sqlObj._setClosed(e);
const request = { type: "store_sql", sqlId, sql: sql2 };
this._sendRequest(request, { responseCallback, errorCallback });
return sqlObj;
}
/** @private */
_closeSql(sqlId) {
if (this.#closed !== void 0) {
return;
}
const responseCallback = () => this.#sqlIdAlloc.free(sqlId);
const errorCallback = (e) => this.#setClosed(e);
const request = { type: "close_sql", sqlId };
this._sendRequest(request, { responseCallback, errorCallback });
}
/** Close the client and the WebSocket. */
close() {
this.#setClosed(new ClientError("Client was manually closed"));
}
/** True if the client is closed. */
get closed() {
return this.#closed !== void 0;
}
};
// ../../node_modules/.pnpm/@libsql+isomorphic-fetch@0.1.10/node_modules/@libsql/isomorphic-fetch/web.js
var _fetch = fetch;
var _Request = Request;
var _Headers = Headers;
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/queue_microtask.js
var _queueMicrotask;
if (typeof queueMicrotask !== "undefined") {
_queueMicrotask = queueMicrotask;
} else {
const resolved = Promise.resolve();
_queueMicrotask = (callback) => {
resolved.then(callback);
};
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/byte_queue.js
var ByteQueue = class {
#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;
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/json_decode.js
function PipelineRespBody(obj) {
const baton = stringOpt(obj["baton"]);
const baseUrl = stringOpt(obj["base_url"]);
const results = arrayObjectsMap(obj["results"], StreamResult);
return { baton, baseUrl, results };
}
function StreamResult(obj) {
const type = string(obj["type"]);
if (type === "ok") {
const response = StreamResponse(object(obj["response"]));
return { type: "ok", response };
} else if (type === "error") {
const error = Error2(object(obj["error"]));
return { type: "error", error };
} else {
throw new ProtoError("Unexpected type of StreamResult");
}
}
function StreamResponse(obj) {
const type = string(obj["type"]);
if (type === "close") {
return { type: "close" };
} else if (type === "execute") {
const result = StmtResult(object(obj["result"]));
return { type: "execute", result };
} else if (type === "batch") {
const result = BatchResult(object(obj["result"]));
return { type: "batch", result };
} else if (type === "sequence") {
return { type: "sequence" };
} else if (type === "describe") {
const result = DescribeResult(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 = boolean(obj["is_autocommit"]);
return { type: "get_autocommit", isAutocommit };
} else {
throw new ProtoError("Unexpected type of StreamResponse");
}
}
function CursorRespBody(obj) {
const baton = stringOpt(obj["baton"]);
const baseUrl = stringOpt(obj["base_url"]);
return { baton, baseUrl };
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/protobuf_decode.js
var PipelineRespBody2 = {
default() {
return { baton: void 0, baseUrl: void 0, results: [] };
},
1(r, msg) {
msg.baton = r.string();
},
2(r, msg) {
msg.baseUrl = r.string();
},
3(r, msg) {
msg.results.push(r.message(StreamResult2));
},
};
var StreamResult2 = {
default() {
return { type: "none" };
},
1(r) {
return { type: "ok", response: r.message(StreamResponse2) };
},
2(r) {
return { type: "error", error: r.message(Error3) };
},
};
var StreamResponse2 = {
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);
},
};
var ExecuteStreamResp = {
default() {
return { type: "execute", result: StmtResult2.default() };
},
1(r, msg) {
msg.result = r.message(StmtResult2);
},
};
var BatchStreamResp = {
default() {
return { type: "batch", result: BatchResult2.default() };
},
1(r, msg) {
msg.result = r.message(BatchResult2);
},
};
var DescribeStreamResp = {
default() {
return { type: "describe", result: DescribeResult2.default() };
},
1(r, msg) {
msg.result = r.message(DescribeResult2);
},
};
var GetAutocommitStreamResp = {
default() {
return { type: "get_autocommit", isAutocommit: false };
},
1(r, msg) {
msg.isAutocommit = r.bool();
},
};
var CursorRespBody2 = {
default() {
return { baton: void 0, baseUrl: void 0 };
},
1(r, msg) {
msg.baton = r.string();
},
2(r, msg) {
msg.baseUrl = r.string();
},
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/cursor.js
var HttpCursor = class extends Cursor {
#stream;
#encoding;
#reader;
#queue;
#closed;
#done;
/** @private */
constructor(stream, encoding) {
super();
this.#stream = stream;
this.#encoding = encoding;
this.#reader = void 0;
this.#queue = new ByteQueue(16 * 1024);
this.#closed = void 0;
this.#done = false;
}
async open(response) {
if (response.body === null) {
throw new ProtoError("No response body for cursor request");
}
this.#reader = response.body.getReader();
const respBody = await this.#nextItem(CursorRespBody, CursorRespBody2);
if (respBody === void 0) {
throw new ProtoError("Empty response to cursor request");
}
return respBody;
}
/** Fetch the next entry from the cursor. */
next() {
return this.#nextItem(CursorEntry, CursorEntry2);
}
/** Close the cursor. */
close() {
this._setClosed(new ClientError("Cursor was manually closed"));
}
/** @private */
_setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
this.#stream._cursorClosed(this);
if (this.#reader !== void 0) {
this.#reader.cancel();
}
}
/** True if the cursor is closed. */
get closed() {
return this.#closed !== void 0;
}
async #nextItem(jsonFun, protobufDef) {
for (;;) {
if (this.#done) {
return void 0;
} else if (this.#closed !== void 0) {
throw new ClosedError("Cursor is closed", this.#closed);
}
if (this.#encoding === "json") {
const jsonData = this.#parseItemJson();
if (jsonData !== void 0) {
const jsonText = new TextDecoder().decode(jsonData);
const jsonValue = JSON.parse(jsonText);
return readJsonObject(jsonValue, jsonFun);
}
} else if (this.#encoding === "protobuf") {
const protobufData = this.#parseItemProtobuf();
if (protobufData !== void 0) {
return readProtobufMessage(protobufData, protobufDef);
}
} else {
throw impossible(this.#encoding, "Impossible encoding");
}
if (this.#reader === void 0) {
throw new InternalError(
"Attempted to read from HTTP cursor before it was opened"
);
}
const { value, done } = await this.#reader.read();
if (done && this.#queue.length === 0) {
this.#done = true;
} else if (done) {
throw new 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 void 0;
}
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 void 0;
}
const byte = data[varintLength];
varintValue |= (byte & 127) << (7 * varintLength);
varintLength += 1;
if (!(byte & 128)) {
break;
}
}
if (data.byteLength < varintLength + varintValue) {
return void 0;
}
const protobufData = data.slice(varintLength, varintLength + varintValue);
this.#queue.shift(varintLength + varintValue);
return protobufData;
}
};
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/json_encode.js
function PipelineReqBody(w, msg) {
if (msg.baton !== void 0) {
w.string("baton", msg.baton);
}
w.arrayObjects("requests", msg.requests, StreamRequest);
}
function StreamRequest(w, msg) {
w.stringRaw("type", msg.type);
if (msg.type === "close") {
} else if (msg.type === "execute") {
w.object("stmt", msg.stmt, Stmt2);
} else if (msg.type === "batch") {
w.object("batch", msg.batch, Batch2);
} else if (msg.type === "sequence") {
if (msg.sql !== void 0) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== void 0) {
w.number("sql_id", msg.sqlId);
}
} else if (msg.type === "describe") {
if (msg.sql !== void 0) {
w.string("sql", msg.sql);
}
if (msg.sqlId !== void 0) {
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") {
} else {
throw impossible(msg, "Impossible type of StreamRequest");
}
}
function CursorReqBody(w, msg) {
if (msg.baton !== void 0) {
w.string("baton", msg.baton);
}
w.object("batch", msg.batch, Batch2);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/protobuf_encode.js
function PipelineReqBody2(w, msg) {
if (msg.baton !== void 0) {
w.string(1, msg.baton);
}
for (const req of msg.requests) {
w.message(2, req, StreamRequest2);
}
}
function StreamRequest2(w, msg) {
if (msg.type === "close") {
w.message(1, msg, CloseStreamReq2);
} 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 impossible(msg, "Impossible type of StreamRequest");
}
}
function CloseStreamReq2(_w, _msg) {}
function ExecuteStreamReq(w, msg) {
w.message(1, msg.stmt, Stmt3);
}
function BatchStreamReq(w, msg) {
w.message(1, msg.batch, Batch3);
}
function SequenceStreamReq(w, msg) {
if (msg.sql !== void 0) {
w.string(1, msg.sql);
}
if (msg.sqlId !== void 0) {
w.int32(2, msg.sqlId);
}
}
function DescribeStreamReq(w, msg) {
if (msg.sql !== void 0) {
w.string(1, msg.sql);
}
if (msg.sqlId !== void 0) {
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 CursorReqBody2(w, msg) {
if (msg.baton !== void 0) {
w.string(1, msg.baton);
}
w.message(2, msg.batch, Batch3);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/stream.js
var HttpStream = class extends Stream {
#client;
#baseUrl;
#jwt;
#fetch;
#baton;
#queue;
#flushing;
#cursor;
#closing;
#closeQueued;
#closed;
#sqlIdAlloc;
/** @private */
constructor(client, baseUrl, jwt, customFetch) {
super(client.intMode);
this.#client = client;
this.#baseUrl = baseUrl.toString();
this.#jwt = jwt;
this.#fetch = customFetch;
this.#baton = void 0;
this.#queue = new Queue();
this.#flushing = false;
this.#closing = false;
this.#closeQueued = false;
this.#closed = void 0;
this.#sqlIdAlloc = new 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(sql2) {
const sqlId = this.#sqlIdAlloc.alloc();
this.#sendStreamRequest({ type: "store_sql", sqlId, sql: sql2 }).then(
() => void 0,
(error) => this._setClosed(error)
);
return new Sql(this, sqlId);
}
/** @private */
_closeSql(sqlId) {
if (this.#closed !== void 0) {
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 void 0;
});
}
/** 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 InternalError(
"Cursor was closed, but it was not associated with the stream"
);
}
this.#cursor = void 0;
_queueMicrotask(() => this.#flushQueue());
}
/** Immediately close the stream. */
close() {
this._setClosed(new ClientError("Stream was manually closed"));
}
/** Gracefully close the stream. */
closeGracefully() {
this.#closing = true;
_queueMicrotask(() => this.#flushQueue());
}
/** True if the stream is closed. */
get closed() {
return this.#closed !== void 0 || this.#closing;
}
/** @private */
_setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
if (this.#cursor !== void 0) {
this.#cursor._setClosed(error);
}
this.#client._streamClosed(this);
for (;;) {
const entry = this.#queue.shift();
if (entry !== void 0) {
entry.errorCallback(error);
} else {
break;
}
}
if ((this.#baton !== void 0 || this.#flushing) && !this.#closeQueued) {
this.#queue.push({
type: "pipeline",
request: { type: "close" },
responseCallback: () => void 0,
errorCallback: () => void 0,
});
this.#closeQueued = true;
_queueMicrotask(() => this.#flushQueue());
}
}
#pushToQueue(entry) {
if (this.#closed !== void 0) {
throw new ClosedError("Stream is closed", this.#closed);
} else if (this.#closing) {
throw new ClosedError("Stream is closing", void 0);
} else {
this.#queue.push(entry);
_queueMicrotask(() => this.#flushQueue());
}
}
#flushQueue() {
if (this.#flushing || this.#cursor !== void 0) {
return;
}
if (this.#closing && this.#queue.length === 0) {
this._setClosed(new ClientError("Stream was gracefully closed"));
return;
}
const endpoint = this.#client._endpoint;
if (endpoint === void 0) {
this.#client._endpointPromise.then(
() => this.#flushQueue(),
(error) => this._setClosed(error)
);
return;
}
const firstEntry = this.#queue.shift();
if (firstEntry === void 0) {
return;
} else if (firstEntry.type === "pipeline") {
const pipeline = [firstEntry];
for (;;) {
const entry = this.#queue.first();
if (entry !== void 0 && entry.type === "pipeline") {
pipeline.push(entry);
this.#queue.shift();
} else if (entry === void 0 && this.#closing && !this.#closeQueued) {
pipeline.push({
type: "pipeline",
request: { type: "close" },
responseCallback: () => void 0,
errorCallback: () => void 0,
});
this.#closeQueued = true;
break;
} else {
break;
}
}
this.#flushPipeline(endpoint, pipeline);
} else if (firstEntry.type === "cursor") {
this.#flushCursor(endpoint, firstEntry);
} else {
throw 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 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 fetch2 = this.#fetch;
promise = fetch2(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,
PipelineReqBody,
PipelineReqBody2
);
}
#createCursorRequest(entry, endpoint) {
if (endpoint.cursorPath === void 0) {
throw new 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,
CursorReqBody,
CursorReqBody2
);
}
#createRequest(url, reqBody, encoding, jsonFun, protobufFun) {
let bodyData;
let contentType;
if (encoding === "json") {
bodyData = writeJsonObject(reqBody, jsonFun);
contentType = "application/json";
} else if (encoding === "protobuf") {
bodyData = writeProtobufMessage(reqBody, protobufFun);
contentType = "application/x-protobuf";
} else {
throw impossible(encoding, "Impossible encoding");
}
const headers = new _Headers();
headers.set("content-type", contentType);
if (this.#jwt !== void 0) {
headers.set("authorization", `Bearer ${this.#jwt}`);
}
return new _Request(url.toString(), {
method: "POST",
headers,
body: bodyData,
});
}
};
function handlePipelineResponse(pipeline, respBody) {
if (respBody.results.length !== pipeline.length) {
throw new 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 ProtoError("Received unexpected type of response");
}
entry.responseCallback(result.response);
} else if (result.type === "error") {
entry.errorCallback(errorFromProto(result.error));
} else if (result.type === "none") {
throw new ProtoError("Received unrecognized type of StreamResult");
} else {
throw impossible(result, "Received impossible type of StreamResult");
}
}
}
async function decodePipelineResponse(resp, encoding) {
if (encoding === "json") {
const respJson = await resp.json();
return readJsonObject(respJson, PipelineRespBody);
} else if (encoding === "protobuf") {
const respData = await resp.arrayBuffer();
return readProtobufMessage(new Uint8Array(respData), PipelineRespBody2);
} else {
throw impossible(encoding, "Impossible encoding");
}
}
async function errorFromResponse(resp) {
const respType = resp.headers.get("content-type") ?? "text/plain";
if (respType === "application/json") {
const respBody = await resp.json();
if ("message" in respBody) {
return errorFromProto(respBody);
}
}
let message = `Server returned HTTP status ${resp.status}`;
if (respType === "text/plain") {
const respBody = (await resp.text()).trim();
if (respBody !== "") {
message += `: ${respBody}`;
}
}
if (resp.status === 404) {
message +=
". It seems that the libsql server is outdated, please try updating the database.";
}
return new HttpServerError(message, resp.status);
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/http/client.js
var 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",
},
*/
];
var fallbackEndpoint = {
versionPath: "v2",
pipelinePath: "v2/pipeline",
cursorPath: void 0,
version: 2,
encoding: "json",
};
var HttpClient = class extends Client {
#url;
#jwt;
#fetch;
#closed;
#streams;
/** @private */
_endpointPromise;
/** @private */
_endpoint;
/** @private */
constructor(url, jwt, customFetch, protocolVersion = 2) {
super();
this.#url = url;
this.#jwt = jwt;
this.#fetch = customFetch ?? _fetch;
this.#closed = void 0;
this.#streams = /* @__PURE__ */ 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 !== void 0) {
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 === void 0) {
throw new 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 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 !== void 0) {
throw new ClosedError("Client is closed", this.#closed);
}
const stream = new HttpStream(this, this.#url, this.#jwt, this.#fetch);
this.#streams.add(stream);
return stream;
}
/** @private */
_streamClosed(stream) {
this.#streams.delete(stream);
}
/** Close the client and all its streams. */
close() {
this.#setClosed(new ClientError("Client was manually closed"));
}
/** True if the client is closed. */
get closed() {
return this.#closed !== void 0;
}
#setClosed(error) {
if (this.#closed !== void 0) {
return;
}
this.#closed = error;
for (const stream of Array.from(this.#streams)) {
stream._setClosed(new ClosedError("Client was closed", error));
}
}
};
async function findEndpoint(customFetch, clientUrl) {
const fetch2 = customFetch;
for (const endpoint of checkEndpoints) {
const url = new URL(endpoint.versionPath, clientUrl);
const request = new _Request(url.toString(), { method: "GET" });
const response = await fetch2(request);
await response.arrayBuffer();
if (response.ok) {
return endpoint;
}
}
return fallbackEndpoint;
}
// ../../node_modules/.pnpm/@libsql+hrana-client@0.5.5/node_modules/@libsql/hrana-client/lib-esm/index.js
function openWs(url, jwt, protocolVersion = 2) {
if (typeof _WebSocket === "undefined") {
throw new WebSocketUnsupportedError(
"WebSockets are not supported in this environment"
);
}
var subprotocols = void 0;
if (protocolVersion == 3) {
subprotocols = Array.from(subprotocolsV3.keys());
} else {
subprotocols = Array.from(subprotocolsV2.keys());
}
const socket = new _WebSocket(url, subprotocols);
return new WsClient(socket, jwt);
}
function openHttp(url, jwt, customFetch, protocolVersion = 2) {
return new HttpClient(
url instanceof URL ? url : new URL(url),
jwt,
customFetch,
protocolVersion
);
}
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/hrana.js
var HranaTransaction = class {
#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, version3) {
this.#mode = mode;
this.#version = version3;
this.#started = void 0;
}
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 === void 0) {
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
const beginStep = batch.step();
const beginPromise = beginStep.run(transactionModeToBegin(this.#mode));
let lastStep = beginStep;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step().condition(BatchCond.ok(lastStep));
if (this.#version >= 3) {
stmtStep.condition(BatchCond.not(BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => void 0);
lastStep = stmtStep;
return rowsPromise;
});
this.#started = batch
.execute()
.then(() => beginPromise)
.then(() => void 0);
try {
await this.#started;
} catch (e) {
this.close();
throw e;
}
} else {
if (this.#version < 3) {
await this.#started;
} else {
}
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
let lastStep = void 0;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step();
if (lastStep !== void 0) {
stmtStep.condition(BatchCond.ok(lastStep));
}
if (this.#version >= 3) {
stmtStep.condition(BatchCond.not(BatchCond.isAutocommit(batch)));
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => void 0);
lastStep = stmtStep;
return rowsPromise;
});
await batch.execute();
}
const resultSets = [];
for (const rowsPromise of rowsPromises) {
const rows = await rowsPromise;
if (rows === void 0) {
throw new LibsqlError(
"Statement in a transaction was not executed, probably because the transaction has been rolled back",
"TRANSACTION_CLOSED"
);
}
resultSets.push(resultSetFromHrana(rows));
}
return resultSets;
} catch (e) {
throw mapHranaError(e);
}
}
async executeMultiple(sql2) {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError(
"Cannot execute statements because the transaction is closed",
"TRANSACTION_CLOSED"
);
}
try {
if (this.#started === void 0) {
this.#started = stream
.run(transactionModeToBegin(this.#mode))
.then(() => void 0);
try {
await this.#started;
} catch (e) {
this.close();
throw e;
}
} else {
await this.#started;
}
await stream.sequence(sql2);
} catch (e) {
throw mapHranaError(e);
}
}
async rollback() {
try {
const stream = this._getStream();
if (stream.closed) {
return;
}
if (this.#started !== void 0) {
} else {
return;
}
const promise = stream.run("ROLLBACK").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
} catch (e) {
throw mapHranaError(e);
} finally {
this.close();
}
}
async commit() {
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 !== void 0) {
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();
}
}
};
async function executeHranaBatch(mode, version3, batch, hranaStmts) {
const beginStep = batch.step();
const beginPromise = beginStep.run(transactionModeToBegin(mode));
let lastStep = beginStep;
const stmtPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step().condition(BatchCond.ok(lastStep));
if (version3 >= 3) {
stmtStep.condition(BatchCond.not(BatchCond.isAutocommit(batch)));
}
const stmtPromise = stmtStep.query(hranaStmt);
lastStep = stmtStep;
return stmtPromise;
});
const commitStep = batch.step().condition(BatchCond.ok(lastStep));
if (version3 >= 3) {
commitStep.condition(BatchCond.not(BatchCond.isAutocommit(batch)));
}
const commitPromise = commitStep.run("COMMIT");
const rollbackStep = batch
.step()
.condition(BatchCond.not(BatchCond.ok(commitStep)));
rollbackStep.run("ROLLBACK").catch((_) => void 0);
await batch.execute();
const resultSets = [];
await beginPromise;
for (const stmtPromise of stmtPromises) {
const hranaRows = await stmtPromise;
if (hranaRows === void 0) {
throw new LibsqlError(
"Statement in a batch was not executed, probably because the transaction has been rolled back",
"TRANSACTION_CLOSED"
);
}
resultSets.push(resultSetFromHrana(hranaRows));
}
await commitPromise;
return resultSets;
}
function stmtToHrana(stmt) {
if (typeof stmt === "string") {
return new Stmt(stmt);
}
const hranaStmt = new Stmt(stmt.sql);
if (Array.isArray(stmt.args)) {
hranaStmt.bindIndexes(stmt.args);
} else {
for (const [key, value] of Object.entries(stmt.args)) {
hranaStmt.bindName(key, value);
}
}
return hranaStmt;
}
function resultSetFromHrana(hranaRows) {
const columns = hranaRows.columnNames.map((c2) => c2 ?? "");
const columnTypes = hranaRows.columnDecltypes.map((c2) => c2 ?? "");
const rows = hranaRows.rows;
const rowsAffected = hranaRows.affectedRowCount;
const lastInsertRowid =
hranaRows.lastInsertRowid !== void 0 ? hranaRows.lastInsertRowid : void 0;
return new ResultSetImpl(
columns,
columnTypes,
rows,
rowsAffected,
lastInsertRowid
);
}
function mapHranaError(e) {
if (e instanceof ClientError) {
const code = mapHranaErrorCode(e);
return new LibsqlError(e.message, code, void 0, e);
}
return e;
}
function mapHranaErrorCode(e) {
if (e instanceof ResponseError && e.code !== void 0) {
return e.code;
} else if (e instanceof ProtoError) {
return "HRANA_PROTO_ERROR";
} else if (e instanceof ClosedError) {
return e.cause instanceof ClientError
? mapHranaErrorCode(e.cause)
: "HRANA_CLOSED_ERROR";
} else if (e instanceof WebSocketError) {
return "HRANA_WEBSOCKET_ERROR";
} else if (e instanceof HttpServerError) {
return "SERVER_ERROR";
} else if (e instanceof ProtocolVersionError) {
return "PROTOCOL_VERSION_ERROR";
} else if (e instanceof InternalError) {
return "INTERNAL_ERROR";
} else {
return "UNKNOWN";
}
}
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/sql_cache.js
var SqlCache = class {
#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 = /* @__PURE__ */ new Set();
for (const hranaStmt of hranaStmts) {
if (typeof hranaStmt.sql !== "string") {
continue;
}
const sqlText = hranaStmt.sql;
let sqlObj = this.#sqls.get(sqlText);
if (sqlObj === void 0) {
while (this.#sqls.size + 1 > this.capacity) {
const [evictSqlText, evictSqlObj] = this.#sqls.peekLru();
if (usedSqlObjs.has(evictSqlObj)) {
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 !== void 0) {
hranaStmt.sql = sqlObj;
usedSqlObjs.add(sqlObj);
}
}
}
};
var Lru = class {
// 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 = /* @__PURE__ */ new Map();
}
get(key) {
const value = this.#cache.get(key);
if (value !== void 0) {
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 void 0;
}
delete(key) {
this.#cache.delete(key);
}
get size() {
return this.#cache.size;
}
};
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/ws.js
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.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 = openWs(url, config.authToken);
} catch (e) {
if (e instanceof 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 WsClient2(client, url, config.authToken, config.intMode);
}
var maxConnAgeMillis = 60 * 1e3;
var sqlCacheCapacity = 100;
var WsClient2 = class {
#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;
/** @private */
constructor(client, url, authToken, intMode) {
this.#url = url;
this.#authToken = authToken;
this.#intMode = intMode;
this.#connState = this.#openConn(client);
this.#futureConnState = void 0;
this.closed = false;
this.protocol = "ws";
}
async execute(stmt) {
const streamState = await this.#openStream();
try {
const hranaStmt = stmtToHrana(stmt);
streamState.conn.sqlCache.apply([hranaStmt]);
const hranaRowsPromise = streamState.stream.query(hranaStmt);
streamState.stream.closeGracefully();
return resultSetFromHrana(await hranaRowsPromise);
} catch (e) {
throw mapHranaError(e);
} finally {
this._closeStream(streamState);
}
}
async batch(stmts, mode = "deferred") {
const streamState = await this.#openStream();
try {
const hranaStmts = stmts.map(stmtToHrana);
const version3 = await streamState.conn.client.getVersion();
streamState.conn.sqlCache.apply(hranaStmts);
const batch = streamState.stream.batch(version3 >= 3);
const resultsPromise = executeHranaBatch(
mode,
version3,
batch,
hranaStmts
);
return await resultsPromise;
} catch (e) {
throw mapHranaError(e);
} finally {
this._closeStream(streamState);
}
}
async transaction(mode = "write") {
const streamState = await this.#openStream();
try {
const version3 = await streamState.conn.client.getVersion();
return new WsTransaction(this, streamState, mode, version3);
} catch (e) {
this._closeStream(streamState);
throw mapHranaError(e);
}
}
async executeMultiple(sql2) {
const streamState = await this.#openStream();
try {
const promise = streamState.stream.sequence(sql2);
streamState.stream.closeGracefully();
await promise;
} catch (e) {
throw mapHranaError(e);
} finally {
this._closeStream(streamState);
}
}
sync() {
return Promise.resolve();
}
async #openStream() {
if (this.closed) {
throw new LibsqlError("The client is closed", "CLIENT_CLOSED");
}
const now = /* @__PURE__ */ new Date();
const ageMillis = now.valueOf() - this.#connState.openTime.valueOf();
if (ageMillis > maxConnAgeMillis && this.#futureConnState === void 0) {
const futureConnState = this.#openConn();
this.#futureConnState = futureConnState;
futureConnState.client.getVersion().then(
(_version) => {
if (this.#connState !== futureConnState) {
if (this.#connState.streamStates.size === 0) {
this.#connState.client.close();
} else {
}
}
this.#connState = futureConnState;
this.#futureConnState = void 0;
},
(_e) => {
this.#futureConnState = void 0;
}
);
}
if (this.#connState.client.closed) {
try {
if (this.#futureConnState !== void 0) {
this.#connState = this.#futureConnState;
} else {
this.#connState = this.#openConn();
}
} catch (e) {
throw mapHranaError(e);
}
}
const connState = this.#connState;
try {
if (connState.useSqlCache === void 0) {
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 ??= openWs(this.#url, this.#authToken);
return {
client,
useSqlCache: void 0,
sqlCache: new SqlCache(client, 0),
openTime: /* @__PURE__ */ new Date(),
streamStates: /* @__PURE__ */ new Set(),
};
} catch (e) {
throw mapHranaError(e);
}
}
_closeStream(streamState) {
streamState.stream.close();
const connState = streamState.conn;
connState.streamStates.delete(streamState);
if (connState.streamStates.size === 0 && connState !== this.#connState) {
connState.client.close();
}
}
close() {
this.#connState.client.close();
this.closed = true;
}
};
var WsTransaction = class extends HranaTransaction {
#client;
#streamState;
/** @private */
constructor(client, state, mode, version3) {
super(mode, version3);
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;
}
};
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/http.js
function _createClient2(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.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 HttpClient2(url, config.authToken, config.intMode, config.fetch);
}
var sqlCacheCapacity2 = 30;
var HttpClient2 = class {
#client;
protocol;
/** @private */
constructor(url, authToken, intMode, customFetch) {
this.#client = openHttp(url, authToken, customFetch);
this.#client.intMode = intMode;
this.protocol = "http";
}
async execute(stmt) {
try {
const hranaStmt = stmtToHrana(stmt);
let rowsPromise;
const stream = this.#client.openStream();
try {
rowsPromise = stream.query(hranaStmt);
} finally {
stream.closeGracefully();
}
return resultSetFromHrana(await rowsPromise);
} catch (e) {
throw mapHranaError(e);
}
}
async batch(stmts, mode = "deferred") {
try {
const hranaStmts = stmts.map(stmtToHrana);
const version3 = await this.#client.getVersion();
let resultsPromise;
const stream = this.#client.openStream();
try {
const sqlCache = new SqlCache(stream, sqlCacheCapacity2);
sqlCache.apply(hranaStmts);
const batch = stream.batch(false);
resultsPromise = executeHranaBatch(mode, version3, batch, hranaStmts);
} finally {
stream.closeGracefully();
}
return await resultsPromise;
} catch (e) {
throw mapHranaError(e);
}
}
async transaction(mode = "write") {
try {
const version3 = await this.#client.getVersion();
return new HttpTransaction(this.#client.openStream(), mode, version3);
} catch (e) {
throw mapHranaError(e);
}
}
async executeMultiple(sql2) {
try {
let promise;
const stream = this.#client.openStream();
try {
promise = stream.sequence(sql2);
} 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();
}
get closed() {
return this.#client.closed;
}
};
var HttpTransaction = class extends HranaTransaction {
#stream;
#sqlCache;
/** @private */
constructor(stream, mode, version3) {
super(mode, version3);
this.#stream = stream;
this.#sqlCache = new SqlCache(stream, sqlCacheCapacity2);
}
/** @private */
_getStream() {
return this.#stream;
}
/** @private */
_getSqlCache() {
return this.#sqlCache;
}
close() {
this.#stream.close();
}
get closed() {
return this.#stream.closed;
}
};
// ../../node_modules/.pnpm/@libsql+client@0.4.0-pre.7/node_modules/@libsql/client/lib-esm/web.js
function createClient(config) {
return _createClient3(expandConfig(config, true));
}
function _createClient3(config) {
if (config.scheme === "ws" || config.scheme === "wss") {
return _createClient(config);
} else if (config.scheme === "http" || config.scheme === "https") {
return _createClient2(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"
);
}
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/libsql/session.js
var _a104;
var _LibSQLSession = class extends SQLiteSession {
constructor(client, dialect, schema, options, tx) {
super(dialect);
this.client = client;
this.schema = schema;
this.options = options;
this.tx = tx;
this.logger = options.logger ?? new NoopLogger();
}
logger;
prepareQuery(query, fields, executeMethod, customResultMapper) {
return new LibSQLPreparedQuery(
this.client,
query,
this.logger,
fields,
this.tx,
executeMethod,
customResultMapper
);
}
async batch(queries) {
const preparedQueries = [];
const builtQueries = [];
for (const query of queries) {
const preparedQuery = query.prepare();
const builtQuery = preparedQuery.getQuery();
preparedQueries.push(preparedQuery);
builtQueries.push({ sql: builtQuery.sql, args: builtQuery.params });
}
const batchResults = await this.client.batch(builtQueries);
return batchResults.map((result, i) =>
preparedQueries[i].mapResult(result, true)
);
}
async transaction(transaction, _config) {
const libsqlTx = await this.client.transaction();
const session = new _LibSQLSession(
this.client,
this.dialect,
this.schema,
this.options,
libsqlTx
);
const tx = new LibSQLTransaction(
"async",
this.dialect,
session,
this.schema
);
try {
const result = await transaction(tx);
await libsqlTx.commit();
return result;
} catch (err) {
await libsqlTx.rollback();
throw err;
}
}
extractRawAllValueFromBatchResult(result) {
return result.rows;
}
extractRawGetValueFromBatchResult(result) {
return result.rows[0];
}
extractRawValuesValueFromBatchResult(result) {
return result.rows;
}
};
var LibSQLSession = _LibSQLSession;
_a104 = entityKind;
__publicField(LibSQLSession, _a104, "LibSQLSession");
var _a105;
var _LibSQLTransaction = class extends SQLiteTransaction {
async transaction(transaction) {
const savepointName = `sp${this.nestedIndex}`;
const tx = new _LibSQLTransaction(
"async",
this.dialect,
this.session,
this.schema,
this.nestedIndex + 1
);
await this.session.run(sql.raw(`savepoint ${savepointName}`));
try {
const result = await transaction(tx);
await this.session.run(sql.raw(`release savepoint ${savepointName}`));
return result;
} catch (err) {
await this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));
throw err;
}
}
};
var LibSQLTransaction = _LibSQLTransaction;
_a105 = entityKind;
__publicField(LibSQLTransaction, _a105, "LibSQLTransaction");
var _a106;
var LibSQLPreparedQuery = class extends SQLitePreparedQuery {
constructor(
client,
query,
logger,
fields,
tx,
executeMethod,
customResultMapper
) {
super("async", executeMethod, query);
this.client = client;
this.logger = logger;
this.fields = fields;
this.tx = tx;
this.customResultMapper = customResultMapper;
this.customResultMapper = customResultMapper;
this.fields = fields;
}
run(placeholderValues) {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
const stmt = { sql: this.query.sql, args: params };
return this.tx ? this.tx.execute(stmt) : this.client.execute(stmt);
}
async all(placeholderValues) {
const { fields, logger, query, tx, client, customResultMapper } = this;
if (!fields && !customResultMapper) {
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
const stmt = { sql: query.sql, args: params };
return (tx ? tx.execute(stmt) : client.execute(stmt)).then(
({ rows: rows2 }) => this.mapAllResult(rows2)
);
}
const rows = await this.values(placeholderValues);
return this.mapAllResult(rows);
}
mapAllResult(rows, isFromBatch) {
if (isFromBatch) {
rows = rows.rows;
}
if (!this.fields && !this.customResultMapper) {
return rows.map((row) => normalizeRow(row));
}
if (this.customResultMapper) {
return this.customResultMapper(rows, normalizeFieldValue);
}
return rows.map((row) => {
return mapResultRow(
this.fields,
Array.prototype.slice.call(row).map((v) => normalizeFieldValue(v)),
this.joinsNotNullableMap
);
});
}
async get(placeholderValues) {
const { fields, logger, query, tx, client, customResultMapper } = this;
if (!fields && !customResultMapper) {
const params = fillPlaceholders(query.params, placeholderValues ?? {});
logger.logQuery(query.sql, params);
const stmt = { sql: query.sql, args: params };
return (tx ? tx.execute(stmt) : client.execute(stmt)).then(
({ rows: rows2 }) => this.mapGetResult(rows2)
);
}
const rows = await this.values(placeholderValues);
return this.mapGetResult(rows);
}
mapGetResult(rows, isFromBatch) {
if (isFromBatch) {
rows = rows.rows;
}
const row = rows[0];
if (!this.fields && !this.customResultMapper) {
return normalizeRow(row);
}
if (!row) {
return void 0;
}
if (this.customResultMapper) {
return this.customResultMapper(rows, normalizeFieldValue);
}
return mapResultRow(
this.fields,
Array.prototype.slice.call(row).map((v) => normalizeFieldValue(v)),
this.joinsNotNullableMap
);
}
values(placeholderValues) {
const params = fillPlaceholders(this.query.params, placeholderValues ?? {});
this.logger.logQuery(this.query.sql, params);
const stmt = { sql: this.query.sql, args: params };
return (this.tx ? this.tx.execute(stmt) : this.client.execute(stmt)).then(
({ rows }) => rows
);
}
};
_a106 = entityKind;
__publicField(LibSQLPreparedQuery, _a106, "LibSQLPreparedQuery");
function normalizeRow(obj) {
return Object.keys(obj).reduce((acc, key) => {
if (Object.prototype.propertyIsEnumerable.call(obj, key)) {
acc[key] = obj[key];
}
return acc;
}, {});
}
function normalizeFieldValue(value) {
if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
if (typeof Buffer !== "undefined") {
if (!(value instanceof Buffer)) {
return Buffer.from(value);
}
return value;
}
if (typeof TextDecoder !== "undefined") {
return new TextDecoder().decode(value);
}
throw new Error(
"TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill."
);
}
return value;
}
// ../../node_modules/.pnpm/drizzle-orm@0.29.3_@libsql+client@0.4.0-pre.7_react@18.2.0/node_modules/drizzle-orm/libsql/driver.js
var _a107;
var LibSQLDatabase = class extends BaseSQLiteDatabase {
async batch(batch) {
return this.session.batch(batch);
}
};
_a107 = entityKind;
__publicField(LibSQLDatabase, _a107, "LibSQLDatabase");
function drizzle(client, config = {}) {
const dialect = new SQLiteAsyncDialect();
let logger;
if (config.logger === true) {
logger = new DefaultLogger();
} else if (config.logger !== false) {
logger = config.logger;
}
let schema;
if (config.schema) {
const tablesConfig = extractTablesRelationalConfig(
config.schema,
createTableRelationsHelpers
);
schema = {
fullSchema: config.schema,
schema: tablesConfig.tables,
tableNamesMap: tablesConfig.tableNamesMap,
};
}
const session = new LibSQLSession(
client,
dialect,
schema,
{ logger },
void 0
);
return new LibSQLDatabase("async", dialect, session, schema);
}
// ../../packages/database/db.ts
function getWebTursoDB(url, authToken) {
return drizzle(createClient({ url, authToken }));
}
// ../../node_modules/.pnpm/nanoid@5.0.4/node_modules/nanoid/non-secure/index.js
var urlAlphabet =
"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
var nanoid = (size = 21) => {
let id = "";
let i = size;
while (i--) {
id += urlAlphabet[(Math.random() * 64) | 0];
}
return id;
};
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/decode-strings.js
var textEncoder = new TextEncoder();
var decoders = /* @__PURE__ */ new Map();
var base64Chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64Lookup = new Uint8Array(256);
for (i = 0; i < base64Chars.length; i++) {
base64Lookup[base64Chars.charCodeAt(i)] = i;
}
var i;
function decodeBase64(base64) {
let bufferLength = Math.ceil(base64.length / 4) * 3;
const len = base64.length;
let p2 = 0;
if (base64.length % 4 === 3) {
bufferLength--;
} else if (base64.length % 4 === 2) {
bufferLength -= 2;
} else if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
const arrayBuffer = new ArrayBuffer(bufferLength);
const bytes = new Uint8Array(arrayBuffer);
for (let i = 0; i < len; i += 4) {
let encoded1 = base64Lookup[base64.charCodeAt(i)];
let encoded2 = base64Lookup[base64.charCodeAt(i + 1)];
let encoded3 = base64Lookup[base64.charCodeAt(i + 2)];
let encoded4 = base64Lookup[base64.charCodeAt(i + 3)];
bytes[p2++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p2++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p2++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arrayBuffer;
}
function getDecoder(charset) {
charset = charset || "utf8";
if (decoders.has(charset)) {
return decoders.get(charset);
}
let decoder;
try {
decoder = new TextDecoder(charset);
} catch (err) {
if (charset === "utf8") {
throw err;
}
return getDecoder();
}
decoders.set(charset, decoder);
return decoder;
}
async function blobToArrayBuffer(blob) {
if ("arrayBuffer" in blob) {
return await blob.arrayBuffer();
}
const fr = new FileReader();
return new Promise((resolve, reject) => {
fr.onload = function (e) {
resolve(e.target.result);
};
fr.onerror = function (e) {
reject(fr.error);
};
fr.readAsArrayBuffer(blob);
});
}
function getHex(c2) {
if (
(c2 >= 48 && c2 <= 57) ||
(c2 >= 97 && c2 <= 102) ||
(c2 >= 65 && c2 <= 70)
) {
return String.fromCharCode(c2);
}
return false;
}
function decodeWord(charset, encoding, str) {
let splitPos = charset.indexOf("*");
if (splitPos >= 0) {
charset = charset.substr(0, splitPos);
}
encoding = encoding.toUpperCase();
let byteStr;
if (encoding === "Q") {
str = str.replace(/=\s+([0-9a-fA-F])/g, "=$1").replace(/[_\s]/g, " ");
let buf = textEncoder.encode(str);
let encodedBytes = [];
for (let i = 0, len = buf.length; i < len; i++) {
let c2 = buf[i];
if (i <= len - 2 && c2 === 61) {
let c1 = getHex(buf[i + 1]);
let c22 = getHex(buf[i + 2]);
if (c1 && c22) {
let c3 = parseInt(c1 + c22, 16);
encodedBytes.push(c3);
i += 2;
continue;
}
}
encodedBytes.push(c2);
}
byteStr = new ArrayBuffer(encodedBytes.length);
let dataView = new DataView(byteStr);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, encodedBytes[i]);
}
} else if (encoding === "B") {
byteStr = decodeBase64(str.replace(/[^a-zA-Z0-9\+\/=]+/g, ""));
} else {
byteStr = textEncoder.encode(str);
}
return getDecoder(charset).decode(byteStr);
}
function decodeWords(str) {
return (str || "")
.toString()
.replace(
/(=\?([^?]+)\?[Bb]\?[^?]*\?=)\s*(?==\?([^?]+)\?[Bb]\?[^?]*\?=)/g,
(match, left, chLeft, chRight) => {
if (chLeft === chRight) {
return left + "__\0JOIN\0__";
}
return match;
}
)
.replace(
/(=\?([^?]+)\?[Qq]\?[^?]*\?=)\s*(?==\?([^?]+)\?[Qq]\?[^?]*\?=)/g,
(match, left, chLeft, chRight) => {
if (chLeft === chRight) {
return left + "__\0JOIN\0__";
}
return match;
}
)
.replace(/(\?=)?__\x00JOIN\x00__(=\?([^?]+)\?[QqBb]\?)?/g, "")
.replace(
/(=\?[^?]+\?[QqBb]\?[^?]*\?=)\s+(?==\?[^?]+\?[QqBb]\?[^?]*\?=)/g,
"$1"
)
.replace(
/=\?([\w_\-*]+)\?([QqBb])\?([^?]*)\?=/g,
(m2, charset, encoding, text2) => decodeWord(charset, encoding, text2)
);
}
function decodeURIComponentWithCharset(encodedStr, charset) {
charset = charset || "utf-8";
let encodedBytes = [];
for (let i = 0; i < encodedStr.length; i++) {
let c2 = encodedStr.charAt(i);
if (c2 === "%" && /^[a-f0-9]{2}/i.test(encodedStr.substr(i + 1, 2))) {
let byte = encodedStr.substr(i + 1, 2);
i += 2;
encodedBytes.push(parseInt(byte, 16));
} else if (c2.charCodeAt(0) > 126) {
c2 = textEncoder.encode(c2);
for (let j = 0; j < c2.length; j++) {
encodedBytes.push(c2[j]);
}
} else {
encodedBytes.push(c2.charCodeAt(0));
}
}
const byteStr = new ArrayBuffer(encodedBytes.length);
const dataView = new DataView(byteStr);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, encodedBytes[i]);
}
return getDecoder(charset).decode(byteStr);
}
function decodeParameterValueContinuations(header) {
let paramKeys = /* @__PURE__ */ new Map();
Object.keys(header.params).forEach((key) => {
let match = key.match(/\*((\d+)\*?)?$/);
if (!match) {
return;
}
let actualKey = key.substr(0, match.index).toLowerCase();
let nr = Number(match[2]) || 0;
let paramVal;
if (!paramKeys.has(actualKey)) {
paramVal = {
charset: false,
values: [],
};
paramKeys.set(actualKey, paramVal);
} else {
paramVal = paramKeys.get(actualKey);
}
let value = header.params[key];
if (
nr === 0 &&
match[0].charAt(match[0].length - 1) === "*" &&
(match = value.match(/^([^']*)'[^']*'(.*)$/))
) {
paramVal.charset = match[1] || "utf-8";
value = match[2];
}
paramVal.values.push({ nr, value });
delete header.params[key];
});
paramKeys.forEach((paramVal, key) => {
header.params[key] = decodeURIComponentWithCharset(
paramVal.values
.sort((a, b) => a.nr - b.nr)
.map((a) => a.value)
.join(""),
paramVal.charset
);
});
}
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/pass-through-decoder.js
var PassThroughDecoder = class {
constructor() {
this.chunks = [];
}
update(line) {
this.chunks.push(line);
this.chunks.push("\n");
}
finalize() {
return blobToArrayBuffer(
new Blob(this.chunks, { type: "application/octet-stream" })
);
}
};
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/base64-decoder.js
var Base64Decoder = class {
constructor(opts) {
opts = opts || {};
this.decoder = opts.decoder || new TextDecoder();
this.maxChunkSize = 100 * 1024;
this.chunks = [];
this.remainder = "";
}
update(buffer) {
let str = this.decoder.decode(buffer);
if (/[^a-zA-Z0-9+\/]/.test(str)) {
str = str.replace(/[^a-zA-Z0-9+\/]+/g, "");
}
this.remainder += str;
if (this.remainder.length >= this.maxChunkSize) {
let allowedBytes = Math.floor(this.remainder.length / 4) * 4;
let base64Str;
if (allowedBytes === this.remainder.length) {
base64Str = this.remainder;
this.remainder = "";
} else {
base64Str = this.remainder.substr(0, allowedBytes);
this.remainder = this.remainder.substr(allowedBytes);
}
if (base64Str.length) {
this.chunks.push(decodeBase64(base64Str));
}
}
}
finalize() {
if (this.remainder && !/^=+$/.test(this.remainder)) {
this.chunks.push(decodeBase64(this.remainder));
}
return blobToArrayBuffer(
new Blob(this.chunks, { type: "application/octet-stream" })
);
}
};
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/qp-decoder.js
var QPDecoder = class {
constructor(opts) {
opts = opts || {};
this.decoder = opts.decoder || new TextDecoder();
this.maxChunkSize = 100 * 1024;
this.remainder = "";
this.chunks = [];
}
decodeQPBytes(encodedBytes) {
let buf = new ArrayBuffer(encodedBytes.length);
let dataView = new DataView(buf);
for (let i = 0, len = encodedBytes.length; i < len; i++) {
dataView.setUint8(i, parseInt(encodedBytes[i], 16));
}
return buf;
}
decodeChunks(str) {
str = str.replace(/=\r?\n/g, "");
let list = str.split(/(?==)/);
let encodedBytes = [];
for (let part of list) {
if (part.charAt(0) !== "=") {
if (encodedBytes.length) {
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
}
this.chunks.push(part);
continue;
}
if (part.length === 3) {
encodedBytes.push(part.substr(1));
continue;
}
if (part.length > 3) {
encodedBytes.push(part.substr(1, 2));
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
part = part.substr(3);
this.chunks.push(part);
}
}
if (encodedBytes.length) {
this.chunks.push(this.decodeQPBytes(encodedBytes));
encodedBytes = [];
}
}
update(buffer) {
let str = this.decoder.decode(buffer) + "\n";
str = this.remainder + str;
if (str.length < this.maxChunkSize) {
this.remainder = str;
return;
}
this.remainder = "";
let partialEnding = str.match(/=[a-fA-F0-9]?$/);
if (partialEnding) {
if (partialEnding.index === 0) {
this.remainder = str;
return;
}
this.remainder = str.substr(partialEnding.index);
str = str.substr(0, partialEnding.index);
}
this.decodeChunks(str);
}
finalize() {
if (this.remainder.length) {
this.decodeChunks(this.remainder);
this.remainder = "";
}
return blobToArrayBuffer(
new Blob(this.chunks, { type: "application/octet-stream" })
);
}
};
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/mime-node.js
var MimeNode = class {
constructor(opts) {
opts = opts || {};
this.postalMime = opts.postalMime;
this.root = !!opts.parentNode;
this.childNodes = [];
if (opts.parentNode) {
opts.parentNode.childNodes.push(this);
}
this.state = "header";
this.headerLines = [];
this.decoders = /* @__PURE__ */ new Map();
this.contentType = {
value: "text/plain",
default: true,
};
this.contentTransferEncoding = {
value: "8bit",
};
this.contentDisposition = {
value: "",
};
this.headers = [];
this.contentDecoder = false;
}
setupContentDecoder(transferEncoding) {
if (/base64/i.test(transferEncoding)) {
this.contentDecoder = new Base64Decoder();
} else if (/quoted-printable/i.test(transferEncoding)) {
this.contentDecoder = new QPDecoder({
decoder: getDecoder(this.contentType.parsed.params.charset),
});
} else {
this.contentDecoder = new PassThroughDecoder();
}
}
async finalize() {
if (this.state === "finished") {
return;
}
if (this.state === "header") {
this.processHeaders();
}
let boundaries = this.postalMime.boundaries;
for (let i = boundaries.length - 1; i >= 0; i--) {
let boundary = boundaries[i];
if (boundary.node === this) {
boundaries.splice(i, 1);
break;
}
}
await this.finalizeChildNodes();
this.content = this.contentDecoder
? await this.contentDecoder.finalize()
: null;
this.state = "finished";
}
async finalizeChildNodes() {
for (let childNode of this.childNodes) {
await childNode.finalize();
}
}
parseStructuredHeader(str) {
let response = {
value: false,
params: {},
};
let key = false;
let value = "";
let stage = "value";
let quote = false;
let escaped = false;
let chr;
for (let i = 0, len = str.length; i < len; i++) {
chr = str.charAt(i);
switch (stage) {
case "key":
if (chr === "=") {
key = value.trim().toLowerCase();
stage = "value";
value = "";
break;
}
value += chr;
break;
case "value":
if (escaped) {
value += chr;
} else if (chr === "\\") {
escaped = true;
continue;
} else if (quote && chr === quote) {
quote = false;
} else if (!quote && chr === '"') {
quote = chr;
} else if (!quote && chr === ";") {
if (key === false) {
response.value = value.trim();
} else {
response.params[key] = value.trim();
}
stage = "key";
value = "";
} else {
value += chr;
}
escaped = false;
break;
}
}
value = value.trim();
if (stage === "value") {
if (key === false) {
response.value = value;
} else {
response.params[key] = value;
}
} else if (value) {
response.params[value.toLowerCase()] = "";
}
if (response.value) {
response.value = response.value.toLowerCase();
}
decodeParameterValueContinuations(response);
return response;
}
decodeFlowedText(str, delSp) {
return str
.split(/\r?\n/)
.reduce((previousValue, currentValue) => {
if (/ $/.test(previousValue) && !/(^|\n)-- $/.test(previousValue)) {
if (delSp) {
return previousValue.slice(0, -1) + currentValue;
} else {
return previousValue + currentValue;
}
} else {
return previousValue + "\n" + currentValue;
}
})
.replace(/^ /gm, "");
}
getTextContent() {
if (!this.content) {
return "";
}
let str = getDecoder(this.contentType.parsed.params.charset).decode(
this.content
);
if (/^flowed$/i.test(this.contentType.parsed.params.format)) {
str = this.decodeFlowedText(
str,
/^yes$/i.test(this.contentType.parsed.params.delsp)
);
}
return str;
}
processHeaders() {
for (let i = this.headerLines.length - 1; i >= 0; i--) {
let line = this.headerLines[i];
if (i && /^\s/.test(line)) {
this.headerLines[i - 1] += "\n" + line;
this.headerLines.splice(i, 1);
} else {
line = line.replace(/\s+/g, " ");
let sep = line.indexOf(":");
let key = sep < 0 ? line.trim() : line.substr(0, sep).trim();
let value = sep < 0 ? "" : line.substr(sep + 1).trim();
this.headers.push({ key: key.toLowerCase(), originalKey: key, value });
switch (key.toLowerCase()) {
case "content-type":
if (this.contentType.default) {
this.contentType = { value, parsed: {} };
}
break;
case "content-transfer-encoding":
this.contentTransferEncoding = { value, parsed: {} };
break;
case "content-disposition":
this.contentDisposition = { value, parsed: {} };
break;
case "content-id":
this.contentId = value;
break;
}
}
}
this.contentType.parsed = this.parseStructuredHeader(
this.contentType.value
);
this.contentType.multipart = /^multipart\//i.test(
this.contentType.parsed.value
)
? this.contentType.parsed.value.substr(
this.contentType.parsed.value.indexOf("/") + 1
)
: false;
if (this.contentType.multipart && this.contentType.parsed.params.boundary) {
this.postalMime.boundaries.push({
value: textEncoder.encode(this.contentType.parsed.params.boundary),
node: this,
});
}
this.contentDisposition.parsed = this.parseStructuredHeader(
this.contentDisposition.value
);
this.contentTransferEncoding.encoding = this.contentTransferEncoding.value
.toLowerCase()
.split(/[^\w-]/)
.shift();
this.setupContentDecoder(this.contentTransferEncoding.encoding);
}
feed(line) {
switch (this.state) {
case "header":
if (!line.length) {
this.state = "body";
return this.processHeaders();
}
this.headerLines.push(getDecoder().decode(line));
break;
case "body": {
this.contentDecoder.update(line);
}
}
}
};
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/html-entities.js
var htmlEntities = {
"&AElig": "\xC6",
"&AElig;": "\xC6",
"&AMP": "&",
"&AMP;": "&",
"&Aacute": "\xC1",
"&Aacute;": "\xC1",
"&Abreve;": "\u0102",
"&Acirc": "\xC2",
"&Acirc;": "\xC2",
"&Acy;": "\u0410",
"&Afr;": "\u{1D504}",
"&Agrave": "\xC0",
"&Agrave;": "\xC0",
"&Alpha;": "\u0391",
"&Amacr;": "\u0100",
"&And;": "\u2A53",
"&Aogon;": "\u0104",
"&Aopf;": "\u{1D538}",
"&ApplyFunction;": "\u2061",
"&Aring": "\xC5",
"&Aring;": "\xC5",
"&Ascr;": "\u{1D49C}",
"&Assign;": "\u2254",
"&Atilde": "\xC3",
"&Atilde;": "\xC3",
"&Auml": "\xC4",
"&Auml;": "\xC4",
"&Backslash;": "\u2216",
"&Barv;": "\u2AE7",
"&Barwed;": "\u2306",
"&Bcy;": "\u0411",
"&Because;": "\u2235",
"&Bernoullis;": "\u212C",
"&Beta;": "\u0392",
"&Bfr;": "\u{1D505}",
"&Bopf;": "\u{1D539}",
"&Breve;": "\u02D8",
"&Bscr;": "\u212C",
"&Bumpeq;": "\u224E",
"&CHcy;": "\u0427",
"&COPY": "\xA9",
"&COPY;": "\xA9",
"&Cacute;": "\u0106",
"&Cap;": "\u22D2",
"&CapitalDifferentialD;": "\u2145",
"&Cayleys;": "\u212D",
"&Ccaron;": "\u010C",
"&Ccedil": "\xC7",
"&Ccedil;": "\xC7",
"&Ccirc;": "\u0108",
"&Cconint;": "\u2230",
"&Cdot;": "\u010A",
"&Cedilla;": "\xB8",
"&CenterDot;": "\xB7",
"&Cfr;": "\u212D",
"&Chi;": "\u03A7",
"&CircleDot;": "\u2299",
"&CircleMinus;": "\u2296",
"&CirclePlus;": "\u2295",
"&CircleTimes;": "\u2297",
"&ClockwiseContourIntegral;": "\u2232",
"&CloseCurlyDoubleQuote;": "\u201D",
"&CloseCurlyQuote;": "\u2019",
"&Colon;": "\u2237",
"&Colone;": "\u2A74",
"&Congruent;": "\u2261",
"&Conint;": "\u222F",
"&ContourIntegral;": "\u222E",
"&Copf;": "\u2102",
"&Coproduct;": "\u2210",
"&CounterClockwiseContourIntegral;": "\u2233",
"&Cross;": "\u2A2F",
"&Cscr;": "\u{1D49E}",
"&Cup;": "\u22D3",
"&CupCap;": "\u224D",
"&DD;": "\u2145",
"&DDotrahd;": "\u2911",
"&DJcy;": "\u0402",
"&DScy;": "\u0405",
"&DZcy;": "\u040F",
"&Dagger;": "\u2021",
"&Darr;": "\u21A1",
"&Dashv;": "\u2AE4",
"&Dcaron;": "\u010E",
"&Dcy;": "\u0414",
"&Del;": "\u2207",
"&Delta;": "\u0394",
"&Dfr;": "\u{1D507}",
"&DiacriticalAcute;": "\xB4",
"&DiacriticalDot;": "\u02D9",
"&DiacriticalDoubleAcute;": "\u02DD",
"&DiacriticalGrave;": "`",
"&DiacriticalTilde;": "\u02DC",
"&Diamond;": "\u22C4",
"&DifferentialD;": "\u2146",
"&Dopf;": "\u{1D53B}",
"&Dot;": "\xA8",
"&DotDot;": "\u20DC",
"&DotEqual;": "\u2250",
"&DoubleContourIntegral;": "\u222F",
"&DoubleDot;": "\xA8",
"&DoubleDownArrow;": "\u21D3",
"&DoubleLeftArrow;": "\u21D0",
"&DoubleLeftRightArrow;": "\u21D4",
"&DoubleLeftTee;": "\u2AE4",
"&DoubleLongLeftArrow;": "\u27F8",
"&DoubleLongLeftRightArrow;": "\u27FA",
"&DoubleLongRightArrow;": "\u27F9",
"&DoubleRightArrow;": "\u21D2",
"&DoubleRightTee;": "\u22A8",
"&DoubleUpArrow;": "\u21D1",
"&DoubleUpDownArrow;": "\u21D5",
"&DoubleVerticalBar;": "\u2225",
"&DownArrow;": "\u2193",
"&DownArrowBar;": "\u2913",
"&DownArrowUpArrow;": "\u21F5",
"&DownBreve;": "\u0311",
"&DownLeftRightVector;": "\u2950",
"&DownLeftTeeVector;": "\u295E",
"&DownLeftVector;": "\u21BD",
"&DownLeftVectorBar;": "\u2956",
"&DownRightTeeVector;": "\u295F",
"&DownRightVector;": "\u21C1",
"&DownRightVectorBar;": "\u2957",
"&DownTee;": "\u22A4",
"&DownTeeArrow;": "\u21A7",
"&Downarrow;": "\u21D3",
"&Dscr;": "\u{1D49F}",
"&Dstrok;": "\u0110",
"&ENG;": "\u014A",
"&ETH": "\xD0",
"&ETH;": "\xD0",
"&Eacute": "\xC9",
"&Eacute;": "\xC9",
"&Ecaron;": "\u011A",
"&Ecirc": "\xCA",
"&Ecirc;": "\xCA",
"&Ecy;": "\u042D",
"&Edot;": "\u0116",
"&Efr;": "\u{1D508}",
"&Egrave": "\xC8",
"&Egrave;": "\xC8",
"&Element;": "\u2208",
"&Emacr;": "\u0112",
"&EmptySmallSquare;": "\u25FB",
"&EmptyVerySmallSquare;": "\u25AB",
"&Eogon;": "\u0118",
"&Eopf;": "\u{1D53C}",
"&Epsilon;": "\u0395",
"&Equal;": "\u2A75",
"&EqualTilde;": "\u2242",
"&Equilibrium;": "\u21CC",
"&Escr;": "\u2130",
"&Esim;": "\u2A73",
"&Eta;": "\u0397",
"&Euml": "\xCB",
"&Euml;": "\xCB",
"&Exists;": "\u2203",
"&ExponentialE;": "\u2147",
"&Fcy;": "\u0424",
"&Ffr;": "\u{1D509}",
"&FilledSmallSquare;": "\u25FC",
"&FilledVerySmallSquare;": "\u25AA",
"&Fopf;": "\u{1D53D}",
"&ForAll;": "\u2200",
"&Fouriertrf;": "\u2131",
"&Fscr;": "\u2131",
"&GJcy;": "\u0403",
"&GT": ">",
"&GT;": ">",
"&Gamma;": "\u0393",
"&Gammad;": "\u03DC",
"&Gbreve;": "\u011E",
"&Gcedil;": "\u0122",
"&Gcirc;": "\u011C",
"&Gcy;": "\u0413",
"&Gdot;": "\u0120",
"&Gfr;": "\u{1D50A}",
"&Gg;": "\u22D9",
"&Gopf;": "\u{1D53E}",
"&GreaterEqual;": "\u2265",
"&GreaterEqualLess;": "\u22DB",
"&GreaterFullEqual;": "\u2267",
"&GreaterGreater;": "\u2AA2",
"&GreaterLess;": "\u2277",
"&GreaterSlantEqual;": "\u2A7E",
"&GreaterTilde;": "\u2273",
"&Gscr;": "\u{1D4A2}",
"&Gt;": "\u226B",
"&HARDcy;": "\u042A",
"&Hacek;": "\u02C7",
"&Hat;": "^",
"&Hcirc;": "\u0124",
"&Hfr;": "\u210C",
"&HilbertSpace;": "\u210B",
"&Hopf;": "\u210D",
"&HorizontalLine;": "\u2500",
"&Hscr;": "\u210B",
"&Hstrok;": "\u0126",
"&HumpDownHump;": "\u224E",
"&HumpEqual;": "\u224F",
"&IEcy;": "\u0415",
"&IJlig;": "\u0132",
"&IOcy;": "\u0401",
"&Iacute": "\xCD",
"&Iacute;": "\xCD",
"&Icirc": "\xCE",
"&Icirc;": "\xCE",
"&Icy;": "\u0418",
"&Idot;": "\u0130",
"&Ifr;": "\u2111",
"&Igrave": "\xCC",
"&Igrave;": "\xCC",
"&Im;": "\u2111",
"&Imacr;": "\u012A",
"&ImaginaryI;": "\u2148",
"&Implies;": "\u21D2",
"&Int;": "\u222C",
"&Integral;": "\u222B",
"&Intersection;": "\u22C2",
"&InvisibleComma;": "\u2063",
"&InvisibleTimes;": "\u2062",
"&Iogon;": "\u012E",
"&Iopf;": "\u{1D540}",
"&Iota;": "\u0399",
"&Iscr;": "\u2110",
"&Itilde;": "\u0128",
"&Iukcy;": "\u0406",
"&Iuml": "\xCF",
"&Iuml;": "\xCF",
"&Jcirc;": "\u0134",
"&Jcy;": "\u0419",
"&Jfr;": "\u{1D50D}",
"&Jopf;": "\u{1D541}",
"&Jscr;": "\u{1D4A5}",
"&Jsercy;": "\u0408",
"&Jukcy;": "\u0404",
"&KHcy;": "\u0425",
"&KJcy;": "\u040C",
"&Kappa;": "\u039A",
"&Kcedil;": "\u0136",
"&Kcy;": "\u041A",
"&Kfr;": "\u{1D50E}",
"&Kopf;": "\u{1D542}",
"&Kscr;": "\u{1D4A6}",
"&LJcy;": "\u0409",
"&LT": "<",
"&LT;": "<",
"&Lacute;": "\u0139",
"&Lambda;": "\u039B",
"&Lang;": "\u27EA",
"&Laplacetrf;": "\u2112",
"&Larr;": "\u219E",
"&Lcaron;": "\u013D",
"&Lcedil;": "\u013B",
"&Lcy;": "\u041B",
"&LeftAngleBracket;": "\u27E8",
"&LeftArrow;": "\u2190",
"&LeftArrowBar;": "\u21E4",
"&LeftArrowRightArrow;": "\u21C6",
"&LeftCeiling;": "\u2308",
"&LeftDoubleBracket;": "\u27E6",
"&LeftDownTeeVector;": "\u2961",
"&LeftDownVector;": "\u21C3",
"&LeftDownVectorBar;": "\u2959",
"&LeftFloor;": "\u230A",
"&LeftRightArrow;": "\u2194",
"&LeftRightVector;": "\u294E",
"&LeftTee;": "\u22A3",
"&LeftTeeArrow;": "\u21A4",
"&LeftTeeVector;": "\u295A",
"&LeftTriangle;": "\u22B2",
"&LeftTriangleBar;": "\u29CF",
"&LeftTriangleEqual;": "\u22B4",
"&LeftUpDownVector;": "\u2951",
"&LeftUpTeeVector;": "\u2960",
"&LeftUpVector;": "\u21BF",
"&LeftUpVectorBar;": "\u2958",
"&LeftVector;": "\u21BC",
"&LeftVectorBar;": "\u2952",
"&Leftarrow;": "\u21D0",
"&Leftrightarrow;": "\u21D4",
"&LessEqualGreater;": "\u22DA",
"&LessFullEqual;": "\u2266",
"&LessGreater;": "\u2276",
"&LessLess;": "\u2AA1",
"&LessSlantEqual;": "\u2A7D",
"&LessTilde;": "\u2272",
"&Lfr;": "\u{1D50F}",
"&Ll;": "\u22D8",
"&Lleftarrow;": "\u21DA",
"&Lmidot;": "\u013F",
"&LongLeftArrow;": "\u27F5",
"&LongLeftRightArrow;": "\u27F7",
"&LongRightArrow;": "\u27F6",
"&Longleftarrow;": "\u27F8",
"&Longleftrightarrow;": "\u27FA",
"&Longrightarrow;": "\u27F9",
"&Lopf;": "\u{1D543}",
"&LowerLeftArrow;": "\u2199",
"&LowerRightArrow;": "\u2198",
"&Lscr;": "\u2112",
"&Lsh;": "\u21B0",
"&Lstrok;": "\u0141",
"&Lt;": "\u226A",
"&Map;": "\u2905",
"&Mcy;": "\u041C",
"&MediumSpace;": "\u205F",
"&Mellintrf;": "\u2133",
"&Mfr;": "\u{1D510}",
"&MinusPlus;": "\u2213",
"&Mopf;": "\u{1D544}",
"&Mscr;": "\u2133",
"&Mu;": "\u039C",
"&NJcy;": "\u040A",
"&Nacute;": "\u0143",
"&Ncaron;": "\u0147",
"&Ncedil;": "\u0145",
"&Ncy;": "\u041D",
"&NegativeMediumSpace;": "\u200B",
"&NegativeThickSpace;": "\u200B",
"&NegativeThinSpace;": "\u200B",
"&NegativeVeryThinSpace;": "\u200B",
"&NestedGreaterGreater;": "\u226B",
"&NestedLessLess;": "\u226A",
"&NewLine;": "\n",
"&Nfr;": "\u{1D511}",
"&NoBreak;": "\u2060",
"&NonBreakingSpace;": "\xA0",
"&Nopf;": "\u2115",
"&Not;": "\u2AEC",
"&NotCongruent;": "\u2262",
"&NotCupCap;": "\u226D",
"&NotDoubleVerticalBar;": "\u2226",
"&NotElement;": "\u2209",
"&NotEqual;": "\u2260",
"&NotEqualTilde;": "\u2242\u0338",
"&NotExists;": "\u2204",
"&NotGreater;": "\u226F",
"&NotGreaterEqual;": "\u2271",
"&NotGreaterFullEqual;": "\u2267\u0338",
"&NotGreaterGreater;": "\u226B\u0338",
"&NotGreaterLess;": "\u2279",
"&NotGreaterSlantEqual;": "\u2A7E\u0338",
"&NotGreaterTilde;": "\u2275",
"&NotHumpDownHump;": "\u224E\u0338",
"&NotHumpEqual;": "\u224F\u0338",
"&NotLeftTriangle;": "\u22EA",
"&NotLeftTriangleBar;": "\u29CF\u0338",
"&NotLeftTriangleEqual;": "\u22EC",
"&NotLess;": "\u226E",
"&NotLessEqual;": "\u2270",
"&NotLessGreater;": "\u2278",
"&NotLessLess;": "\u226A\u0338",
"&NotLessSlantEqual;": "\u2A7D\u0338",
"&NotLessTilde;": "\u2274",
"&NotNestedGreaterGreater;": "\u2AA2\u0338",
"&NotNestedLessLess;": "\u2AA1\u0338",
"&NotPrecedes;": "\u2280",
"&NotPrecedesEqual;": "\u2AAF\u0338",
"&NotPrecedesSlantEqual;": "\u22E0",
"&NotReverseElement;": "\u220C",
"&NotRightTriangle;": "\u22EB",
"&NotRightTriangleBar;": "\u29D0\u0338",
"&NotRightTriangleEqual;": "\u22ED",
"&NotSquareSubset;": "\u228F\u0338",
"&NotSquareSubsetEqual;": "\u22E2",
"&NotSquareSuperset;": "\u2290\u0338",
"&NotSquareSupersetEqual;": "\u22E3",
"&NotSubset;": "\u2282\u20D2",
"&NotSubsetEqual;": "\u2288",
"&NotSucceeds;": "\u2281",
"&NotSucceedsEqual;": "\u2AB0\u0338",
"&NotSucceedsSlantEqual;": "\u22E1",
"&NotSucceedsTilde;": "\u227F\u0338",
"&NotSuperset;": "\u2283\u20D2",
"&NotSupersetEqual;": "\u2289",
"&NotTilde;": "\u2241",
"&NotTildeEqual;": "\u2244",
"&NotTildeFullEqual;": "\u2247",
"&NotTildeTilde;": "\u2249",
"&NotVerticalBar;": "\u2224",
"&Nscr;": "\u{1D4A9}",
"&Ntilde": "\xD1",
"&Ntilde;": "\xD1",
"&Nu;": "\u039D",
"&OElig;": "\u0152",
"&Oacute": "\xD3",
"&Oacute;": "\xD3",
"&Ocirc": "\xD4",
"&Ocirc;": "\xD4",
"&Ocy;": "\u041E",
"&Odblac;": "\u0150",
"&Ofr;": "\u{1D512}",
"&Ograve": "\xD2",
"&Ograve;": "\xD2",
"&Omacr;": "\u014C",
"&Omega;": "\u03A9",
"&Omicron;": "\u039F",
"&Oopf;": "\u{1D546}",
"&OpenCurlyDoubleQuote;": "\u201C",
"&OpenCurlyQuote;": "\u2018",
"&Or;": "\u2A54",
"&Oscr;": "\u{1D4AA}",
"&Oslash": "\xD8",
"&Oslash;": "\xD8",
"&Otilde": "\xD5",
"&Otilde;": "\xD5",
"&Otimes;": "\u2A37",
"&Ouml": "\xD6",
"&Ouml;": "\xD6",
"&OverBar;": "\u203E",
"&OverBrace;": "\u23DE",
"&OverBracket;": "\u23B4",
"&OverParenthesis;": "\u23DC",
"&PartialD;": "\u2202",
"&Pcy;": "\u041F",
"&Pfr;": "\u{1D513}",
"&Phi;": "\u03A6",
"&Pi;": "\u03A0",
"&PlusMinus;": "\xB1",
"&Poincareplane;": "\u210C",
"&Popf;": "\u2119",
"&Pr;": "\u2ABB",
"&Precedes;": "\u227A",
"&PrecedesEqual;": "\u2AAF",
"&PrecedesSlantEqual;": "\u227C",
"&PrecedesTilde;": "\u227E",
"&Prime;": "\u2033",
"&Product;": "\u220F",
"&Proportion;": "\u2237",
"&Proportional;": "\u221D",
"&Pscr;": "\u{1D4AB}",
"&Psi;": "\u03A8",
"&QUOT": '"',
"&QUOT;": '"',
"&Qfr;": "\u{1D514}",
"&Qopf;": "\u211A",
"&Qscr;": "\u{1D4AC}",
"&RBarr;": "\u2910",
"&REG": "\xAE",
"&REG;": "\xAE",
"&Racute;": "\u0154",
"&Rang;": "\u27EB",
"&Rarr;": "\u21A0",
"&Rarrtl;": "\u2916",
"&Rcaron;": "\u0158",
"&Rcedil;": "\u0156",
"&Rcy;": "\u0420",
"&Re;": "\u211C",
"&ReverseElement;": "\u220B",
"&ReverseEquilibrium;": "\u21CB",
"&ReverseUpEquilibrium;": "\u296F",
"&Rfr;": "\u211C",
"&Rho;": "\u03A1",
"&RightAngleBracket;": "\u27E9",
"&RightArrow;": "\u2192",
"&RightArrowBar;": "\u21E5",
"&RightArrowLeftArrow;": "\u21C4",
"&RightCeiling;": "\u2309",
"&RightDoubleBracket;": "\u27E7",
"&RightDownTeeVector;": "\u295D",
"&RightDownVector;": "\u21C2",
"&RightDownVectorBar;": "\u2955",
"&RightFloor;": "\u230B",
"&RightTee;": "\u22A2",
"&RightTeeArrow;": "\u21A6",
"&RightTeeVector;": "\u295B",
"&RightTriangle;": "\u22B3",
"&RightTriangleBar;": "\u29D0",
"&RightTriangleEqual;": "\u22B5",
"&RightUpDownVector;": "\u294F",
"&RightUpTeeVector;": "\u295C",
"&RightUpVector;": "\u21BE",
"&RightUpVectorBar;": "\u2954",
"&RightVector;": "\u21C0",
"&RightVectorBar;": "\u2953",
"&Rightarrow;": "\u21D2",
"&Ropf;": "\u211D",
"&RoundImplies;": "\u2970",
"&Rrightarrow;": "\u21DB",
"&Rscr;": "\u211B",
"&Rsh;": "\u21B1",
"&RuleDelayed;": "\u29F4",
"&SHCHcy;": "\u0429",
"&SHcy;": "\u0428",
"&SOFTcy;": "\u042C",
"&Sacute;": "\u015A",
"&Sc;": "\u2ABC",
"&Scaron;": "\u0160",
"&Scedil;": "\u015E",
"&Scirc;": "\u015C",
"&Scy;": "\u0421",
"&Sfr;": "\u{1D516}",
"&ShortDownArrow;": "\u2193",
"&ShortLeftArrow;": "\u2190",
"&ShortRightArrow;": "\u2192",
"&ShortUpArrow;": "\u2191",
"&Sigma;": "\u03A3",
"&SmallCircle;": "\u2218",
"&Sopf;": "\u{1D54A}",
"&Sqrt;": "\u221A",
"&Square;": "\u25A1",
"&SquareIntersection;": "\u2293",
"&SquareSubset;": "\u228F",
"&SquareSubsetEqual;": "\u2291",
"&SquareSuperset;": "\u2290",
"&SquareSupersetEqual;": "\u2292",
"&SquareUnion;": "\u2294",
"&Sscr;": "\u{1D4AE}",
"&Star;": "\u22C6",
"&Sub;": "\u22D0",
"&Subset;": "\u22D0",
"&SubsetEqual;": "\u2286",
"&Succeeds;": "\u227B",
"&SucceedsEqual;": "\u2AB0",
"&SucceedsSlantEqual;": "\u227D",
"&SucceedsTilde;": "\u227F",
"&SuchThat;": "\u220B",
"&Sum;": "\u2211",
"&Sup;": "\u22D1",
"&Superset;": "\u2283",
"&SupersetEqual;": "\u2287",
"&Supset;": "\u22D1",
"&THORN": "\xDE",
"&THORN;": "\xDE",
"&TRADE;": "\u2122",
"&TSHcy;": "\u040B",
"&TScy;": "\u0426",
"&Tab;": " ",
"&Tau;": "\u03A4",
"&Tcaron;": "\u0164",
"&Tcedil;": "\u0162",
"&Tcy;": "\u0422",
"&Tfr;": "\u{1D517}",
"&Therefore;": "\u2234",
"&Theta;": "\u0398",
"&ThickSpace;": "\u205F\u200A",
"&ThinSpace;": "\u2009",
"&Tilde;": "\u223C",
"&TildeEqual;": "\u2243",
"&TildeFullEqual;": "\u2245",
"&TildeTilde;": "\u2248",
"&Topf;": "\u{1D54B}",
"&TripleDot;": "\u20DB",
"&Tscr;": "\u{1D4AF}",
"&Tstrok;": "\u0166",
"&Uacute": "\xDA",
"&Uacute;": "\xDA",
"&Uarr;": "\u219F",
"&Uarrocir;": "\u2949",
"&Ubrcy;": "\u040E",
"&Ubreve;": "\u016C",
"&Ucirc": "\xDB",
"&Ucirc;": "\xDB",
"&Ucy;": "\u0423",
"&Udblac;": "\u0170",
"&Ufr;": "\u{1D518}",
"&Ugrave": "\xD9",
"&Ugrave;": "\xD9",
"&Umacr;": "\u016A",
"&UnderBar;": "_",
"&UnderBrace;": "\u23DF",
"&UnderBracket;": "\u23B5",
"&UnderParenthesis;": "\u23DD",
"&Union;": "\u22C3",
"&UnionPlus;": "\u228E",
"&Uogon;": "\u0172",
"&Uopf;": "\u{1D54C}",
"&UpArrow;": "\u2191",
"&UpArrowBar;": "\u2912",
"&UpArrowDownArrow;": "\u21C5",
"&UpDownArrow;": "\u2195",
"&UpEquilibrium;": "\u296E",
"&UpTee;": "\u22A5",
"&UpTeeArrow;": "\u21A5",
"&Uparrow;": "\u21D1",
"&Updownarrow;": "\u21D5",
"&UpperLeftArrow;": "\u2196",
"&UpperRightArrow;": "\u2197",
"&Upsi;": "\u03D2",
"&Upsilon;": "\u03A5",
"&Uring;": "\u016E",
"&Uscr;": "\u{1D4B0}",
"&Utilde;": "\u0168",
"&Uuml": "\xDC",
"&Uuml;": "\xDC",
"&VDash;": "\u22AB",
"&Vbar;": "\u2AEB",
"&Vcy;": "\u0412",
"&Vdash;": "\u22A9",
"&Vdashl;": "\u2AE6",
"&Vee;": "\u22C1",
"&Verbar;": "\u2016",
"&Vert;": "\u2016",
"&VerticalBar;": "\u2223",
"&VerticalLine;": "|",
"&VerticalSeparator;": "\u2758",
"&VerticalTilde;": "\u2240",
"&VeryThinSpace;": "\u200A",
"&Vfr;": "\u{1D519}",
"&Vopf;": "\u{1D54D}",
"&Vscr;": "\u{1D4B1}",
"&Vvdash;": "\u22AA",
"&Wcirc;": "\u0174",
"&Wedge;": "\u22C0",
"&Wfr;": "\u{1D51A}",
"&Wopf;": "\u{1D54E}",
"&Wscr;": "\u{1D4B2}",
"&Xfr;": "\u{1D51B}",
"&Xi;": "\u039E",
"&Xopf;": "\u{1D54F}",
"&Xscr;": "\u{1D4B3}",
"&YAcy;": "\u042F",
"&YIcy;": "\u0407",
"&YUcy;": "\u042E",
"&Yacute": "\xDD",
"&Yacute;": "\xDD",
"&Ycirc;": "\u0176",
"&Ycy;": "\u042B",
"&Yfr;": "\u{1D51C}",
"&Yopf;": "\u{1D550}",
"&Yscr;": "\u{1D4B4}",
"&Yuml;": "\u0178",
"&ZHcy;": "\u0416",
"&Zacute;": "\u0179",
"&Zcaron;": "\u017D",
"&Zcy;": "\u0417",
"&Zdot;": "\u017B",
"&ZeroWidthSpace;": "\u200B",
"&Zeta;": "\u0396",
"&Zfr;": "\u2128",
"&Zopf;": "\u2124",
"&Zscr;": "\u{1D4B5}",
"&aacute": "\xE1",
"&aacute;": "\xE1",
"&abreve;": "\u0103",
"&ac;": "\u223E",
"&acE;": "\u223E\u0333",
"&acd;": "\u223F",
"&acirc": "\xE2",
"&acirc;": "\xE2",
"&acute": "\xB4",
"&acute;": "\xB4",
"&acy;": "\u0430",
"&aelig": "\xE6",
"&aelig;": "\xE6",
"&af;": "\u2061",
"&afr;": "\u{1D51E}",
"&agrave": "\xE0",
"&agrave;": "\xE0",
"&alefsym;": "\u2135",
"&aleph;": "\u2135",
"&alpha;": "\u03B1",
"&amacr;": "\u0101",
"&amalg;": "\u2A3F",
"&amp": "&",
"&amp;": "&",
"&and;": "\u2227",
"&andand;": "\u2A55",
"&andd;": "\u2A5C",
"&andslope;": "\u2A58",
"&andv;": "\u2A5A",
"&ang;": "\u2220",
"&ange;": "\u29A4",
"&angle;": "\u2220",
"&angmsd;": "\u2221",
"&angmsdaa;": "\u29A8",
"&angmsdab;": "\u29A9",
"&angmsdac;": "\u29AA",
"&angmsdad;": "\u29AB",
"&angmsdae;": "\u29AC",
"&angmsdaf;": "\u29AD",
"&angmsdag;": "\u29AE",
"&angmsdah;": "\u29AF",
"&angrt;": "\u221F",
"&angrtvb;": "\u22BE",
"&angrtvbd;": "\u299D",
"&angsph;": "\u2222",
"&angst;": "\xC5",
"&angzarr;": "\u237C",
"&aogon;": "\u0105",
"&aopf;": "\u{1D552}",
"&ap;": "\u2248",
"&apE;": "\u2A70",
"&apacir;": "\u2A6F",
"&ape;": "\u224A",
"&apid;": "\u224B",
"&apos;": "'",
"&approx;": "\u2248",
"&approxeq;": "\u224A",
"&aring": "\xE5",
"&aring;": "\xE5",
"&ascr;": "\u{1D4B6}",
"&ast;": "*",
"&asymp;": "\u2248",
"&asympeq;": "\u224D",
"&atilde": "\xE3",
"&atilde;": "\xE3",
"&auml": "\xE4",
"&auml;": "\xE4",
"&awconint;": "\u2233",
"&awint;": "\u2A11",
"&bNot;": "\u2AED",
"&backcong;": "\u224C",
"&backepsilon;": "\u03F6",
"&backprime;": "\u2035",
"&backsim;": "\u223D",
"&backsimeq;": "\u22CD",
"&barvee;": "\u22BD",
"&barwed;": "\u2305",
"&barwedge;": "\u2305",
"&bbrk;": "\u23B5",
"&bbrktbrk;": "\u23B6",
"&bcong;": "\u224C",
"&bcy;": "\u0431",
"&bdquo;": "\u201E",
"&becaus;": "\u2235",
"&because;": "\u2235",
"&bemptyv;": "\u29B0",
"&bepsi;": "\u03F6",
"&bernou;": "\u212C",
"&beta;": "\u03B2",
"&beth;": "\u2136",
"&between;": "\u226C",
"&bfr;": "\u{1D51F}",
"&bigcap;": "\u22C2",
"&bigcirc;": "\u25EF",
"&bigcup;": "\u22C3",
"&bigodot;": "\u2A00",
"&bigoplus;": "\u2A01",
"&bigotimes;": "\u2A02",
"&bigsqcup;": "\u2A06",
"&bigstar;": "\u2605",
"&bigtriangledown;": "\u25BD",
"&bigtriangleup;": "\u25B3",
"&biguplus;": "\u2A04",
"&bigvee;": "\u22C1",
"&bigwedge;": "\u22C0",
"&bkarow;": "\u290D",
"&blacklozenge;": "\u29EB",
"&blacksquare;": "\u25AA",
"&blacktriangle;": "\u25B4",
"&blacktriangledown;": "\u25BE",
"&blacktriangleleft;": "\u25C2",
"&blacktriangleright;": "\u25B8",
"&blank;": "\u2423",
"&blk12;": "\u2592",
"&blk14;": "\u2591",
"&blk34;": "\u2593",
"&block;": "\u2588",
"&bne;": "=\u20E5",
"&bnequiv;": "\u2261\u20E5",
"&bnot;": "\u2310",
"&bopf;": "\u{1D553}",
"&bot;": "\u22A5",
"&bottom;": "\u22A5",
"&bowtie;": "\u22C8",
"&boxDL;": "\u2557",
"&boxDR;": "\u2554",
"&boxDl;": "\u2556",
"&boxDr;": "\u2553",
"&boxH;": "\u2550",
"&boxHD;": "\u2566",
"&boxHU;": "\u2569",
"&boxHd;": "\u2564",
"&boxHu;": "\u2567",
"&boxUL;": "\u255D",
"&boxUR;": "\u255A",
"&boxUl;": "\u255C",
"&boxUr;": "\u2559",
"&boxV;": "\u2551",
"&boxVH;": "\u256C",
"&boxVL;": "\u2563",
"&boxVR;": "\u2560",
"&boxVh;": "\u256B",
"&boxVl;": "\u2562",
"&boxVr;": "\u255F",
"&boxbox;": "\u29C9",
"&boxdL;": "\u2555",
"&boxdR;": "\u2552",
"&boxdl;": "\u2510",
"&boxdr;": "\u250C",
"&boxh;": "\u2500",
"&boxhD;": "\u2565",
"&boxhU;": "\u2568",
"&boxhd;": "\u252C",
"&boxhu;": "\u2534",
"&boxminus;": "\u229F",
"&boxplus;": "\u229E",
"&boxtimes;": "\u22A0",
"&boxuL;": "\u255B",
"&boxuR;": "\u2558",
"&boxul;": "\u2518",
"&boxur;": "\u2514",
"&boxv;": "\u2502",
"&boxvH;": "\u256A",
"&boxvL;": "\u2561",
"&boxvR;": "\u255E",
"&boxvh;": "\u253C",
"&boxvl;": "\u2524",
"&boxvr;": "\u251C",
"&bprime;": "\u2035",
"&breve;": "\u02D8",
"&brvbar": "\xA6",
"&brvbar;": "\xA6",
"&bscr;": "\u{1D4B7}",
"&bsemi;": "\u204F",
"&bsim;": "\u223D",
"&bsime;": "\u22CD",
"&bsol;": "\\",
"&bsolb;": "\u29C5",
"&bsolhsub;": "\u27C8",
"&bull;": "\u2022",
"&bullet;": "\u2022",
"&bump;": "\u224E",
"&bumpE;": "\u2AAE",
"&bumpe;": "\u224F",
"&bumpeq;": "\u224F",
"&cacute;": "\u0107",
"&cap;": "\u2229",
"&capand;": "\u2A44",
"&capbrcup;": "\u2A49",
"&capcap;": "\u2A4B",
"&capcup;": "\u2A47",
"&capdot;": "\u2A40",
"&caps;": "\u2229\uFE00",
"&caret;": "\u2041",
"&caron;": "\u02C7",
"&ccaps;": "\u2A4D",
"&ccaron;": "\u010D",
"&ccedil": "\xE7",
"&ccedil;": "\xE7",
"&ccirc;": "\u0109",
"&ccups;": "\u2A4C",
"&ccupssm;": "\u2A50",
"&cdot;": "\u010B",
"&cedil": "\xB8",
"&cedil;": "\xB8",
"&cemptyv;": "\u29B2",
"&cent": "\xA2",
"&cent;": "\xA2",
"&centerdot;": "\xB7",
"&cfr;": "\u{1D520}",
"&chcy;": "\u0447",
"&check;": "\u2713",
"&checkmark;": "\u2713",
"&chi;": "\u03C7",
"&cir;": "\u25CB",
"&cirE;": "\u29C3",
"&circ;": "\u02C6",
"&circeq;": "\u2257",
"&circlearrowleft;": "\u21BA",
"&circlearrowright;": "\u21BB",
"&circledR;": "\xAE",
"&circledS;": "\u24C8",
"&circledast;": "\u229B",
"&circledcirc;": "\u229A",
"&circleddash;": "\u229D",
"&cire;": "\u2257",
"&cirfnint;": "\u2A10",
"&cirmid;": "\u2AEF",
"&cirscir;": "\u29C2",
"&clubs;": "\u2663",
"&clubsuit;": "\u2663",
"&colon;": ":",
"&colone;": "\u2254",
"&coloneq;": "\u2254",
"&comma;": ",",
"&commat;": "@",
"&comp;": "\u2201",
"&compfn;": "\u2218",
"&complement;": "\u2201",
"&complexes;": "\u2102",
"&cong;": "\u2245",
"&congdot;": "\u2A6D",
"&conint;": "\u222E",
"&copf;": "\u{1D554}",
"&coprod;": "\u2210",
"&copy": "\xA9",
"&copy;": "\xA9",
"&copysr;": "\u2117",
"&crarr;": "\u21B5",
"&cross;": "\u2717",
"&cscr;": "\u{1D4B8}",
"&csub;": "\u2ACF",
"&csube;": "\u2AD1",
"&csup;": "\u2AD0",
"&csupe;": "\u2AD2",
"&ctdot;": "\u22EF",
"&cudarrl;": "\u2938",
"&cudarrr;": "\u2935",
"&cuepr;": "\u22DE",
"&cuesc;": "\u22DF",
"&cularr;": "\u21B6",
"&cularrp;": "\u293D",
"&cup;": "\u222A",
"&cupbrcap;": "\u2A48",
"&cupcap;": "\u2A46",
"&cupcup;": "\u2A4A",
"&cupdot;": "\u228D",
"&cupor;": "\u2A45",
"&cups;": "\u222A\uFE00",
"&curarr;": "\u21B7",
"&curarrm;": "\u293C",
"&curlyeqprec;": "\u22DE",
"&curlyeqsucc;": "\u22DF",
"&curlyvee;": "\u22CE",
"&curlywedge;": "\u22CF",
"&curren": "\xA4",
"&curren;": "\xA4",
"&curvearrowleft;": "\u21B6",
"&curvearrowright;": "\u21B7",
"&cuvee;": "\u22CE",
"&cuwed;": "\u22CF",
"&cwconint;": "\u2232",
"&cwint;": "\u2231",
"&cylcty;": "\u232D",
"&dArr;": "\u21D3",
"&dHar;": "\u2965",
"&dagger;": "\u2020",
"&daleth;": "\u2138",
"&darr;": "\u2193",
"&dash;": "\u2010",
"&dashv;": "\u22A3",
"&dbkarow;": "\u290F",
"&dblac;": "\u02DD",
"&dcaron;": "\u010F",
"&dcy;": "\u0434",
"&dd;": "\u2146",
"&ddagger;": "\u2021",
"&ddarr;": "\u21CA",
"&ddotseq;": "\u2A77",
"&deg": "\xB0",
"&deg;": "\xB0",
"&delta;": "\u03B4",
"&demptyv;": "\u29B1",
"&dfisht;": "\u297F",
"&dfr;": "\u{1D521}",
"&dharl;": "\u21C3",
"&dharr;": "\u21C2",
"&diam;": "\u22C4",
"&diamond;": "\u22C4",
"&diamondsuit;": "\u2666",
"&diams;": "\u2666",
"&die;": "\xA8",
"&digamma;": "\u03DD",
"&disin;": "\u22F2",
"&div;": "\xF7",
"&divide": "\xF7",
"&divide;": "\xF7",
"&divideontimes;": "\u22C7",
"&divonx;": "\u22C7",
"&djcy;": "\u0452",
"&dlcorn;": "\u231E",
"&dlcrop;": "\u230D",
"&dollar;": "$",
"&dopf;": "\u{1D555}",
"&dot;": "\u02D9",
"&doteq;": "\u2250",
"&doteqdot;": "\u2251",
"&dotminus;": "\u2238",
"&dotplus;": "\u2214",
"&dotsquare;": "\u22A1",
"&doublebarwedge;": "\u2306",
"&downarrow;": "\u2193",
"&downdownarrows;": "\u21CA",
"&downharpoonleft;": "\u21C3",
"&downharpoonright;": "\u21C2",
"&drbkarow;": "\u2910",
"&drcorn;": "\u231F",
"&drcrop;": "\u230C",
"&dscr;": "\u{1D4B9}",
"&dscy;": "\u0455",
"&dsol;": "\u29F6",
"&dstrok;": "\u0111",
"&dtdot;": "\u22F1",
"&dtri;": "\u25BF",
"&dtrif;": "\u25BE",
"&duarr;": "\u21F5",
"&duhar;": "\u296F",
"&dwangle;": "\u29A6",
"&dzcy;": "\u045F",
"&dzigrarr;": "\u27FF",
"&eDDot;": "\u2A77",
"&eDot;": "\u2251",
"&eacute": "\xE9",
"&eacute;": "\xE9",
"&easter;": "\u2A6E",
"&ecaron;": "\u011B",
"&ecir;": "\u2256",
"&ecirc": "\xEA",
"&ecirc;": "\xEA",
"&ecolon;": "\u2255",
"&ecy;": "\u044D",
"&edot;": "\u0117",
"&ee;": "\u2147",
"&efDot;": "\u2252",
"&efr;": "\u{1D522}",
"&eg;": "\u2A9A",
"&egrave": "\xE8",
"&egrave;": "\xE8",
"&egs;": "\u2A96",
"&egsdot;": "\u2A98",
"&el;": "\u2A99",
"&elinters;": "\u23E7",
"&ell;": "\u2113",
"&els;": "\u2A95",
"&elsdot;": "\u2A97",
"&emacr;": "\u0113",
"&empty;": "\u2205",
"&emptyset;": "\u2205",
"&emptyv;": "\u2205",
"&emsp13;": "\u2004",
"&emsp14;": "\u2005",
"&emsp;": "\u2003",
"&eng;": "\u014B",
"&ensp;": "\u2002",
"&eogon;": "\u0119",
"&eopf;": "\u{1D556}",
"&epar;": "\u22D5",
"&eparsl;": "\u29E3",
"&eplus;": "\u2A71",
"&epsi;": "\u03B5",
"&epsilon;": "\u03B5",
"&epsiv;": "\u03F5",
"&eqcirc;": "\u2256",
"&eqcolon;": "\u2255",
"&eqsim;": "\u2242",
"&eqslantgtr;": "\u2A96",
"&eqslantless;": "\u2A95",
"&equals;": "=",
"&equest;": "\u225F",
"&equiv;": "\u2261",
"&equivDD;": "\u2A78",
"&eqvparsl;": "\u29E5",
"&erDot;": "\u2253",
"&erarr;": "\u2971",
"&escr;": "\u212F",
"&esdot;": "\u2250",
"&esim;": "\u2242",
"&eta;": "\u03B7",
"&eth": "\xF0",
"&eth;": "\xF0",
"&euml": "\xEB",
"&euml;": "\xEB",
"&euro;": "\u20AC",
"&excl;": "!",
"&exist;": "\u2203",
"&expectation;": "\u2130",
"&exponentiale;": "\u2147",
"&fallingdotseq;": "\u2252",
"&fcy;": "\u0444",
"&female;": "\u2640",
"&ffilig;": "\uFB03",
"&fflig;": "\uFB00",
"&ffllig;": "\uFB04",
"&ffr;": "\u{1D523}",
"&filig;": "\uFB01",
"&fjlig;": "fj",
"&flat;": "\u266D",
"&fllig;": "\uFB02",
"&fltns;": "\u25B1",
"&fnof;": "\u0192",
"&fopf;": "\u{1D557}",
"&forall;": "\u2200",
"&fork;": "\u22D4",
"&forkv;": "\u2AD9",
"&fpartint;": "\u2A0D",
"&frac12": "\xBD",
"&frac12;": "\xBD",
"&frac13;": "\u2153",
"&frac14": "\xBC",
"&frac14;": "\xBC",
"&frac15;": "\u2155",
"&frac16;": "\u2159",
"&frac18;": "\u215B",
"&frac23;": "\u2154",
"&frac25;": "\u2156",
"&frac34": "\xBE",
"&frac34;": "\xBE",
"&frac35;": "\u2157",
"&frac38;": "\u215C",
"&frac45;": "\u2158",
"&frac56;": "\u215A",
"&frac58;": "\u215D",
"&frac78;": "\u215E",
"&frasl;": "\u2044",
"&frown;": "\u2322",
"&fscr;": "\u{1D4BB}",
"&gE;": "\u2267",
"&gEl;": "\u2A8C",
"&gacute;": "\u01F5",
"&gamma;": "\u03B3",
"&gammad;": "\u03DD",
"&gap;": "\u2A86",
"&gbreve;": "\u011F",
"&gcirc;": "\u011D",
"&gcy;": "\u0433",
"&gdot;": "\u0121",
"&ge;": "\u2265",
"&gel;": "\u22DB",
"&geq;": "\u2265",
"&geqq;": "\u2267",
"&geqslant;": "\u2A7E",
"&ges;": "\u2A7E",
"&gescc;": "\u2AA9",
"&gesdot;": "\u2A80",
"&gesdoto;": "\u2A82",
"&gesdotol;": "\u2A84",
"&gesl;": "\u22DB\uFE00",
"&gesles;": "\u2A94",
"&gfr;": "\u{1D524}",
"&gg;": "\u226B",
"&ggg;": "\u22D9",
"&gimel;": "\u2137",
"&gjcy;": "\u0453",
"&gl;": "\u2277",
"&glE;": "\u2A92",
"&gla;": "\u2AA5",
"&glj;": "\u2AA4",
"&gnE;": "\u2269",
"&gnap;": "\u2A8A",
"&gnapprox;": "\u2A8A",
"&gne;": "\u2A88",
"&gneq;": "\u2A88",
"&gneqq;": "\u2269",
"&gnsim;": "\u22E7",
"&gopf;": "\u{1D558}",
"&grave;": "`",
"&gscr;": "\u210A",
"&gsim;": "\u2273",
"&gsime;": "\u2A8E",
"&gsiml;": "\u2A90",
"&gt": ">",
"&gt;": ">",
"&gtcc;": "\u2AA7",
"&gtcir;": "\u2A7A",
"&gtdot;": "\u22D7",
"&gtlPar;": "\u2995",
"&gtquest;": "\u2A7C",
"&gtrapprox;": "\u2A86",
"&gtrarr;": "\u2978",
"&gtrdot;": "\u22D7",
"&gtreqless;": "\u22DB",
"&gtreqqless;": "\u2A8C",
"&gtrless;": "\u2277",
"&gtrsim;": "\u2273",
"&gvertneqq;": "\u2269\uFE00",
"&gvnE;": "\u2269\uFE00",
"&hArr;": "\u21D4",
"&hairsp;": "\u200A",
"&half;": "\xBD",
"&hamilt;": "\u210B",
"&hardcy;": "\u044A",
"&harr;": "\u2194",
"&harrcir;": "\u2948",
"&harrw;": "\u21AD",
"&hbar;": "\u210F",
"&hcirc;": "\u0125",
"&hearts;": "\u2665",
"&heartsuit;": "\u2665",
"&hellip;": "\u2026",
"&hercon;": "\u22B9",
"&hfr;": "\u{1D525}",
"&hksearow;": "\u2925",
"&hkswarow;": "\u2926",
"&hoarr;": "\u21FF",
"&homtht;": "\u223B",
"&hookleftarrow;": "\u21A9",
"&hookrightarrow;": "\u21AA",
"&hopf;": "\u{1D559}",
"&horbar;": "\u2015",
"&hscr;": "\u{1D4BD}",
"&hslash;": "\u210F",
"&hstrok;": "\u0127",
"&hybull;": "\u2043",
"&hyphen;": "\u2010",
"&iacute": "\xED",
"&iacute;": "\xED",
"&ic;": "\u2063",
"&icirc": "\xEE",
"&icirc;": "\xEE",
"&icy;": "\u0438",
"&iecy;": "\u0435",
"&iexcl": "\xA1",
"&iexcl;": "\xA1",
"&iff;": "\u21D4",
"&ifr;": "\u{1D526}",
"&igrave": "\xEC",
"&igrave;": "\xEC",
"&ii;": "\u2148",
"&iiiint;": "\u2A0C",
"&iiint;": "\u222D",
"&iinfin;": "\u29DC",
"&iiota;": "\u2129",
"&ijlig;": "\u0133",
"&imacr;": "\u012B",
"&image;": "\u2111",
"&imagline;": "\u2110",
"&imagpart;": "\u2111",
"&imath;": "\u0131",
"&imof;": "\u22B7",
"&imped;": "\u01B5",
"&in;": "\u2208",
"&incare;": "\u2105",
"&infin;": "\u221E",
"&infintie;": "\u29DD",
"&inodot;": "\u0131",
"&int;": "\u222B",
"&intcal;": "\u22BA",
"&integers;": "\u2124",
"&intercal;": "\u22BA",
"&intlarhk;": "\u2A17",
"&intprod;": "\u2A3C",
"&iocy;": "\u0451",
"&iogon;": "\u012F",
"&iopf;": "\u{1D55A}",
"&iota;": "\u03B9",
"&iprod;": "\u2A3C",
"&iquest": "\xBF",
"&iquest;": "\xBF",
"&iscr;": "\u{1D4BE}",
"&isin;": "\u2208",
"&isinE;": "\u22F9",
"&isindot;": "\u22F5",
"&isins;": "\u22F4",
"&isinsv;": "\u22F3",
"&isinv;": "\u2208",
"&it;": "\u2062",
"&itilde;": "\u0129",
"&iukcy;": "\u0456",
"&iuml": "\xEF",
"&iuml;": "\xEF",
"&jcirc;": "\u0135",
"&jcy;": "\u0439",
"&jfr;": "\u{1D527}",
"&jmath;": "\u0237",
"&jopf;": "\u{1D55B}",
"&jscr;": "\u{1D4BF}",
"&jsercy;": "\u0458",
"&jukcy;": "\u0454",
"&kappa;": "\u03BA",
"&kappav;": "\u03F0",
"&kcedil;": "\u0137",
"&kcy;": "\u043A",
"&kfr;": "\u{1D528}",
"&kgreen;": "\u0138",
"&khcy;": "\u0445",
"&kjcy;": "\u045C",
"&kopf;": "\u{1D55C}",
"&kscr;": "\u{1D4C0}",
"&lAarr;": "\u21DA",
"&lArr;": "\u21D0",
"&lAtail;": "\u291B",
"&lBarr;": "\u290E",
"&lE;": "\u2266",
"&lEg;": "\u2A8B",
"&lHar;": "\u2962",
"&lacute;": "\u013A",
"&laemptyv;": "\u29B4",
"&lagran;": "\u2112",
"&lambda;": "\u03BB",
"&lang;": "\u27E8",
"&langd;": "\u2991",
"&langle;": "\u27E8",
"&lap;": "\u2A85",
"&laquo": "\xAB",
"&laquo;": "\xAB",
"&larr;": "\u2190",
"&larrb;": "\u21E4",
"&larrbfs;": "\u291F",
"&larrfs;": "\u291D",
"&larrhk;": "\u21A9",
"&larrlp;": "\u21AB",
"&larrpl;": "\u2939",
"&larrsim;": "\u2973",
"&larrtl;": "\u21A2",
"&lat;": "\u2AAB",
"&latail;": "\u2919",
"&late;": "\u2AAD",
"&lates;": "\u2AAD\uFE00",
"&lbarr;": "\u290C",
"&lbbrk;": "\u2772",
"&lbrace;": "{",
"&lbrack;": "[",
"&lbrke;": "\u298B",
"&lbrksld;": "\u298F",
"&lbrkslu;": "\u298D",
"&lcaron;": "\u013E",
"&lcedil;": "\u013C",
"&lceil;": "\u2308",
"&lcub;": "{",
"&lcy;": "\u043B",
"&ldca;": "\u2936",
"&ldquo;": "\u201C",
"&ldquor;": "\u201E",
"&ldrdhar;": "\u2967",
"&ldrushar;": "\u294B",
"&ldsh;": "\u21B2",
"&le;": "\u2264",
"&leftarrow;": "\u2190",
"&leftarrowtail;": "\u21A2",
"&leftharpoondown;": "\u21BD",
"&leftharpoonup;": "\u21BC",
"&leftleftarrows;": "\u21C7",
"&leftrightarrow;": "\u2194",
"&leftrightarrows;": "\u21C6",
"&leftrightharpoons;": "\u21CB",
"&leftrightsquigarrow;": "\u21AD",
"&leftthreetimes;": "\u22CB",
"&leg;": "\u22DA",
"&leq;": "\u2264",
"&leqq;": "\u2266",
"&leqslant;": "\u2A7D",
"&les;": "\u2A7D",
"&lescc;": "\u2AA8",
"&lesdot;": "\u2A7F",
"&lesdoto;": "\u2A81",
"&lesdotor;": "\u2A83",
"&lesg;": "\u22DA\uFE00",
"&lesges;": "\u2A93",
"&lessapprox;": "\u2A85",
"&lessdot;": "\u22D6",
"&lesseqgtr;": "\u22DA",
"&lesseqqgtr;": "\u2A8B",
"&lessgtr;": "\u2276",
"&lesssim;": "\u2272",
"&lfisht;": "\u297C",
"&lfloor;": "\u230A",
"&lfr;": "\u{1D529}",
"&lg;": "\u2276",
"&lgE;": "\u2A91",
"&lhard;": "\u21BD",
"&lharu;": "\u21BC",
"&lharul;": "\u296A",
"&lhblk;": "\u2584",
"&ljcy;": "\u0459",
"&ll;": "\u226A",
"&llarr;": "\u21C7",
"&llcorner;": "\u231E",
"&llhard;": "\u296B",
"&lltri;": "\u25FA",
"&lmidot;": "\u0140",
"&lmoust;": "\u23B0",
"&lmoustache;": "\u23B0",
"&lnE;": "\u2268",
"&lnap;": "\u2A89",
"&lnapprox;": "\u2A89",
"&lne;": "\u2A87",
"&lneq;": "\u2A87",
"&lneqq;": "\u2268",
"&lnsim;": "\u22E6",
"&loang;": "\u27EC",
"&loarr;": "\u21FD",
"&lobrk;": "\u27E6",
"&longleftarrow;": "\u27F5",
"&longleftrightarrow;": "\u27F7",
"&longmapsto;": "\u27FC",
"&longrightarrow;": "\u27F6",
"&looparrowleft;": "\u21AB",
"&looparrowright;": "\u21AC",
"&lopar;": "\u2985",
"&lopf;": "\u{1D55D}",
"&loplus;": "\u2A2D",
"&lotimes;": "\u2A34",
"&lowast;": "\u2217",
"&lowbar;": "_",
"&loz;": "\u25CA",
"&lozenge;": "\u25CA",
"&lozf;": "\u29EB",
"&lpar;": "(",
"&lparlt;": "\u2993",
"&lrarr;": "\u21C6",
"&lrcorner;": "\u231F",
"&lrhar;": "\u21CB",
"&lrhard;": "\u296D",
"&lrm;": "\u200E",
"&lrtri;": "\u22BF",
"&lsaquo;": "\u2039",
"&lscr;": "\u{1D4C1}",
"&lsh;": "\u21B0",
"&lsim;": "\u2272",
"&lsime;": "\u2A8D",
"&lsimg;": "\u2A8F",
"&lsqb;": "[",
"&lsquo;": "\u2018",
"&lsquor;": "\u201A",
"&lstrok;": "\u0142",
"&lt": "<",
"&lt;": "<",
"&ltcc;": "\u2AA6",
"&ltcir;": "\u2A79",
"&ltdot;": "\u22D6",
"&lthree;": "\u22CB",
"&ltimes;": "\u22C9",
"&ltlarr;": "\u2976",
"&ltquest;": "\u2A7B",
"&ltrPar;": "\u2996",
"&ltri;": "\u25C3",
"&ltrie;": "\u22B4",
"&ltrif;": "\u25C2",
"&lurdshar;": "\u294A",
"&luruhar;": "\u2966",
"&lvertneqq;": "\u2268\uFE00",
"&lvnE;": "\u2268\uFE00",
"&mDDot;": "\u223A",
"&macr": "\xAF",
"&macr;": "\xAF",
"&male;": "\u2642",
"&malt;": "\u2720",
"&maltese;": "\u2720",
"&map;": "\u21A6",
"&mapsto;": "\u21A6",
"&mapstodown;": "\u21A7",
"&mapstoleft;": "\u21A4",
"&mapstoup;": "\u21A5",
"&marker;": "\u25AE",
"&mcomma;": "\u2A29",
"&mcy;": "\u043C",
"&mdash;": "\u2014",
"&measuredangle;": "\u2221",
"&mfr;": "\u{1D52A}",
"&mho;": "\u2127",
"&micro": "\xB5",
"&micro;": "\xB5",
"&mid;": "\u2223",
"&midast;": "*",
"&midcir;": "\u2AF0",
"&middot": "\xB7",
"&middot;": "\xB7",
"&minus;": "\u2212",
"&minusb;": "\u229F",
"&minusd;": "\u2238",
"&minusdu;": "\u2A2A",
"&mlcp;": "\u2ADB",
"&mldr;": "\u2026",
"&mnplus;": "\u2213",
"&models;": "\u22A7",
"&mopf;": "\u{1D55E}",
"&mp;": "\u2213",
"&mscr;": "\u{1D4C2}",
"&mstpos;": "\u223E",
"&mu;": "\u03BC",
"&multimap;": "\u22B8",
"&mumap;": "\u22B8",
"&nGg;": "\u22D9\u0338",
"&nGt;": "\u226B\u20D2",
"&nGtv;": "\u226B\u0338",
"&nLeftarrow;": "\u21CD",
"&nLeftrightarrow;": "\u21CE",
"&nLl;": "\u22D8\u0338",
"&nLt;": "\u226A\u20D2",
"&nLtv;": "\u226A\u0338",
"&nRightarrow;": "\u21CF",
"&nVDash;": "\u22AF",
"&nVdash;": "\u22AE",
"&nabla;": "\u2207",
"&nacute;": "\u0144",
"&nang;": "\u2220\u20D2",
"&nap;": "\u2249",
"&napE;": "\u2A70\u0338",
"&napid;": "\u224B\u0338",
"&napos;": "\u0149",
"&napprox;": "\u2249",
"&natur;": "\u266E",
"&natural;": "\u266E",
"&naturals;": "\u2115",
"&nbsp": "\xA0",
"&nbsp;": "\xA0",
"&nbump;": "\u224E\u0338",
"&nbumpe;": "\u224F\u0338",
"&ncap;": "\u2A43",
"&ncaron;": "\u0148",
"&ncedil;": "\u0146",
"&ncong;": "\u2247",
"&ncongdot;": "\u2A6D\u0338",
"&ncup;": "\u2A42",
"&ncy;": "\u043D",
"&ndash;": "\u2013",
"&ne;": "\u2260",
"&neArr;": "\u21D7",
"&nearhk;": "\u2924",
"&nearr;": "\u2197",
"&nearrow;": "\u2197",
"&nedot;": "\u2250\u0338",
"&nequiv;": "\u2262",
"&nesear;": "\u2928",
"&nesim;": "\u2242\u0338",
"&nexist;": "\u2204",
"&nexists;": "\u2204",
"&nfr;": "\u{1D52B}",
"&ngE;": "\u2267\u0338",
"&nge;": "\u2271",
"&ngeq;": "\u2271",
"&ngeqq;": "\u2267\u0338",
"&ngeqslant;": "\u2A7E\u0338",
"&nges;": "\u2A7E\u0338",
"&ngsim;": "\u2275",
"&ngt;": "\u226F",
"&ngtr;": "\u226F",
"&nhArr;": "\u21CE",
"&nharr;": "\u21AE",
"&nhpar;": "\u2AF2",
"&ni;": "\u220B",
"&nis;": "\u22FC",
"&nisd;": "\u22FA",
"&niv;": "\u220B",
"&njcy;": "\u045A",
"&nlArr;": "\u21CD",
"&nlE;": "\u2266\u0338",
"&nlarr;": "\u219A",
"&nldr;": "\u2025",
"&nle;": "\u2270",
"&nleftarrow;": "\u219A",
"&nleftrightarrow;": "\u21AE",
"&nleq;": "\u2270",
"&nleqq;": "\u2266\u0338",
"&nleqslant;": "\u2A7D\u0338",
"&nles;": "\u2A7D\u0338",
"&nless;": "\u226E",
"&nlsim;": "\u2274",
"&nlt;": "\u226E",
"&nltri;": "\u22EA",
"&nltrie;": "\u22EC",
"&nmid;": "\u2224",
"&nopf;": "\u{1D55F}",
"&not": "\xAC",
"&not;": "\xAC",
"&notin;": "\u2209",
"&notinE;": "\u22F9\u0338",
"&notindot;": "\u22F5\u0338",
"&notinva;": "\u2209",
"&notinvb;": "\u22F7",
"&notinvc;": "\u22F6",
"&notni;": "\u220C",
"&notniva;": "\u220C",
"&notnivb;": "\u22FE",
"&notnivc;": "\u22FD",
"&npar;": "\u2226",
"&nparallel;": "\u2226",
"&nparsl;": "\u2AFD\u20E5",
"&npart;": "\u2202\u0338",
"&npolint;": "\u2A14",
"&npr;": "\u2280",
"&nprcue;": "\u22E0",
"&npre;": "\u2AAF\u0338",
"&nprec;": "\u2280",
"&npreceq;": "\u2AAF\u0338",
"&nrArr;": "\u21CF",
"&nrarr;": "\u219B",
"&nrarrc;": "\u2933\u0338",
"&nrarrw;": "\u219D\u0338",
"&nrightarrow;": "\u219B",
"&nrtri;": "\u22EB",
"&nrtrie;": "\u22ED",
"&nsc;": "\u2281",
"&nsccue;": "\u22E1",
"&nsce;": "\u2AB0\u0338",
"&nscr;": "\u{1D4C3}",
"&nshortmid;": "\u2224",
"&nshortparallel;": "\u2226",
"&nsim;": "\u2241",
"&nsime;": "\u2244",
"&nsimeq;": "\u2244",
"&nsmid;": "\u2224",
"&nspar;": "\u2226",
"&nsqsube;": "\u22E2",
"&nsqsupe;": "\u22E3",
"&nsub;": "\u2284",
"&nsubE;": "\u2AC5\u0338",
"&nsube;": "\u2288",
"&nsubset;": "\u2282\u20D2",
"&nsubseteq;": "\u2288",
"&nsubseteqq;": "\u2AC5\u0338",
"&nsucc;": "\u2281",
"&nsucceq;": "\u2AB0\u0338",
"&nsup;": "\u2285",
"&nsupE;": "\u2AC6\u0338",
"&nsupe;": "\u2289",
"&nsupset;": "\u2283\u20D2",
"&nsupseteq;": "\u2289",
"&nsupseteqq;": "\u2AC6\u0338",
"&ntgl;": "\u2279",
"&ntilde": "\xF1",
"&ntilde;": "\xF1",
"&ntlg;": "\u2278",
"&ntriangleleft;": "\u22EA",
"&ntrianglelefteq;": "\u22EC",
"&ntriangleright;": "\u22EB",
"&ntrianglerighteq;": "\u22ED",
"&nu;": "\u03BD",
"&num;": "#",
"&numero;": "\u2116",
"&numsp;": "\u2007",
"&nvDash;": "\u22AD",
"&nvHarr;": "\u2904",
"&nvap;": "\u224D\u20D2",
"&nvdash;": "\u22AC",
"&nvge;": "\u2265\u20D2",
"&nvgt;": ">\u20D2",
"&nvinfin;": "\u29DE",
"&nvlArr;": "\u2902",
"&nvle;": "\u2264\u20D2",
"&nvlt;": "<\u20D2",
"&nvltrie;": "\u22B4\u20D2",
"&nvrArr;": "\u2903",
"&nvrtrie;": "\u22B5\u20D2",
"&nvsim;": "\u223C\u20D2",
"&nwArr;": "\u21D6",
"&nwarhk;": "\u2923",
"&nwarr;": "\u2196",
"&nwarrow;": "\u2196",
"&nwnear;": "\u2927",
"&oS;": "\u24C8",
"&oacute": "\xF3",
"&oacute;": "\xF3",
"&oast;": "\u229B",
"&ocir;": "\u229A",
"&ocirc": "\xF4",
"&ocirc;": "\xF4",
"&ocy;": "\u043E",
"&odash;": "\u229D",
"&odblac;": "\u0151",
"&odiv;": "\u2A38",
"&odot;": "\u2299",
"&odsold;": "\u29BC",
"&oelig;": "\u0153",
"&ofcir;": "\u29BF",
"&ofr;": "\u{1D52C}",
"&ogon;": "\u02DB",
"&ograve": "\xF2",
"&ograve;": "\xF2",
"&ogt;": "\u29C1",
"&ohbar;": "\u29B5",
"&ohm;": "\u03A9",
"&oint;": "\u222E",
"&olarr;": "\u21BA",
"&olcir;": "\u29BE",
"&olcross;": "\u29BB",
"&oline;": "\u203E",
"&olt;": "\u29C0",
"&omacr;": "\u014D",
"&omega;": "\u03C9",
"&omicron;": "\u03BF",
"&omid;": "\u29B6",
"&ominus;": "\u2296",
"&oopf;": "\u{1D560}",
"&opar;": "\u29B7",
"&operp;": "\u29B9",
"&oplus;": "\u2295",
"&or;": "\u2228",
"&orarr;": "\u21BB",
"&ord;": "\u2A5D",
"&order;": "\u2134",
"&orderof;": "\u2134",
"&ordf": "\xAA",
"&ordf;": "\xAA",
"&ordm": "\xBA",
"&ordm;": "\xBA",
"&origof;": "\u22B6",
"&oror;": "\u2A56",
"&orslope;": "\u2A57",
"&orv;": "\u2A5B",
"&oscr;": "\u2134",
"&oslash": "\xF8",
"&oslash;": "\xF8",
"&osol;": "\u2298",
"&otilde": "\xF5",
"&otilde;": "\xF5",
"&otimes;": "\u2297",
"&otimesas;": "\u2A36",
"&ouml": "\xF6",
"&ouml;": "\xF6",
"&ovbar;": "\u233D",
"&par;": "\u2225",
"&para": "\xB6",
"&para;": "\xB6",
"&parallel;": "\u2225",
"&parsim;": "\u2AF3",
"&parsl;": "\u2AFD",
"&part;": "\u2202",
"&pcy;": "\u043F",
"&percnt;": "%",
"&period;": ".",
"&permil;": "\u2030",
"&perp;": "\u22A5",
"&pertenk;": "\u2031",
"&pfr;": "\u{1D52D}",
"&phi;": "\u03C6",
"&phiv;": "\u03D5",
"&phmmat;": "\u2133",
"&phone;": "\u260E",
"&pi;": "\u03C0",
"&pitchfork;": "\u22D4",
"&piv;": "\u03D6",
"&planck;": "\u210F",
"&planckh;": "\u210E",
"&plankv;": "\u210F",
"&plus;": "+",
"&plusacir;": "\u2A23",
"&plusb;": "\u229E",
"&pluscir;": "\u2A22",
"&plusdo;": "\u2214",
"&plusdu;": "\u2A25",
"&pluse;": "\u2A72",
"&plusmn": "\xB1",
"&plusmn;": "\xB1",
"&plussim;": "\u2A26",
"&plustwo;": "\u2A27",
"&pm;": "\xB1",
"&pointint;": "\u2A15",
"&popf;": "\u{1D561}",
"&pound": "\xA3",
"&pound;": "\xA3",
"&pr;": "\u227A",
"&prE;": "\u2AB3",
"&prap;": "\u2AB7",
"&prcue;": "\u227C",
"&pre;": "\u2AAF",
"&prec;": "\u227A",
"&precapprox;": "\u2AB7",
"&preccurlyeq;": "\u227C",
"&preceq;": "\u2AAF",
"&precnapprox;": "\u2AB9",
"&precneqq;": "\u2AB5",
"&precnsim;": "\u22E8",
"&precsim;": "\u227E",
"&prime;": "\u2032",
"&primes;": "\u2119",
"&prnE;": "\u2AB5",
"&prnap;": "\u2AB9",
"&prnsim;": "\u22E8",
"&prod;": "\u220F",
"&profalar;": "\u232E",
"&profline;": "\u2312",
"&profsurf;": "\u2313",
"&prop;": "\u221D",
"&propto;": "\u221D",
"&prsim;": "\u227E",
"&prurel;": "\u22B0",
"&pscr;": "\u{1D4C5}",
"&psi;": "\u03C8",
"&puncsp;": "\u2008",
"&qfr;": "\u{1D52E}",
"&qint;": "\u2A0C",
"&qopf;": "\u{1D562}",
"&qprime;": "\u2057",
"&qscr;": "\u{1D4C6}",
"&quaternions;": "\u210D",
"&quatint;": "\u2A16",
"&quest;": "?",
"&questeq;": "\u225F",
"&quot": '"',
"&quot;": '"',
"&rAarr;": "\u21DB",
"&rArr;": "\u21D2",
"&rAtail;": "\u291C",
"&rBarr;": "\u290F",
"&rHar;": "\u2964",
"&race;": "\u223D\u0331",
"&racute;": "\u0155",
"&radic;": "\u221A",
"&raemptyv;": "\u29B3",
"&rang;": "\u27E9",
"&rangd;": "\u2992",
"&range;": "\u29A5",
"&rangle;": "\u27E9",
"&raquo": "\xBB",
"&raquo;": "\xBB",
"&rarr;": "\u2192",
"&rarrap;": "\u2975",
"&rarrb;": "\u21E5",
"&rarrbfs;": "\u2920",
"&rarrc;": "\u2933",
"&rarrfs;": "\u291E",
"&rarrhk;": "\u21AA",
"&rarrlp;": "\u21AC",
"&rarrpl;": "\u2945",
"&rarrsim;": "\u2974",
"&rarrtl;": "\u21A3",
"&rarrw;": "\u219D",
"&ratail;": "\u291A",
"&ratio;": "\u2236",
"&rationals;": "\u211A",
"&rbarr;": "\u290D",
"&rbbrk;": "\u2773",
"&rbrace;": "}",
"&rbrack;": "]",
"&rbrke;": "\u298C",
"&rbrksld;": "\u298E",
"&rbrkslu;": "\u2990",
"&rcaron;": "\u0159",
"&rcedil;": "\u0157",
"&rceil;": "\u2309",
"&rcub;": "}",
"&rcy;": "\u0440",
"&rdca;": "\u2937",
"&rdldhar;": "\u2969",
"&rdquo;": "\u201D",
"&rdquor;": "\u201D",
"&rdsh;": "\u21B3",
"&real;": "\u211C",
"&realine;": "\u211B",
"&realpart;": "\u211C",
"&reals;": "\u211D",
"&rect;": "\u25AD",
"&reg": "\xAE",
"&reg;": "\xAE",
"&rfisht;": "\u297D",
"&rfloor;": "\u230B",
"&rfr;": "\u{1D52F}",
"&rhard;": "\u21C1",
"&rharu;": "\u21C0",
"&rharul;": "\u296C",
"&rho;": "\u03C1",
"&rhov;": "\u03F1",
"&rightarrow;": "\u2192",
"&rightarrowtail;": "\u21A3",
"&rightharpoondown;": "\u21C1",
"&rightharpoonup;": "\u21C0",
"&rightleftarrows;": "\u21C4",
"&rightleftharpoons;": "\u21CC",
"&rightrightarrows;": "\u21C9",
"&rightsquigarrow;": "\u219D",
"&rightthreetimes;": "\u22CC",
"&ring;": "\u02DA",
"&risingdotseq;": "\u2253",
"&rlarr;": "\u21C4",
"&rlhar;": "\u21CC",
"&rlm;": "\u200F",
"&rmoust;": "\u23B1",
"&rmoustache;": "\u23B1",
"&rnmid;": "\u2AEE",
"&roang;": "\u27ED",
"&roarr;": "\u21FE",
"&robrk;": "\u27E7",
"&ropar;": "\u2986",
"&ropf;": "\u{1D563}",
"&roplus;": "\u2A2E",
"&rotimes;": "\u2A35",
"&rpar;": ")",
"&rpargt;": "\u2994",
"&rppolint;": "\u2A12",
"&rrarr;": "\u21C9",
"&rsaquo;": "\u203A",
"&rscr;": "\u{1D4C7}",
"&rsh;": "\u21B1",
"&rsqb;": "]",
"&rsquo;": "\u2019",
"&rsquor;": "\u2019",
"&rthree;": "\u22CC",
"&rtimes;": "\u22CA",
"&rtri;": "\u25B9",
"&rtrie;": "\u22B5",
"&rtrif;": "\u25B8",
"&rtriltri;": "\u29CE",
"&ruluhar;": "\u2968",
"&rx;": "\u211E",
"&sacute;": "\u015B",
"&sbquo;": "\u201A",
"&sc;": "\u227B",
"&scE;": "\u2AB4",
"&scap;": "\u2AB8",
"&scaron;": "\u0161",
"&sccue;": "\u227D",
"&sce;": "\u2AB0",
"&scedil;": "\u015F",
"&scirc;": "\u015D",
"&scnE;": "\u2AB6",
"&scnap;": "\u2ABA",
"&scnsim;": "\u22E9",
"&scpolint;": "\u2A13",
"&scsim;": "\u227F",
"&scy;": "\u0441",
"&sdot;": "\u22C5",
"&sdotb;": "\u22A1",
"&sdote;": "\u2A66",
"&seArr;": "\u21D8",
"&searhk;": "\u2925",
"&searr;": "\u2198",
"&searrow;": "\u2198",
"&sect": "\xA7",
"&sect;": "\xA7",
"&semi;": ";",
"&seswar;": "\u2929",
"&setminus;": "\u2216",
"&setmn;": "\u2216",
"&sext;": "\u2736",
"&sfr;": "\u{1D530}",
"&sfrown;": "\u2322",
"&sharp;": "\u266F",
"&shchcy;": "\u0449",
"&shcy;": "\u0448",
"&shortmid;": "\u2223",
"&shortparallel;": "\u2225",
"&shy": "\xAD",
"&shy;": "\xAD",
"&sigma;": "\u03C3",
"&sigmaf;": "\u03C2",
"&sigmav;": "\u03C2",
"&sim;": "\u223C",
"&simdot;": "\u2A6A",
"&sime;": "\u2243",
"&simeq;": "\u2243",
"&simg;": "\u2A9E",
"&simgE;": "\u2AA0",
"&siml;": "\u2A9D",
"&simlE;": "\u2A9F",
"&simne;": "\u2246",
"&simplus;": "\u2A24",
"&simrarr;": "\u2972",
"&slarr;": "\u2190",
"&smallsetminus;": "\u2216",
"&smashp;": "\u2A33",
"&smeparsl;": "\u29E4",
"&smid;": "\u2223",
"&smile;": "\u2323",
"&smt;": "\u2AAA",
"&smte;": "\u2AAC",
"&smtes;": "\u2AAC\uFE00",
"&softcy;": "\u044C",
"&sol;": "/",
"&solb;": "\u29C4",
"&solbar;": "\u233F",
"&sopf;": "\u{1D564}",
"&spades;": "\u2660",
"&spadesuit;": "\u2660",
"&spar;": "\u2225",
"&sqcap;": "\u2293",
"&sqcaps;": "\u2293\uFE00",
"&sqcup;": "\u2294",
"&sqcups;": "\u2294\uFE00",
"&sqsub;": "\u228F",
"&sqsube;": "\u2291",
"&sqsubset;": "\u228F",
"&sqsubseteq;": "\u2291",
"&sqsup;": "\u2290",
"&sqsupe;": "\u2292",
"&sqsupset;": "\u2290",
"&sqsupseteq;": "\u2292",
"&squ;": "\u25A1",
"&square;": "\u25A1",
"&squarf;": "\u25AA",
"&squf;": "\u25AA",
"&srarr;": "\u2192",
"&sscr;": "\u{1D4C8}",
"&ssetmn;": "\u2216",
"&ssmile;": "\u2323",
"&sstarf;": "\u22C6",
"&star;": "\u2606",
"&starf;": "\u2605",
"&straightepsilon;": "\u03F5",
"&straightphi;": "\u03D5",
"&strns;": "\xAF",
"&sub;": "\u2282",
"&subE;": "\u2AC5",
"&subdot;": "\u2ABD",
"&sube;": "\u2286",
"&subedot;": "\u2AC3",
"&submult;": "\u2AC1",
"&subnE;": "\u2ACB",
"&subne;": "\u228A",
"&subplus;": "\u2ABF",
"&subrarr;": "\u2979",
"&subset;": "\u2282",
"&subseteq;": "\u2286",
"&subseteqq;": "\u2AC5",
"&subsetneq;": "\u228A",
"&subsetneqq;": "\u2ACB",
"&subsim;": "\u2AC7",
"&subsub;": "\u2AD5",
"&subsup;": "\u2AD3",
"&succ;": "\u227B",
"&succapprox;": "\u2AB8",
"&succcurlyeq;": "\u227D",
"&succeq;": "\u2AB0",
"&succnapprox;": "\u2ABA",
"&succneqq;": "\u2AB6",
"&succnsim;": "\u22E9",
"&succsim;": "\u227F",
"&sum;": "\u2211",
"&sung;": "\u266A",
"&sup1": "\xB9",
"&sup1;": "\xB9",
"&sup2": "\xB2",
"&sup2;": "\xB2",
"&sup3": "\xB3",
"&sup3;": "\xB3",
"&sup;": "\u2283",
"&supE;": "\u2AC6",
"&supdot;": "\u2ABE",
"&supdsub;": "\u2AD8",
"&supe;": "\u2287",
"&supedot;": "\u2AC4",
"&suphsol;": "\u27C9",
"&suphsub;": "\u2AD7",
"&suplarr;": "\u297B",
"&supmult;": "\u2AC2",
"&supnE;": "\u2ACC",
"&supne;": "\u228B",
"&supplus;": "\u2AC0",
"&supset;": "\u2283",
"&supseteq;": "\u2287",
"&supseteqq;": "\u2AC6",
"&supsetneq;": "\u228B",
"&supsetneqq;": "\u2ACC",
"&supsim;": "\u2AC8",
"&supsub;": "\u2AD4",
"&supsup;": "\u2AD6",
"&swArr;": "\u21D9",
"&swarhk;": "\u2926",
"&swarr;": "\u2199",
"&swarrow;": "\u2199",
"&swnwar;": "\u292A",
"&szlig": "\xDF",
"&szlig;": "\xDF",
"&target;": "\u2316",
"&tau;": "\u03C4",
"&tbrk;": "\u23B4",
"&tcaron;": "\u0165",
"&tcedil;": "\u0163",
"&tcy;": "\u0442",
"&tdot;": "\u20DB",
"&telrec;": "\u2315",
"&tfr;": "\u{1D531}",
"&there4;": "\u2234",
"&therefore;": "\u2234",
"&theta;": "\u03B8",
"&thetasym;": "\u03D1",
"&thetav;": "\u03D1",
"&thickapprox;": "\u2248",
"&thicksim;": "\u223C",
"&thinsp;": "\u2009",
"&thkap;": "\u2248",
"&thksim;": "\u223C",
"&thorn": "\xFE",
"&thorn;": "\xFE",
"&tilde;": "\u02DC",
"&times": "\xD7",
"&times;": "\xD7",
"&timesb;": "\u22A0",
"&timesbar;": "\u2A31",
"&timesd;": "\u2A30",
"&tint;": "\u222D",
"&toea;": "\u2928",
"&top;": "\u22A4",
"&topbot;": "\u2336",
"&topcir;": "\u2AF1",
"&topf;": "\u{1D565}",
"&topfork;": "\u2ADA",
"&tosa;": "\u2929",
"&tprime;": "\u2034",
"&trade;": "\u2122",
"&triangle;": "\u25B5",
"&triangledown;": "\u25BF",
"&triangleleft;": "\u25C3",
"&trianglelefteq;": "\u22B4",
"&triangleq;": "\u225C",
"&triangleright;": "\u25B9",
"&trianglerighteq;": "\u22B5",
"&tridot;": "\u25EC",
"&trie;": "\u225C",
"&triminus;": "\u2A3A",
"&triplus;": "\u2A39",
"&trisb;": "\u29CD",
"&tritime;": "\u2A3B",
"&trpezium;": "\u23E2",
"&tscr;": "\u{1D4C9}",
"&tscy;": "\u0446",
"&tshcy;": "\u045B",
"&tstrok;": "\u0167",
"&twixt;": "\u226C",
"&twoheadleftarrow;": "\u219E",
"&twoheadrightarrow;": "\u21A0",
"&uArr;": "\u21D1",
"&uHar;": "\u2963",
"&uacute": "\xFA",
"&uacute;": "\xFA",
"&uarr;": "\u2191",
"&ubrcy;": "\u045E",
"&ubreve;": "\u016D",
"&ucirc": "\xFB",
"&ucirc;": "\xFB",
"&ucy;": "\u0443",
"&udarr;": "\u21C5",
"&udblac;": "\u0171",
"&udhar;": "\u296E",
"&ufisht;": "\u297E",
"&ufr;": "\u{1D532}",
"&ugrave": "\xF9",
"&ugrave;": "\xF9",
"&uharl;": "\u21BF",
"&uharr;": "\u21BE",
"&uhblk;": "\u2580",
"&ulcorn;": "\u231C",
"&ulcorner;": "\u231C",
"&ulcrop;": "\u230F",
"&ultri;": "\u25F8",
"&umacr;": "\u016B",
"&uml": "\xA8",
"&uml;": "\xA8",
"&uogon;": "\u0173",
"&uopf;": "\u{1D566}",
"&uparrow;": "\u2191",
"&updownarrow;": "\u2195",
"&upharpoonleft;": "\u21BF",
"&upharpoonright;": "\u21BE",
"&uplus;": "\u228E",
"&upsi;": "\u03C5",
"&upsih;": "\u03D2",
"&upsilon;": "\u03C5",
"&upuparrows;": "\u21C8",
"&urcorn;": "\u231D",
"&urcorner;": "\u231D",
"&urcrop;": "\u230E",
"&uring;": "\u016F",
"&urtri;": "\u25F9",
"&uscr;": "\u{1D4CA}",
"&utdot;": "\u22F0",
"&utilde;": "\u0169",
"&utri;": "\u25B5",
"&utrif;": "\u25B4",
"&uuarr;": "\u21C8",
"&uuml": "\xFC",
"&uuml;": "\xFC",
"&uwangle;": "\u29A7",
"&vArr;": "\u21D5",
"&vBar;": "\u2AE8",
"&vBarv;": "\u2AE9",
"&vDash;": "\u22A8",
"&vangrt;": "\u299C",
"&varepsilon;": "\u03F5",
"&varkappa;": "\u03F0",
"&varnothing;": "\u2205",
"&varphi;": "\u03D5",
"&varpi;": "\u03D6",
"&varpropto;": "\u221D",
"&varr;": "\u2195",
"&varrho;": "\u03F1",
"&varsigma;": "\u03C2",
"&varsubsetneq;": "\u228A\uFE00",
"&varsubsetneqq;": "\u2ACB\uFE00",
"&varsupsetneq;": "\u228B\uFE00",
"&varsupsetneqq;": "\u2ACC\uFE00",
"&vartheta;": "\u03D1",
"&vartriangleleft;": "\u22B2",
"&vartriangleright;": "\u22B3",
"&vcy;": "\u0432",
"&vdash;": "\u22A2",
"&vee;": "\u2228",
"&veebar;": "\u22BB",
"&veeeq;": "\u225A",
"&vellip;": "\u22EE",
"&verbar;": "|",
"&vert;": "|",
"&vfr;": "\u{1D533}",
"&vltri;": "\u22B2",
"&vnsub;": "\u2282\u20D2",
"&vnsup;": "\u2283\u20D2",
"&vopf;": "\u{1D567}",
"&vprop;": "\u221D",
"&vrtri;": "\u22B3",
"&vscr;": "\u{1D4CB}",
"&vsubnE;": "\u2ACB\uFE00",
"&vsubne;": "\u228A\uFE00",
"&vsupnE;": "\u2ACC\uFE00",
"&vsupne;": "\u228B\uFE00",
"&vzigzag;": "\u299A",
"&wcirc;": "\u0175",
"&wedbar;": "\u2A5F",
"&wedge;": "\u2227",
"&wedgeq;": "\u2259",
"&weierp;": "\u2118",
"&wfr;": "\u{1D534}",
"&wopf;": "\u{1D568}",
"&wp;": "\u2118",
"&wr;": "\u2240",
"&wreath;": "\u2240",
"&wscr;": "\u{1D4CC}",
"&xcap;": "\u22C2",
"&xcirc;": "\u25EF",
"&xcup;": "\u22C3",
"&xdtri;": "\u25BD",
"&xfr;": "\u{1D535}",
"&xhArr;": "\u27FA",
"&xharr;": "\u27F7",
"&xi;": "\u03BE",
"&xlArr;": "\u27F8",
"&xlarr;": "\u27F5",
"&xmap;": "\u27FC",
"&xnis;": "\u22FB",
"&xodot;": "\u2A00",
"&xopf;": "\u{1D569}",
"&xoplus;": "\u2A01",
"&xotime;": "\u2A02",
"&xrArr;": "\u27F9",
"&xrarr;": "\u27F6",
"&xscr;": "\u{1D4CD}",
"&xsqcup;": "\u2A06",
"&xuplus;": "\u2A04",
"&xutri;": "\u25B3",
"&xvee;": "\u22C1",
"&xwedge;": "\u22C0",
"&yacute": "\xFD",
"&yacute;": "\xFD",
"&yacy;": "\u044F",
"&ycirc;": "\u0177",
"&ycy;": "\u044B",
"&yen": "\xA5",
"&yen;": "\xA5",
"&yfr;": "\u{1D536}",
"&yicy;": "\u0457",
"&yopf;": "\u{1D56A}",
"&yscr;": "\u{1D4CE}",
"&yucy;": "\u044E",
"&yuml": "\xFF",
"&yuml;": "\xFF",
"&zacute;": "\u017A",
"&zcaron;": "\u017E",
"&zcy;": "\u0437",
"&zdot;": "\u017C",
"&zeetrf;": "\u2128",
"&zeta;": "\u03B6",
"&zfr;": "\u{1D537}",
"&zhcy;": "\u0436",
"&zigrarr;": "\u21DD",
"&zopf;": "\u{1D56B}",
"&zscr;": "\u{1D4CF}",
"&zwj;": "\u200D",
"&zwnj;": "\u200C",
};
var html_entities_default = htmlEntities;
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/text-format.js
function decodeHTMLEntities(str) {
return str.replace(/&(#\d+|#x[a-f0-9]+|[a-z]+\d*);?/gi, (match, entity) => {
if (typeof html_entities_default[match] === "string") {
return html_entities_default[match];
}
if (entity.charAt(0) !== "#" || match.charAt(match.length - 1) !== ";") {
return match;
}
let codePoint;
if (entity.charAt(1) === "x") {
codePoint = parseInt(entity.substr(2), 16);
} else {
codePoint = parseInt(entity.substr(1), 10);
}
var output = "";
if ((codePoint >= 55296 && codePoint <= 57343) || codePoint > 1114111) {
return "\uFFFD";
}
if (codePoint > 65535) {
codePoint -= 65536;
output += String.fromCharCode(((codePoint >>> 10) & 1023) | 55296);
codePoint = 56320 | (codePoint & 1023);
}
output += String.fromCharCode(codePoint);
return output;
});
}
function escapeHtml(str) {
return str.trim().replace(/[<>"'?&]/g, (c2) => {
let hex = c2.charCodeAt(0).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return "&#x" + hex.toUpperCase() + ";";
});
}
function textToHtml(str) {
let html = escapeHtml(str).replace(/\n/g, "<br />");
return "<div>" + html + "</div>";
}
function htmlToText(str) {
str = str
.replace(/\r?\n/g, "")
.replace(/<\!\-\-.*?\-\->/gi, " ")
.replace(/<br\b[^>]*>/gi, "\n")
.replace(/<\/?(p|div|table|tr|td|th)\b[^>]*>/gi, "\n\n")
.replace(/<script\b[^>]*>.*?<\/script\b[^>]*>/gi, " ")
.replace(/^.*<body\b[^>]*>/i, "")
.replace(/^.*<\/head\b[^>]*>/i, "")
.replace(/^.*<\!doctype\b[^>]*>/i, "")
.replace(/<\/body\b[^>]*>.*$/i, "")
.replace(/<\/html\b[^>]*>.*$/i, "")
.replace(/<a\b[^>]*href\s*=\s*["']?([^\s"']+)[^>]*>/gi, " ($1) ")
.replace(/<\/?(span|em|i|strong|b|u|a)\b[^>]*>/gi, "")
.replace(/<li\b[^>]*>[\n\u0001\s]*/gi, "* ")
.replace(/<hr\b[^>]*>/g, "\n-------------\n")
.replace(/<[^>]*>/g, " ")
.replace(/\u0001/g, "\n")
.replace(/[ \t]+/g, " ")
.replace(/^\s+$/gm, "")
.replace(/\n\n+/g, "\n\n")
.replace(/^\n+/, "\n")
.replace(/\n+$/, "\n");
str = decodeHTMLEntities(str);
return str;
}
function formatTextAddress(address) {
return []
.concat(address.name || [])
.concat(address.name ? `<${address.address}>` : address.address)
.join(" ");
}
function formatTextAddresses(addresses) {
let parts = [];
let processAddress = (address, partCounter) => {
if (partCounter) {
parts.push(", ");
}
if (address.group) {
let groupStart = `${address.name}:`;
let groupEnd = `;`;
parts.push(groupStart);
address.group.forEach(processAddress);
parts.push(groupEnd);
} else {
parts.push(formatTextAddress(address));
}
};
addresses.forEach(processAddress);
return parts.join("");
}
function formatHtmlAddress(address) {
return `<a href="mailto:${escapeHtml(address.address)}" class="postal-email-address">${escapeHtml(address.name || `<${address.address}>`)}</a>`;
}
function formatHtmlAddresses(addresses) {
let parts = [];
let processAddress = (address, partCounter) => {
if (partCounter) {
parts.push('<span class="postal-email-address-separator">, </span>');
}
if (address.group) {
let groupStart = `<span class="postal-email-address-group">${escapeHtml(address.name)}:</span>`;
let groupEnd = `<span class="postal-email-address-group">;</span>`;
parts.push(groupStart);
address.group.forEach(processAddress);
parts.push(groupEnd);
} else {
parts.push(formatHtmlAddress(address));
}
};
addresses.forEach(processAddress);
return parts.join(" ");
}
function foldLines(str, lineLength, afterSpace) {
str = (str || "").toString();
lineLength = lineLength || 76;
let pos = 0,
len = str.length,
result = "",
line,
match;
while (pos < len) {
line = str.substr(pos, lineLength);
if (line.length < lineLength) {
result += line;
break;
}
if ((match = line.match(/^[^\n\r]*(\r?\n|\r)/))) {
line = match[0];
result += line;
pos += line.length;
continue;
} else if (
(match = line.match(/(\s+)[^\s]*$/)) &&
match[0].length - (afterSpace ? (match[1] || "").length : 0) < line.length
) {
line = line.substr(
0,
line.length -
(match[0].length - (afterSpace ? (match[1] || "").length : 0))
);
} else if ((match = str.substr(pos + line.length).match(/^[^\s]+(\s*)/))) {
line =
line +
match[0].substr(
0,
match[0].length - (!afterSpace ? (match[1] || "").length : 0)
);
}
result += line;
pos += line.length;
if (pos < len) {
result += "\r\n";
}
}
return result;
}
function formatTextHeader(message) {
let rows = [];
if (message.from) {
rows.push({ key: "From", val: formatTextAddress(message.from) });
}
if (message.subject) {
rows.push({ key: "Subject", val: message.subject });
}
if (message.date) {
let dateOptions = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
};
let dateStr =
typeof Intl === "undefined"
? message.date
: new Intl.DateTimeFormat("default", dateOptions).format(
new Date(message.date)
);
rows.push({ key: "Date", val: dateStr });
}
if (message.to && message.to.length) {
rows.push({ key: "To", val: formatTextAddresses(message.to) });
}
if (message.cc && message.cc.length) {
rows.push({ key: "Cc", val: formatTextAddresses(message.cc) });
}
if (message.bcc && message.bcc.length) {
rows.push({ key: "Bcc", val: formatTextAddresses(message.bcc) });
}
let maxKeyLength = rows
.map((r) => r.key.length)
.reduce((acc, cur) => {
return cur > acc ? cur : acc;
}, 0);
rows = rows.flatMap((row) => {
let sepLen = maxKeyLength - row.key.length;
let prefix = `${row.key}: ${" ".repeat(sepLen)}`;
let emptyPrefix = `${" ".repeat(row.key.length + 1)} ${" ".repeat(sepLen)}`;
let foldedLines = foldLines(row.val, 80, true)
.split(/\r?\n/)
.map((line) => line.trim());
return foldedLines.map((line, i) => `${i ? emptyPrefix : prefix}${line}`);
});
let maxLineLength = rows
.map((r) => r.length)
.reduce((acc, cur) => {
return cur > acc ? cur : acc;
}, 0);
let lineMarker = "-".repeat(maxLineLength);
let template = `
${lineMarker}
${rows.join("\n")}
${lineMarker}
`;
return template;
}
function formatHtmlHeader(message) {
let rows = [];
if (message.from) {
rows.push(
`<div class="postal-email-header-key">From</div><div class="postal-email-header-value">${formatHtmlAddress(message.from)}</div>`
);
}
if (message.subject) {
rows.push(
`<div class="postal-email-header-key">Subject</div><div class="postal-email-header-value postal-email-header-subject">${escapeHtml(
message.subject
)}</div>`
);
}
if (message.date) {
let dateOptions = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
};
let dateStr =
typeof Intl === "undefined"
? message.date
: new Intl.DateTimeFormat("default", dateOptions).format(
new Date(message.date)
);
rows.push(
`<div class="postal-email-header-key">Date</div><div class="postal-email-header-value postal-email-header-date" data-date="${escapeHtml(
message.date
)}">${escapeHtml(dateStr)}</div>`
);
}
if (message.to && message.to.length) {
rows.push(
`<div class="postal-email-header-key">To</div><div class="postal-email-header-value">${formatHtmlAddresses(message.to)}</div>`
);
}
if (message.cc && message.cc.length) {
rows.push(
`<div class="postal-email-header-key">Cc</div><div class="postal-email-header-value">${formatHtmlAddresses(message.cc)}</div>`
);
}
if (message.bcc && message.bcc.length) {
rows.push(
`<div class="postal-email-header-key">Bcc</div><div class="postal-email-header-value">${formatHtmlAddresses(message.bcc)}</div>`
);
}
let template = `<div class="postal-email-header">${rows.length ? '<div class="postal-email-header-row">' : ""}${rows.join(
'</div>\n<div class="postal-email-header-row">'
)}${rows.length ? "</div>" : ""}</div>`;
return template;
}
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/address-parser.js
function _handleAddress(tokens) {
let token;
let isGroup = false;
let state = "text";
let address;
let addresses = [];
let data = {
address: [],
comment: [],
group: [],
text: [],
};
let i;
let len;
for (i = 0, len = tokens.length; i < len; i++) {
token = tokens[i];
if (token.type === "operator") {
switch (token.value) {
case "<":
state = "address";
break;
case "(":
state = "comment";
break;
case ":":
state = "group";
isGroup = true;
break;
default:
state = "text";
}
} else if (token.value) {
if (state === "address") {
token.value = token.value.replace(/^[^<]*<\s*/, "");
}
data[state].push(token.value);
}
}
if (!data.text.length && data.comment.length) {
data.text = data.comment;
data.comment = [];
}
if (isGroup) {
data.text = data.text.join(" ");
addresses.push({
name: decodeWords(data.text || (address && address.name)),
group: data.group.length ? addressParser(data.group.join(",")) : [],
});
} else {
if (!data.address.length && data.text.length) {
for (i = data.text.length - 1; i >= 0; i--) {
if (data.text[i].match(/^[^@\s]+@[^@\s]+$/)) {
data.address = data.text.splice(i, 1);
break;
}
}
let _regexHandler = function (address2) {
if (!data.address.length) {
data.address = [address2.trim()];
return " ";
} else {
return address2;
}
};
if (!data.address.length) {
for (i = data.text.length - 1; i >= 0; i--) {
data.text[i] = data.text[i]
.replace(/\s*\b[^@\s]+@[^\s]+\b\s*/, _regexHandler)
.trim();
if (data.address.length) {
break;
}
}
}
}
if (!data.text.length && data.comment.length) {
data.text = data.comment;
data.comment = [];
}
if (data.address.length > 1) {
data.text = data.text.concat(data.address.splice(1));
}
data.text = data.text.join(" ");
data.address = data.address.join(" ");
if (!data.address && /^=\?[^=]+?=$/.test(data.text.trim())) {
const parsedSubAddresses = addressParser(decodeWords(data.text));
if (parsedSubAddresses && parsedSubAddresses.length) {
return parsedSubAddresses;
}
}
if (!data.address && isGroup) {
return [];
} else {
address = {
address: data.address || data.text || "",
name: decodeWords(data.text || data.address || ""),
};
if (address.address === address.name) {
if ((address.address || "").match(/@/)) {
address.name = "";
} else {
address.address = "";
}
}
addresses.push(address);
}
}
return addresses;
}
var Tokenizer = class {
constructor(str) {
this.str = (str || "").toString();
this.operatorCurrent = "";
this.operatorExpecting = "";
this.node = null;
this.escaped = false;
this.list = [];
this.operators = {
'"': '"',
"(": ")",
"<": ">",
",": "",
":": ";",
// Semicolons are not a legal delimiter per the RFC2822 grammar other
// than for terminating a group, but they are also not valid for any
// other use in this context. Given that some mail clients have
// historically allowed the semicolon as a delimiter equivalent to the
// comma in their UI, it makes sense to treat them the same as a comma
// when used outside of a group.
";": "",
};
}
/**
* Tokenizes the original input string
*
* @return {Array} An array of operator|text tokens
*/
tokenize() {
let chr,
list = [];
for (let i = 0, len = this.str.length; i < len; i++) {
chr = this.str.charAt(i);
this.checkChar(chr);
}
this.list.forEach((node) => {
node.value = (node.value || "").toString().trim();
if (node.value) {
list.push(node);
}
});
return list;
}
/**
* Checks if a character is an operator or text and acts accordingly
*
* @param {String} chr Character from the address field
*/
checkChar(chr) {
if (this.escaped) {
} else if (chr === this.operatorExpecting) {
this.node = {
type: "operator",
value: chr,
};
this.list.push(this.node);
this.node = null;
this.operatorExpecting = "";
this.escaped = false;
return;
} else if (!this.operatorExpecting && chr in this.operators) {
this.node = {
type: "operator",
value: chr,
};
this.list.push(this.node);
this.node = null;
this.operatorExpecting = this.operators[chr];
this.escaped = false;
return;
} else if (['"', "'"].includes(this.operatorExpecting) && chr === "\\") {
this.escaped = true;
return;
}
if (!this.node) {
this.node = {
type: "text",
value: "",
};
this.list.push(this.node);
}
if (chr === "\n") {
chr = " ";
}
if (chr.charCodeAt(0) >= 33 || [" ", " "].includes(chr)) {
this.node.value += chr;
}
this.escaped = false;
}
};
function addressParser(str, options) {
options = options || {};
let tokenizer = new Tokenizer(str);
let tokens = tokenizer.tokenize();
let addresses = [];
let address = [];
let parsedAddresses = [];
tokens.forEach((token) => {
if (
token.type === "operator" &&
(token.value === "," || token.value === ";")
) {
if (address.length) {
addresses.push(address);
}
address = [];
} else {
address.push(token);
}
});
if (address.length) {
addresses.push(address);
}
addresses.forEach((address2) => {
address2 = _handleAddress(address2);
if (address2.length) {
parsedAddresses = parsedAddresses.concat(address2);
}
});
if (options.flatten) {
let addresses2 = [];
let walkAddressList = (list) => {
list.forEach((address2) => {
if (address2.group) {
return walkAddressList(address2.group);
} else {
addresses2.push(address2);
}
});
};
walkAddressList(parsedAddresses);
return addresses2;
}
return parsedAddresses;
}
var address_parser_default = addressParser;
// ../../node_modules/.pnpm/postal-mime@2.0.2/node_modules/postal-mime/src/postal-mime.js
var PostalMime = class {
constructor() {
this.root = this.currentNode = new MimeNode({
postalMime: this,
});
this.boundaries = [];
this.textContent = {};
this.attachments = [];
this.started = false;
}
async finalize() {
await this.root.finalize();
}
async processLine(line, isFinal) {
let boundaries = this.boundaries;
if (
boundaries.length &&
line.length > 2 &&
line[0] === 45 &&
line[1] === 45
) {
for (let i = boundaries.length - 1; i >= 0; i--) {
let boundary = boundaries[i];
if (
line.length !== boundary.value.length + 2 &&
line.length !== boundary.value.length + 4
) {
continue;
}
let isTerminator = line.length === boundary.value.length + 4;
if (
isTerminator &&
(line[line.length - 2] !== 45 || line[line.length - 1] !== 45)
) {
continue;
}
let boudaryMatches = true;
for (let i2 = 0; i2 < boundary.value.length; i2++) {
if (line[i2 + 2] !== boundary.value[i2]) {
boudaryMatches = false;
break;
}
}
if (!boudaryMatches) {
continue;
}
if (isTerminator) {
await boundary.node.finalize();
this.currentNode = boundary.node.parentNode || this.root;
} else {
await boundary.node.finalizeChildNodes();
this.currentNode = new MimeNode({
postalMime: this,
parentNode: boundary.node,
});
}
if (isFinal) {
return this.finalize();
}
return;
}
}
this.currentNode.feed(line);
if (isFinal) {
return this.finalize();
}
}
readLine() {
let startPos = this.readPos;
let endPos = this.readPos;
let res = () => {
return {
bytes: new Uint8Array(this.buf, startPos, endPos - startPos),
done: this.readPos >= this.av.length,
};
};
while (this.readPos < this.av.length) {
const c2 = this.av[this.readPos++];
if (c2 !== 13 && c2 !== 10) {
endPos = this.readPos;
}
if (c2 === 10) {
return res();
}
}
return res();
}
async processNodeTree() {
let textContent = {};
let textTypes = /* @__PURE__ */ new Set();
let textMap = (this.textMap = /* @__PURE__ */ new Map());
let walk = async (node, alternative, related) => {
alternative = alternative || false;
related = related || false;
if (!node.contentType.multipart) {
if (
node.contentType.parsed.value === "message/rfc822" &&
node.contentDisposition.parsed.value !== "attachment"
) {
const subParser = new PostalMime();
node.subMessage = await subParser.parse(node.content);
if (!textMap.has(node)) {
textMap.set(node, {});
}
let textEntry = textMap.get(node);
if (node.subMessage.text || !node.subMessage.html) {
textEntry.plain = textEntry.plain || [];
textEntry.plain.push({
type: "subMessage",
value: node.subMessage,
});
textTypes.add("plain");
}
if (node.subMessage.html) {
textEntry.html = textEntry.html || [];
textEntry.html.push({ type: "subMessage", value: node.subMessage });
textTypes.add("html");
}
if (subParser.textMap) {
subParser.textMap.forEach((subTextEntry, subTextNode) => {
textMap.set(subTextNode, subTextEntry);
});
}
for (let attachment of node.subMessage.attachments || []) {
this.attachments.push(attachment);
}
} else if (
(/^text\//i.test(node.contentType.parsed.value) ||
node.contentType.parsed.value === "message/delivery-status") &&
node.contentDisposition.parsed.value !== "attachment"
) {
let textType = node.contentType.parsed.value.substr(
node.contentType.parsed.value.indexOf("/") + 1
);
if (node.contentType.parsed.value === "message/delivery-status") {
textType = "plain";
}
let selectorNode = alternative || node;
if (!textMap.has(selectorNode)) {
textMap.set(selectorNode, {});
}
let textEntry = textMap.get(selectorNode);
textEntry[textType] = textEntry[textType] || [];
textEntry[textType].push({
type: "text",
value: node.getTextContent(),
});
textTypes.add(textType);
} else if (node.content) {
let filename =
node.contentDisposition.parsed.params.filename ||
node.contentType.parsed.params.name ||
null;
let attachment = {
filename: decodeWords(filename),
mimeType: node.contentType.parsed.value,
disposition: node.contentDisposition.parsed.value || null,
};
if (related && node.contentId) {
attachment.related = true;
}
if (node.contentId) {
attachment.contentId = node.contentId;
}
attachment.content = node.content;
this.attachments.push(attachment);
}
} else if (node.contentType.multipart === "alternative") {
alternative = node;
} else if (node.contentType.multipart === "related") {
related = node;
}
for (let childNode of node.childNodes) {
await walk(childNode, alternative, related);
}
};
await walk(this.root, false, []);
textMap.forEach((mapEntry) => {
textTypes.forEach((textType) => {
if (!textContent[textType]) {
textContent[textType] = [];
}
if (mapEntry[textType]) {
mapEntry[textType].forEach((textEntry) => {
switch (textEntry.type) {
case "text":
textContent[textType].push(textEntry.value);
break;
case "subMessage":
{
switch (textType) {
case "html":
textContent[textType].push(
formatHtmlHeader(textEntry.value)
);
break;
case "plain":
textContent[textType].push(
formatTextHeader(textEntry.value)
);
break;
}
}
break;
}
});
} else {
let alternativeType;
switch (textType) {
case "html":
alternativeType = "plain";
break;
case "plain":
alternativeType = "html";
break;
}
(mapEntry[alternativeType] || []).forEach((textEntry) => {
switch (textEntry.type) {
case "text":
switch (textType) {
case "html":
textContent[textType].push(textToHtml(textEntry.value));
break;
case "plain":
textContent[textType].push(htmlToText(textEntry.value));
break;
}
break;
case "subMessage":
{
switch (textType) {
case "html":
textContent[textType].push(
formatHtmlHeader(textEntry.value)
);
break;
case "plain":
textContent[textType].push(
formatTextHeader(textEntry.value)
);
break;
}
}
break;
}
});
}
});
});
Object.keys(textContent).forEach((textType) => {
textContent[textType] = textContent[textType].join("\n");
});
this.textContent = textContent;
}
async parse(buf) {
if (this.started) {
throw new Error("Can not reuse parser, create a new PostalMime object");
}
this.started = true;
buf = buf || ArrayBuffer(0);
if (typeof buf === "string") {
buf = textEncoder.encode(buf);
}
if (
buf instanceof Blob ||
Object.prototype.toString.call(buf) === "[object Blob]"
) {
buf = await blobToArrayBuffer(buf);
}
if (buf.buffer instanceof ArrayBuffer) {
buf = new Uint8Array(buf).buffer;
}
this.buf = buf;
this.av = new Uint8Array(buf);
this.readPos = 0;
while (this.readPos < this.av.length) {
const line = this.readLine();
await this.processLine(line.bytes, line.done);
}
await this.processNodeTree();
let message = {
headers: this.root.headers
.map((entry) => ({ key: entry.key, value: entry.value }))
.reverse(),
};
for (let key of ["from", "sender", "reply-to"]) {
let addressHeader = this.root.headers.find((line) => line.key === key);
if (addressHeader && addressHeader.value) {
let addresses = address_parser_default(addressHeader.value);
if (addresses && addresses.length) {
message[key.replace(/\-(.)/g, (o, c2) => c2.toUpperCase())] =
addresses[0];
}
}
}
for (let key of ["delivered-to", "return-path"]) {
let addressHeader = this.root.headers.find((line) => line.key === key);
if (addressHeader && addressHeader.value) {
let addresses = address_parser_default(addressHeader.value);
if (addresses && addresses.length && addresses[0].address) {
message[key.replace(/\-(.)/g, (o, c2) => c2.toUpperCase())] =
addresses[0].address;
}
}
}
for (let key of ["to", "cc", "bcc"]) {
let addressHeaders = this.root.headers.filter((line) => line.key === key);
let addresses = [];
addressHeaders
.filter((entry) => entry && entry.value)
.map((entry) => address_parser_default(entry.value))
.forEach((parsed) => (addresses = addresses.concat(parsed || [])));
if (addresses && addresses.length) {
message[key] = addresses;
}
}
for (let key of ["subject", "message-id", "in-reply-to", "references"]) {
let header = this.root.headers.find((line) => line.key === key);
if (header && header.value) {
message[key.replace(/\-(.)/g, (o, c2) => c2.toUpperCase())] =
decodeWords(header.value);
}
}
let dateHeader = this.root.headers.find((line) => line.key === "date");
if (dateHeader) {
let date = new Date(dateHeader.value);
if (!date || date.toString() === "Invalid Date") {
date = dateHeader.value;
} else {
date = date.toISOString();
}
message.date = date;
}
if (this.textContent && this.textContent.html) {
message.html = this.textContent.html;
}
if (this.textContent && this.textContent.plain) {
message.text = this.textContent.plain;
}
message.attachments = this.attachments;
return message;
}
};
// src/index.ts
var src_default = {
async email(message, env, ctx) {
try {
const messageFrom = message.from;
const messageTo = message.to;
const rawText = await new Response(message.raw).text();
const mail = await new PostalMime().parse(rawText);
const now = /* @__PURE__ */ new Date();
const db = getWebTursoDB(env.TURSO_DB_URL, env.TURSO_DB_AUTH_TOKEN);
const newEmail = {
id: nanoid(),
messageFrom,
messageTo,
...mail,
createdAt: now,
updatedAt: now,
};
const email = insertEmailSchema.parse(newEmail);
await insertEmail(db, email);
} catch (e) {
console.log(e);
}
},
};
export { src_default as default };
//# sourceMappingURL=index.js.map