sv
Version:
A CLI for creating and updating SvelteKit projects
5,723 lines • 229 kB
JavaScript
import { Element, T, Tag, __commonJS, __export, __toESM as __toESM$1, __toESM$1 as __toESM, be, detect, esm_exports, getUserAgent, parseCss$1, parseHtml, parseHtml$1, parseJson$1, parseScript, parseScript$1, parseSvelte, require_picocolors as require_picocolors$1, require_picocolors$1 as require_picocolors, resolveCommand, serializeScript, stripAst, up, walk, walk_exports } from "./package-manager-DO5R9a6p.js";
import fs, { existsSync, lstatSync, readdirSync } from "node:fs";
import path, { dirname, join } from "node:path";
import process$1, { stdin, stdout } from "node:process";
import * as _ from "node:readline";
import Eu from "node:readline";
import { ReadStream, WriteStream } from "node:tty";
import { stripVTControlCharacters } from "node:util";
//#region packages/cli/utils/env.ts
const TESTING = process$1.env.NODE_ENV?.toLowerCase() === "test";
//#endregion
//#region packages/core/dist/dedent-DwrHTfuc.js
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
const dedent = createDedent({});
var dedent_default = dedent;
function createDedent(options$6) {
dedent$1.withOptions = (newOptions) => createDedent(_objectSpread(_objectSpread({}, options$6), newOptions));
return dedent$1;
function dedent$1(strings, ...values) {
const raw = typeof strings === "string" ? [strings] : strings.raw;
const { escapeSpecialCharacters = Array.isArray(strings), trimWhitespace = true } = options$6;
let result = "";
for (let i = 0; i < raw.length; i++) {
let next = raw[i];
if (escapeSpecialCharacters) next = next.replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{");
result += next;
if (i < values.length) result += values[i];
}
const lines = result.split("\n");
let mindent = null;
for (const l of lines) {
const m$1 = l.match(/^(\s+)\S+/);
if (m$1) {
const indent = m$1[1].length;
if (!mindent) mindent = indent;
else mindent = Math.min(mindent, indent);
}
}
if (mindent !== null) {
const m$1 = mindent;
result = lines.map((l) => l[0] === " " || l[0] === " " ? l.slice(m$1) : l).join("\n");
}
if (trimWhitespace) result = result.trim();
if (escapeSpecialCharacters) result = result.replace(/\\n/g, "\n");
return result;
}
}
//#endregion
//#region packages/core/dist/common-D3LG2iy6.js
function decircular(object) {
const seenObjects = new WeakMap();
function internalDecircular(value, path$1 = []) {
if (!(value !== null && typeof value === "object")) return value;
const existingPath = seenObjects.get(value);
if (existingPath) return `[Circular *${existingPath.join(".")}]`;
seenObjects.set(value, path$1);
const newValue = Array.isArray(value) ? [] : {};
for (const [key2, value2] of Object.entries(value)) newValue[key2] = internalDecircular(value2, [...path$1, key2]);
seenObjects.delete(value);
return newValue;
}
return internalDecircular(object);
}
var common_exports = {};
__export(common_exports, {
addJsDocComment: () => addJsDocComment,
addJsDocTypeComment: () => addJsDocTypeComment,
appendFromString: () => appendFromString,
appendStatement: () => appendStatement,
areNodesEqual: () => areNodesEqual,
contains: () => contains,
createBlockStatement: () => createBlockStatement,
createExpressionStatement: () => createExpressionStatement,
createLiteral: () => createLiteral,
createSatisfies: () => createSatisfies,
createSpread: () => createSpread,
hasTypeProperty: () => hasTypeProperty,
parseExpression: () => parseExpression,
parseFromString: () => parseFromString,
parseStatement: () => parseStatement,
typeAnnotate: () => typeAnnotate
});
function addJsDocTypeComment(node, options$6) {
const comment = {
type: "Block",
value: `* @type {${options$6.type}} `
};
addComment(node, comment);
}
function addJsDocComment(node, options$6) {
const commentLines = [];
for (const [key, value] of Object.entries(options$6.params)) commentLines.push(`@param {${key}} ${value}`);
const comment = {
type: "Block",
value: `*\n * ${commentLines.join("\n * ")}\n `
};
addComment(node, comment);
}
function addComment(node, comment) {
node.leadingComments ??= [];
const found = node.leadingComments.find((item) => item.type === "Block" && item.value === comment.value);
if (!found) node.leadingComments.push(comment);
}
function typeAnnotate(node, options$6) {
const expression = {
type: "TSAsExpression",
expression: node,
typeAnnotation: {
type: "TSTypeReference",
typeName: {
type: "Identifier",
name: options$6.type
}
}
};
return expression;
}
function createSatisfies(node, options$6) {
const expression = {
type: "TSSatisfiesExpression",
expression: node,
typeAnnotation: {
type: "TSTypeReference",
typeName: {
type: "Identifier",
name: options$6.type
}
}
};
return expression;
}
function createSpread(argument) {
return {
type: "SpreadElement",
argument
};
}
function createLiteral(value) {
const literal = {
type: "Literal",
value: value ?? null
};
return literal;
}
function areNodesEqual(node, otherNode) {
const nodeClone = stripAst(decircular(node), ["loc", "raw"]);
const otherNodeClone = stripAst(decircular(otherNode), ["loc", "raw"]);
return serializeScript(nodeClone) === serializeScript(otherNodeClone);
}
function createBlockStatement() {
const statement = {
type: "BlockStatement",
body: []
};
return statement;
}
function createExpressionStatement(options$6) {
const statement = {
type: "ExpressionStatement",
expression: options$6.expression
};
return statement;
}
function appendFromString(node, options$6) {
const program = parseScript(dedent_default(options$6.code));
for (const childNode of program.body) node.body.push(childNode);
}
function parseExpression(code) {
const program = parseScript(dedent_default(code));
stripAst(program, ["raw"]);
const statement = program.body[0];
if (statement.type !== "ExpressionStatement") throw new Error("Code provided was not an expression");
return statement.expression;
}
function parseStatement(code) {
return parseFromString(code);
}
function parseFromString(code) {
const program = parseScript(dedent_default(code));
const statement = program.body[0];
return statement;
}
function appendStatement(node, options$6) {
if (!contains(node, options$6.statement)) node.body.push(options$6.statement);
}
function contains(node, targetNode) {
let found = false;
walk(node, null, { _(currentNode, { next, stop }) {
if (currentNode.type === targetNode.type) {
found = areNodesEqual(currentNode, targetNode);
if (found) stop();
}
next();
} });
return found;
}
function hasTypeProperty(node, options$6) {
return node.type === "TSPropertySignature" && node.key.type === "Identifier" && node.key.name === options$6.name;
}
//#endregion
//#region packages/core/dist/js.js
var array_exports = {};
__export(array_exports, {
append: () => append,
create: () => create$1,
prepend: () => prepend
});
function create$1() {
const arrayExpression = {
type: "ArrayExpression",
elements: []
};
return arrayExpression;
}
function append(node, element) {
insertElement(node, element, { insertEnd: true });
}
function prepend(node, element) {
insertElement(node, element, { insertEnd: false });
}
function insertElement(node, element, options$6) {
if (typeof element === "string") {
const existingLiterals = node.elements.filter((item) => item !== null && item.type === "Literal");
let literal = existingLiterals.find((item) => item.value === element);
if (!literal) {
literal = {
type: "Literal",
value: element
};
if (options$6.insertEnd) node.elements.push(literal);
else node.elements.unshift(literal);
}
} else {
const elements = node.elements;
const anyNodeEquals = elements.some((item) => item && areNodesEqual(element, item));
if (!anyNodeEquals) if (options$6.insertEnd) node.elements.push(element);
else node.elements.unshift(element);
}
}
var object_exports = {};
__export(object_exports, {
addProperties: () => addProperties,
create: () => create,
overrideProperties: () => overrideProperties,
overrideProperty: () => overrideProperty,
property: () => property,
removeProperty: () => removeProperty
});
function property(node, options$6) {
const properties = node.properties.filter((x$2) => x$2.type === "Property");
let prop = properties.find((x$2) => x$2.key.name === options$6.name);
let propertyValue;
if (prop) propertyValue = prop.value;
else {
let isShorthand = false;
if (options$6.fallback.type === "Identifier") {
const identifier = options$6.fallback;
isShorthand = identifier.name === options$6.name;
}
propertyValue = options$6.fallback;
prop = {
type: "Property",
shorthand: isShorthand,
key: {
type: "Identifier",
name: options$6.name
},
value: propertyValue,
kind: "init",
computed: false,
method: false
};
node.properties.push(prop);
}
return propertyValue;
}
function overrideProperty(node, options$6) {
const properties = node.properties.filter((x$2) => x$2.type === "Property");
const prop = properties.find((x$2) => x$2.key.name === options$6.name);
if (!prop) return property(node, {
name: options$6.name,
fallback: options$6.value
});
prop.value = options$6.value;
return options$6.value;
}
function overrideProperties(node, options$6) {
for (const [prop, value] of Object.entries(options$6.properties)) {
if (value === undefined) continue;
overrideProperty(node, {
name: prop,
value
});
}
}
function addProperties(node, options$6) {
for (const [prop, value] of Object.entries(options$6.properties)) {
if (value === undefined) continue;
property(node, {
name: prop,
fallback: value
});
}
}
function removeProperty(node, options$6) {
const properties = node.properties.filter((x$2) => x$2.type === "Property");
const propIdx = properties.findIndex((x$2) => x$2.key.name === options$6.name);
if (propIdx !== -1) node.properties.splice(propIdx, 1);
}
function create(properties) {
const objExpression = {
type: "ObjectExpression",
properties: []
};
const getExpression = (value) => {
let expression;
if (Array.isArray(value)) {
expression = create$1();
for (const v$2 of value) append(expression, getExpression(v$2));
} else if (typeof value === "object" && value !== null) expression = value.type !== undefined ? value : create(value);
else expression = createLiteral(value);
return expression;
};
for (const [prop, value] of Object.entries(properties)) {
if (value === undefined) continue;
property(objExpression, {
name: prop,
fallback: getExpression(value)
});
}
return objExpression;
}
var function_exports = {};
__export(function_exports, {
createArrow: () => createArrow,
createCall: () => createCall,
getArgument: () => getArgument
});
function createCall(options$6) {
const callExpression = {
type: "CallExpression",
callee: {
type: "Identifier",
name: options$6.name
},
arguments: [],
optional: false
};
for (const arg of options$6.args) {
let argNode;
if (options$6.useIdentifiers) argNode = {
type: "Identifier",
name: arg
};
else argNode = {
type: "Literal",
value: arg
};
callExpression.arguments.push(argNode);
}
return callExpression;
}
function createArrow(options$6) {
const arrowFunction = {
type: "ArrowFunctionExpression",
async: options$6.async,
body: options$6.body,
params: [],
expression: options$6.body.type !== "BlockStatement"
};
return arrowFunction;
}
function getArgument(node, options$6) {
if (options$6.index < node.arguments.length) return node.arguments[options$6.index];
node.arguments.push(options$6.fallback);
return options$6.fallback;
}
var imports_exports = {};
__export(imports_exports, {
addDefault: () => addDefault,
addEmpty: () => addEmpty,
addNamed: () => addNamed,
addNamespace: () => addNamespace
});
function addEmpty(node, options$6) {
const expectedImportDeclaration = {
type: "ImportDeclaration",
source: {
type: "Literal",
value: options$6.from
},
specifiers: [],
attributes: [],
importKind: "value"
};
addImportIfNecessary(node, expectedImportDeclaration);
}
function addNamespace(node, options$6) {
const expectedImportDeclaration = {
type: "ImportDeclaration",
importKind: "value",
source: {
type: "Literal",
value: options$6.from
},
specifiers: [{
type: "ImportNamespaceSpecifier",
local: {
type: "Identifier",
name: options$6.as
}
}],
attributes: []
};
addImportIfNecessary(node, expectedImportDeclaration);
}
function addDefault(node, options$6) {
const expectedImportDeclaration = {
type: "ImportDeclaration",
source: {
type: "Literal",
value: options$6.from
},
specifiers: [{
type: "ImportDefaultSpecifier",
local: {
type: "Identifier",
name: options$6.as
}
}],
attributes: [],
importKind: "value"
};
addImportIfNecessary(node, expectedImportDeclaration);
}
function addNamed(node, options$6) {
const o_imports = Array.isArray(options$6.imports) ? Object.fromEntries(options$6.imports.map((n$1) => [n$1, n$1])) : options$6.imports;
const specifiers = Object.entries(o_imports).map(([key, value]) => {
const specifier = {
type: "ImportSpecifier",
imported: {
type: "Identifier",
name: key
},
local: {
type: "Identifier",
name: value
}
};
return specifier;
});
let importDecl;
walk(node, null, { ImportDeclaration(declaration$1) {
if (declaration$1.source.value === options$6.from && declaration$1.specifiers) importDecl = declaration$1;
} });
if (importDecl) {
specifiers.forEach((specifierToAdd) => {
const sourceExists = importDecl?.specifiers?.every((existingSpecifier) => existingSpecifier.type === "ImportSpecifier" && existingSpecifier.local?.name !== specifierToAdd.local?.name && existingSpecifier.imported.type === "Identifier" && specifierToAdd.imported.type === "Identifier" && existingSpecifier.imported.name !== specifierToAdd.imported.name);
if (sourceExists) importDecl?.specifiers?.push(specifierToAdd);
});
return;
}
const expectedImportDeclaration = {
type: "ImportDeclaration",
source: {
type: "Literal",
value: options$6.from
},
specifiers,
attributes: [],
importKind: options$6.isType ? "type" : "value"
};
node.body.unshift(expectedImportDeclaration);
}
function addImportIfNecessary(node, expectedImportDeclaration) {
const importDeclarations = node.body.filter((item) => item.type === "ImportDeclaration");
const importDeclaration = importDeclarations.find((item) => areNodesEqual(item, expectedImportDeclaration));
if (!importDeclaration) node.body.unshift(expectedImportDeclaration);
}
var variables_exports = {};
__export(variables_exports, {
createIdentifier: () => createIdentifier,
declaration: () => declaration,
typeAnnotateDeclarator: () => typeAnnotateDeclarator
});
function declaration(node, options$6) {
const declarations = node.type === "Program" ? node.body.filter((x$2) => x$2.type === "VariableDeclaration") : [node];
let declaration$1 = declarations.find((x$2) => {
const declarator = x$2.declarations[0];
const identifier = declarator.id;
return identifier.name === options$6.name;
});
if (declaration$1) return declaration$1;
declaration$1 = {
type: "VariableDeclaration",
kind: options$6.kind,
declarations: [{
type: "VariableDeclarator",
id: {
type: "Identifier",
name: options$6.name
},
init: options$6.value
}]
};
return declaration$1;
}
function createIdentifier(name) {
const identifier = {
type: "Identifier",
name
};
return identifier;
}
function typeAnnotateDeclarator(node, options$6) {
if (node.id.type === "Identifier") node.id.typeAnnotation = {
type: "TSTypeAnnotation",
typeAnnotation: {
type: "TSTypeReference",
typeName: {
type: "Identifier",
name: options$6.typeName
}
}
};
return node;
}
var exports_exports = {};
__export(exports_exports, {
createDefault: () => createDefault,
createNamed: () => createNamed
});
function createDefault(node, options$6) {
const existingNode = node.body.find((item) => item.type === "ExportDefaultDeclaration");
if (!existingNode) {
const exportNode = {
type: "ExportDefaultDeclaration",
declaration: options$6.fallback
};
node.body.push(exportNode);
return {
astNode: exportNode,
value: options$6.fallback
};
}
const exportDefaultDeclaration = existingNode;
if (exportDefaultDeclaration.declaration.type === "Identifier") {
const identifier = exportDefaultDeclaration.declaration;
let variableDeclaration;
let variableDeclarator;
for (const declaration$2 of node.body) {
if (declaration$2.type !== "VariableDeclaration") continue;
const declarator = declaration$2.declarations.find((declarator$1) => declarator$1.type === "VariableDeclarator" && declarator$1.id.type === "Identifier" && declarator$1.id.name === identifier.name);
variableDeclarator = declarator;
variableDeclaration = declaration$2;
}
if (!variableDeclaration || !variableDeclarator) throw new Error(`Unable to find exported variable '${identifier.name}'`);
const value = variableDeclarator.init;
return {
astNode: exportDefaultDeclaration,
value
};
}
const declaration$1 = exportDefaultDeclaration.declaration;
return {
astNode: exportDefaultDeclaration,
value: declaration$1
};
}
function createNamed(node, options$6) {
const namedExports = node.body.filter((item) => item.type === "ExportNamedDeclaration");
let namedExport = namedExports.find((exportNode) => {
const variableDeclaration = exportNode.declaration;
const variableDeclarator = variableDeclaration.declarations[0];
const identifier = variableDeclarator.id;
return identifier.name === options$6.name;
});
if (namedExport) return namedExport;
namedExport = {
type: "ExportNamedDeclaration",
declaration: options$6.fallback,
specifiers: [],
attributes: []
};
node.body.push(namedExport);
return namedExport;
}
var kit_exports = {};
__export(kit_exports, {
addGlobalAppInterface: () => addGlobalAppInterface,
addHooksHandle: () => addHooksHandle
});
function addGlobalAppInterface(node, options$6) {
let globalDecl = node.body.filter((n$1) => n$1.type === "TSModuleDeclaration").find((m$1) => m$1.global && m$1.declare);
if (!globalDecl) {
globalDecl = parseFromString("declare global {}");
node.body.push(globalDecl);
}
if (globalDecl.body?.type !== "TSModuleBlock") throw new Error("Unexpected body type of `declare global` in `src/app.d.ts`");
let app;
let interfaceNode;
walk(globalDecl, null, {
TSModuleDeclaration(node$1, { next }) {
if (node$1.id.type === "Identifier" && node$1.id.name === "App") app = node$1;
next();
},
TSInterfaceDeclaration(node$1) {
if (node$1.id.type === "Identifier" && node$1.id.name === options$6.name) interfaceNode = node$1;
}
});
if (!app) {
app = parseFromString("namespace App {}");
globalDecl.body.body.push(app);
}
if (app.body?.type !== "TSModuleBlock") throw new Error("Unexpected body type of `namespace App` in `src/app.d.ts`");
if (!interfaceNode) {
interfaceNode = parseFromString(`interface ${options$6.name} {}`);
app.body.body.push(interfaceNode);
}
return interfaceNode;
}
function addHooksHandle(node, options$6) {
if (options$6.typescript) addNamed(node, {
from: "@sveltejs/kit",
imports: { Handle: "Handle" },
isType: true
});
let isSpecifier = false;
let handleName = "handle";
let exportDecl;
let originalHandleDecl;
walk(node, null, { ExportNamedDeclaration(declaration$1) {
let maybeHandleDecl;
const handleSpecifier = declaration$1.specifiers?.find((specifier) => specifier.exported.type === "Identifier" && specifier.exported.name === "handle");
if (handleSpecifier && handleSpecifier.local.type === "Identifier" && handleSpecifier.exported.type === "Identifier") {
isSpecifier = true;
handleName = handleSpecifier.local?.name ?? handleSpecifier.exported.name;
const handleFunc = node.body.find((item) => isFunctionDeclaration(item, handleName));
const handleVar = node.body.find((item) => isVariableDeclaration(item, handleName));
maybeHandleDecl = handleFunc ?? handleVar;
}
maybeHandleDecl ??= declaration$1.declaration ?? undefined;
if (maybeHandleDecl && isVariableDeclaration(maybeHandleDecl, handleName)) {
exportDecl = declaration$1;
originalHandleDecl = maybeHandleDecl;
}
if (maybeHandleDecl && isFunctionDeclaration(maybeHandleDecl, handleName)) {
exportDecl = declaration$1;
originalHandleDecl = maybeHandleDecl;
}
} });
const newHandle = parseExpression(options$6.handleContent);
if (contains(node, newHandle)) return;
if (!originalHandleDecl || !exportDecl) {
const newHandleDecl$1 = declaration(node, {
kind: "const",
name: options$6.newHandleName,
value: newHandle
});
if (options$6.typescript) {
const declarator = newHandleDecl$1.declarations[0];
typeAnnotateDeclarator(declarator, { typeName: "Handle" });
}
node.body.push(newHandleDecl$1);
const handleDecl = declaration(node, {
kind: "const",
name: handleName,
value: createIdentifier(options$6.newHandleName)
});
if (options$6.typescript) {
const declarator = handleDecl.declarations[0];
typeAnnotateDeclarator(declarator, { typeName: "Handle" });
}
createNamed(node, {
name: handleName,
fallback: handleDecl
});
return;
}
const newHandleDecl = declaration(node, {
kind: "const",
name: options$6.newHandleName,
value: newHandle
});
if (options$6.typescript) {
const declarator = newHandleDecl.declarations[0];
typeAnnotateDeclarator(declarator, { typeName: "Handle" });
}
let sequence;
if (originalHandleDecl.type === "VariableDeclaration") {
const handle = originalHandleDecl.declarations.find((declarator) => declarator.type === "VariableDeclarator" && usingSequence(declarator, handleName));
sequence = handle?.init;
}
if (sequence) {
const hasNewArg = sequence.arguments.some((arg) => arg.type === "Identifier" && arg.name === options$6.newHandleName);
if (!hasNewArg) sequence.arguments.push(createIdentifier(options$6.newHandleName));
node.body = node.body.filter((item) => item !== originalHandleDecl && item !== exportDecl && item !== newHandleDecl);
if (isSpecifier) node.body.push(newHandleDecl, originalHandleDecl, exportDecl);
else node.body.push(newHandleDecl, exportDecl);
}
const NEW_HANDLE_NAME = "originalHandle";
const sequenceCall = createCall({
name: "sequence",
args: [NEW_HANDLE_NAME, options$6.newHandleName],
useIdentifiers: true
});
const finalHandleDecl = declaration(node, {
kind: "const",
name: handleName,
value: sequenceCall
});
addNamed(node, {
from: "@sveltejs/kit/hooks",
imports: { sequence: "sequence" }
});
let renameRequired = false;
if (originalHandleDecl && isVariableDeclaration(originalHandleDecl, handleName)) {
const handle = getVariableDeclarator(originalHandleDecl, handleName);
if (handle && handle.id.type === "Identifier" && handle.init?.type !== "Identifier") {
renameRequired = true;
handle.id.name = NEW_HANDLE_NAME;
}
}
if (originalHandleDecl && isFunctionDeclaration(originalHandleDecl, handleName)) {
renameRequired = true;
originalHandleDecl.id.name = NEW_HANDLE_NAME;
}
node.body = node.body.filter((item) => item !== originalHandleDecl && item !== exportDecl && item !== newHandleDecl);
if (isSpecifier) node.body.push(originalHandleDecl, newHandleDecl, finalHandleDecl, exportDecl);
if (exportDecl.declaration && renameRequired) {
node.body.push(exportDecl.declaration, newHandleDecl);
createNamed(node, {
name: handleName,
fallback: finalHandleDecl
});
} else if (exportDecl.declaration && isVariableDeclaration(originalHandleDecl, handleName)) {
const variableDeclarator = getVariableDeclarator(originalHandleDecl, handleName);
const sequenceCall$1 = createCall({
name: "sequence",
args: [(variableDeclarator?.init).name, options$6.newHandleName],
useIdentifiers: true
});
const finalHandleDecl$1 = declaration(node, {
kind: "const",
name: handleName,
value: sequenceCall$1
});
if (options$6.typescript) {
const declarator = finalHandleDecl$1.declarations[0];
typeAnnotateDeclarator(declarator, { typeName: "Handle" });
}
node.body.push(newHandleDecl);
createNamed(node, {
name: handleName,
fallback: finalHandleDecl$1
});
}
}
function usingSequence(node, handleName) {
return node.id.type === "Identifier" && node.id.name === handleName && node.init?.type === "CallExpression" && node.init.callee.type === "Identifier" && node.init.callee.name === "sequence";
}
function isVariableDeclaration(node, variableName) {
return node.type === "VariableDeclaration" && getVariableDeclarator(node, variableName) !== undefined;
}
function getVariableDeclarator(node, variableName) {
return node.declarations.find((d$1) => d$1.type === "VariableDeclarator" && d$1.id.type === "Identifier" && d$1.id.name === variableName);
}
function isFunctionDeclaration(node, funcName) {
return node.type === "FunctionDeclaration" && node.id?.name === funcName;
}
var vite_exports = {};
__export(vite_exports, { addPlugin: () => addPlugin });
function exportDefaultConfig(ast, options$6 = {}) {
const { fallback, ignoreWrapper } = options$6;
let fallbackExpression;
if (fallback) fallbackExpression = typeof fallback === "string" ? parseExpression(fallback) : fallback;
else fallbackExpression = create({});
const { value } = createDefault(ast, { fallback: fallbackExpression });
const rootObject = value.type === "TSSatisfiesExpression" ? value.expression : value;
let configObject;
if (!ignoreWrapper || !("arguments" in rootObject) || !Array.isArray(rootObject.arguments)) {
configObject = rootObject;
return configObject;
}
if (rootObject.type !== "CallExpression" || rootObject.callee.type !== "Identifier" || rootObject.callee.name !== ignoreWrapper) {
configObject = rootObject;
return configObject;
}
const firstArg = getArgument(rootObject, {
index: 0,
fallback: create({})
});
if (firstArg.type === "ArrowFunctionExpression") {
const arrowFunction = firstArg;
if (arrowFunction.body.type === "BlockStatement") {
const returnStatement = arrowFunction.body.body.find((stmt) => stmt.type === "ReturnStatement");
if (returnStatement && returnStatement.argument?.type === "ObjectExpression") configObject = returnStatement.argument;
else {
configObject = create({});
const newReturnStatement = {
type: "ReturnStatement",
argument: configObject
};
arrowFunction.body.body.push(newReturnStatement);
}
} else if (arrowFunction.body.type === "ObjectExpression") configObject = arrowFunction.body;
else {
configObject = create({});
arrowFunction.body = configObject;
arrowFunction.expression = true;
}
} else if (firstArg.type === "ObjectExpression") configObject = firstArg;
else configObject = create({});
return configObject;
}
function addInArrayOfObject(ast, options$6) {
const { code, arrayProperty, mode = "append" } = options$6;
const targetArray = property(ast, {
name: arrayProperty,
fallback: create$1()
});
const expression = parseExpression(code);
if (mode === "prepend") prepend(targetArray, expression);
else append(targetArray, expression);
}
const addPlugin = (ast, options$6) => {
addNamed(ast, {
from: "vite",
imports: { defineConfig: "defineConfig" }
});
const configObject = exportDefaultConfig(ast, {
fallback: "defineConfig()",
ignoreWrapper: "defineConfig"
});
addInArrayOfObject(configObject, {
arrayProperty: "plugins",
...options$6
});
};
//#endregion
//#region packages/cli/commands/add/utils.ts
var import_picocolors$5 = __toESM(require_picocolors(), 1);
function getPackageJson(cwd) {
const packageText = readFile(cwd, commonFilePaths.packageJson);
if (!packageText) {
const pkgPath = path.join(cwd, commonFilePaths.packageJson);
throw new Error(`Invalid workspace: missing '${pkgPath}'`);
}
const { data, generateCode } = parseJson$1(packageText);
return {
source: packageText,
data,
generateCode
};
}
async function formatFiles(options$6) {
const args = [
"prettier",
"--write",
"--ignore-unknown",
...options$6.paths
];
const cmd = resolveCommand(options$6.packageManager, "execute-local", args);
await be(cmd.command, cmd.args, {
nodeOptions: {
cwd: options$6.cwd,
stdio: "pipe"
},
throwOnError: true
});
}
function readFile(cwd, filePath) {
const fullFilePath = path.resolve(cwd, filePath);
if (!fileExists(cwd, filePath)) return "";
const text = fs.readFileSync(fullFilePath, "utf8");
return text;
}
function installPackages(dependencies, workspace) {
const { data, generateCode } = getPackageJson(workspace.cwd);
for (const dependency of dependencies) if (dependency.dev) {
data.devDependencies ??= {};
data.devDependencies[dependency.pkg] = dependency.version;
} else {
data.dependencies ??= {};
data.dependencies[dependency.pkg] = dependency.version;
}
if (data.dependencies) data.dependencies = alphabetizeProperties(data.dependencies);
if (data.devDependencies) data.devDependencies = alphabetizeProperties(data.devDependencies);
writeFile(workspace, commonFilePaths.packageJson, generateCode());
return commonFilePaths.packageJson;
}
function alphabetizeProperties(obj) {
const orderedObj = {};
const sortedEntries = Object.entries(obj).sort(([a], [b$1]) => a.localeCompare(b$1));
for (const [key, value] of sortedEntries) orderedObj[key] = value;
return orderedObj;
}
function writeFile(workspace, filePath, content) {
const fullFilePath = path.resolve(workspace.cwd, filePath);
const fullDirectoryPath = path.dirname(fullFilePath);
if (content && !content.endsWith("\n")) content += "\n";
if (!fs.existsSync(fullDirectoryPath)) fs.mkdirSync(fullDirectoryPath, { recursive: true });
fs.writeFileSync(fullFilePath, content, "utf8");
}
function fileExists(cwd, filePath) {
const fullFilePath = path.resolve(cwd, filePath);
return fs.existsSync(fullFilePath);
}
const commonFilePaths = {
packageJson: "package.json",
svelteConfig: "svelte.config.js",
tsconfig: "tsconfig.json",
viteConfig: "vite.config.js",
viteConfigTS: "vite.config.ts"
};
function getHighlighter() {
return {
command: (str) => import_picocolors$5.default.bold(import_picocolors$5.default.cyanBright(str)),
env: (str) => import_picocolors$5.default.yellow(str),
path: (str) => import_picocolors$5.default.green(str),
route: (str) => import_picocolors$5.default.bold(str),
website: (str) => import_picocolors$5.default.whiteBright(str)
};
}
//#endregion
//#region packages/cli/commands/add/workspace.ts
async function createWorkspace({ cwd, options: options$6 = {}, packageManager }) {
const resolvedCwd = path.resolve(cwd);
const viteConfigPath = path.join(resolvedCwd, commonFilePaths.viteConfigTS);
let usesTypescript = fs.existsSync(viteConfigPath);
const viteConfigFile = usesTypescript ? commonFilePaths.viteConfigTS : commonFilePaths.viteConfig;
if (TESTING) usesTypescript ||= fs.existsSync(path.join(resolvedCwd, commonFilePaths.tsconfig));
else usesTypescript ||= up(commonFilePaths.tsconfig, { cwd }) !== undefined;
let dependencies = {};
let directory = resolvedCwd;
const root = findRoot(resolvedCwd);
while (directory && directory !== root) {
if (fs.existsSync(path.join(directory, commonFilePaths.packageJson))) {
const { data: packageJson } = getPackageJson(directory);
dependencies = {
...packageJson.devDependencies,
...packageJson.dependencies,
...dependencies
};
}
directory = path.dirname(directory);
}
for (const [key, value] of Object.entries(dependencies)) dependencies[key] = value.replaceAll(/[^\d|.]/g, "");
return {
cwd: resolvedCwd,
options: options$6,
packageManager: packageManager ?? (await detect({ cwd }))?.name ?? getUserAgent() ?? "npm",
typescript: usesTypescript,
viteConfigFile,
kit: dependencies["@sveltejs/kit"] ? parseKitOptions(resolvedCwd) : undefined,
dependencyVersion: (pkg) => dependencies[pkg]
};
}
function findRoot(cwd) {
const { root } = path.parse(cwd);
let directory = cwd;
while (directory && directory !== root) {
if (fs.existsSync(path.join(directory, commonFilePaths.packageJson))) {
if (fs.existsSync(path.join(directory, "pnpm-workspace.yaml"))) return directory;
const { data } = getPackageJson(directory);
if (data.workspaces) return directory;
}
directory = path.dirname(directory);
}
return root;
}
function parseKitOptions(cwd) {
const configSource = readFile(cwd, commonFilePaths.svelteConfig);
const { ast } = parseScript$1(configSource);
const defaultExport = ast.body.find((s) => s.type === "ExportDefaultDeclaration");
if (!defaultExport) throw Error("Missing default export in `svelte.config.js`");
let objectExpression;
if (defaultExport.declaration.type === "Identifier") {
const identifier = defaultExport.declaration;
for (const declaration$1 of ast.body) {
if (declaration$1.type !== "VariableDeclaration") continue;
const declarator = declaration$1.declarations.find((d$1) => d$1.type === "VariableDeclarator" && d$1.id.type === "Identifier" && d$1.id.name === identifier.name);
if (declarator?.init?.type !== "ObjectExpression") continue;
objectExpression = declarator.init;
}
if (!objectExpression) throw Error("Unable to find svelte config object expression from `svelte.config.js`");
} else if (defaultExport.declaration.type === "ObjectExpression") objectExpression = defaultExport.declaration;
if (!objectExpression) throw new Error("Unexpected svelte config shape from `svelte.config.js`");
const kit = object_exports.property(objectExpression, {
name: "kit",
fallback: object_exports.create({})
});
const files = object_exports.property(kit, {
name: "files",
fallback: object_exports.create({})
});
const routes = object_exports.property(files, {
name: "routes",
fallback: common_exports.createLiteral("")
});
const lib = object_exports.property(files, {
name: "lib",
fallback: common_exports.createLiteral("")
});
const routesDirectory = routes.value || "src/routes";
const libDirectory = lib.value || "src/lib";
return {
routesDirectory,
libDirectory
};
}
//#endregion
//#region packages/cli/lib/install.ts
var import_picocolors$4 = __toESM(require_picocolors(), 1);
async function installAddon({ addons, cwd, options: options$6, packageManager = "npm" }) {
const workspace = await createWorkspace({
cwd,
packageManager
});
const addonSetupResults = setupAddons(Object.values(addons), workspace);
return await applyAddons({
addons,
workspace,
options: options$6,
addonSetupResults
});
}
async function applyAddons({ addons, workspace, addonSetupResults, options: options$6 }) {
const filesToFormat = new Set();
const allPnpmBuildDependencies = [];
const mapped = Object.entries(addons).map(([, addon]) => addon);
const ordered = orderAddons(mapped, addonSetupResults);
for (const addon of ordered) {
workspace = await createWorkspace({
...workspace,
options: options$6[addon.id]
});
const { files, pnpmBuildDependencies } = await runAddon({
workspace,
addon,
multiple: ordered.length > 1
});
files.forEach((f$1) => filesToFormat.add(f$1));
pnpmBuildDependencies.forEach((s) => allPnpmBuildDependencies.push(s));
}
return {
filesToFormat: Array.from(filesToFormat),
pnpmBuildDependencies: allPnpmBuildDependencies
};
}
function setupAddons(addons, workspace) {
const addonSetupResults = {};
for (const addon of addons) {
const setupResult = {
unsupported: [],
dependsOn: [],
runsAfter: []
};
addon.setup?.({
...workspace,
dependsOn: (name) => {
setupResult.dependsOn.push(name);
setupResult.runsAfter.push(name);
},
unsupported: (reason) => setupResult.unsupported.push(reason),
runsAfter: (name) => setupResult.runsAfter.push(name)
});
addonSetupResults[addon.id] = setupResult;
}
return addonSetupResults;
}
async function runAddon({ addon, multiple, workspace }) {
const files = new Set();
for (const [id, question] of Object.entries(addon.options)) if (question.condition?.(workspace.options) !== false) workspace.options[id] ??= question.default;
const dependencies = [];
const pnpmBuildDependencies = [];
const sv = {
file: (path$1, content) => {
try {
const exists = fileExists(workspace.cwd, path$1);
let fileContent = exists ? readFile(workspace.cwd, path$1) : "";
fileContent = content(fileContent);
if (!fileContent) return fileContent;
writeFile(workspace, path$1, fileContent);
files.add(path$1);
} catch (e) {
if (e instanceof Error) throw new Error(`Unable to process '${path$1}'. Reason: ${e.message}`);
throw e;
}
},
execute: async (commandArgs, stdio) => {
const { command, args } = resolveCommand(workspace.packageManager, "execute", commandArgs);
const addonPrefix = multiple ? `${addon.id}: ` : "";
const executedCommand = `${command} ${args.join(" ")}`;
if (!TESTING) T.step(`${addonPrefix}Running external command ${import_picocolors$4.default.gray(`(${executedCommand})`)}`);
if (workspace.packageManager === "npm") args.unshift("--yes");
try {
await be(command, args, {
nodeOptions: {
cwd: workspace.cwd,
stdio: TESTING ? "pipe" : stdio
},
throwOnError: true
});
} catch (error) {
const typedError = error;
throw new Error(`Failed to execute scripts '${executedCommand}': ${typedError.message}`, { cause: typedError.output });
}
},
dependency: (pkg, version) => {
dependencies.push({
pkg,
version,
dev: false
});
},
devDependency: (pkg, version) => {
dependencies.push({
pkg,
version,
dev: true
});
},
pnpmBuildDependendency: (pkg) => {
pnpmBuildDependencies.push(pkg);
}
};
await addon.run({
...workspace,
sv
});
const pkgPath = installPackages(dependencies, workspace);
files.add(pkgPath);
return {
files: Array.from(files),
pnpmBuildDependencies
};
}
function orderAddons(addons, setupResults) {
return addons.sort((a, b$1) => {
return setupResults[a.id]?.runsAfter?.length - setupResults[b$1.id]?.runsAfter?.length;
});
}
//#endregion
//#region packages/core/dist/index.js
function defineAddon(config) {
return config;
}
function defineAddonOptions(options$6) {
return options$6;
}
var require_src = __commonJS({ "node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
const ESC = "\x1B";
const CSI = `${ESC}[`;
const beep = "\x07";
const cursor = {
to(x$2, y) {
if (!y) return `${CSI}${x$2 + 1}G`;
return `${CSI}${y + 1};${x$2 + 1}H`;
},
move(x$2, y) {
let ret = "";
if (x$2 < 0) ret += `${CSI}${-x$2}D`;
else if (x$2 > 0) ret += `${CSI}${x$2}C`;
if (y < 0) ret += `${CSI}${-y}A`;
else if (y > 0) ret += `${CSI}${y}B`;
return ret;
},
up: (count = 1) => `${CSI}${count}A`,
down: (count = 1) => `${CSI}${count}B`,
forward: (count = 1) => `${CSI}${count}C`,
backward: (count = 1) => `${CSI}${count}D`,
nextLine: (count = 1) => `${CSI}E`.repeat(count),
prevLine: (count = 1) => `${CSI}F`.repeat(count),
left: `${CSI}G`,
hide: `${CSI}?25l`,
show: `${CSI}?25h`,
save: `${ESC}7`,
restore: `${ESC}8`
};
const scroll = {
up: (count = 1) => `${CSI}S`.repeat(count),
down: (count = 1) => `${CSI}T`.repeat(count)
};
const erase = {
screen: `${CSI}2J`,
up: (count = 1) => `${CSI}1J`.repeat(count),
down: (count = 1) => `${CSI}J`.repeat(count),
line: `${CSI}2K`,
lineEnd: `${CSI}K`,
lineStart: `${CSI}1K`,
lines(count) {
let clear = "";
for (let i = 0; i < count; i++) clear += this.line + (i < count - 1 ? cursor.up() : "");
if (count) clear += cursor.left;
return clear;
}
};
module.exports = {
cursor,
scroll,
erase,
beep
};
} });
var import_src$1 = __toESM$1(require_src(), 1);
var import_picocolors$3 = __toESM$1(require_picocolors$1(), 1);
function hu({ onlyFirst: e$1 = !1 } = {}) {
const t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
return new RegExp(t, e$1 ? void 0 : "g");
}
const cu = hu();
function Y(e$1) {
if (typeof e$1 != "string") throw new TypeError(`Expected a \`string\`, got \`${typeof e$1}\``);
return e$1.replace(cu, "");
}
function Z(e$1) {
return e$1 && e$1.__esModule && Object.prototype.hasOwnProperty.call(e$1, "default") ? e$1.default : e$1;
}
var q$1 = { exports: {} };
(function(e$1) {
var D$1 = {};
e$1.exports = D$1, D$1.eastAsianWidth = function(s) {
var i = s.charCodeAt(0), F$1 = s.length == 2 ? s.charCodeAt(1) : 0, u = i;
return 55296 <= i && i <= 56319 && 56320 <= F$1 && F$1 <= 57343 && (i &= 1023, F$1 &= 1023, u = i << 10 | F$1, u += 65536), u == 12288 || 65281 <= u && u <= 65376 || 65504 <= u && u <= 65510 ? "F" : u == 8361 || 65377 <= u && u <= 65470 || 65474 <= u && u <= 65479 || 65482 <= u && u <= 65487 || 65490 <= u && u <= 65495 || 65498 <= u && u <= 65500 || 65512 <= u && u <= 65518 ? "H" : 4352 <= u && u <= 4447 || 4515 <= u && u <= 4519 || 4602 <= u && u <= 4607 || 9001 <= u && u <= 9002 || 11904 <= u && u <= 11929 || 11931 <= u && u <= 12019 || 12032 <= u && u <= 12245 || 12272 <= u && u <= 12283 || 12289 <= u && u <= 12350 || 12353 <= u && u <= 12438 || 12441 <= u && u <= 12543 || 12549 <= u && u <= 12589 || 12593 <= u && u <= 12686 || 12688 <= u && u <= 12730 || 12736 <= u && u <= 12771 || 12784 <= u && u <= 12830 || 12832 <= u && u <= 12871 || 12880 <= u && u <= 13054 || 13056 <= u && u <= 19903 || 19968 <= u && u <= 42124 || 42128 <= u && u <= 42182 || 43360 <= u && u <= 43388 || 44032 <= u && u <= 55203 || 55216 <= u && u <= 55238 || 55243 <= u && u <= 55291 || 63744 <= u && u <= 64255 || 65040 <= u && u <= 65049 || 65072 <= u && u <= 65106 || 65108 <= u && u <= 65126 || 65128 <= u && u <= 65131 || 110592 <= u && u <= 110593 || 127488 <= u && u <= 127490 || 127504 <= u && u <= 127546 || 127552 <= u && u <= 127560 || 127568 <= u && u <= 127569 || 131072 <= u && u <= 194367 || 177984 <= u && u <= 196605 || 196608 <= u && u <= 262141 ? "W" : 32 <= u && u <= 126 || 162 <= u && u <= 163 || 165 <= u && u <= 166 || u == 172 || u == 175 || 10214 <= u && u <= 10221 || 10629 <= u && u <= 10630 ? "Na" : u == 161 || u == 164 || 167 <= u && u <= 168 || u == 170 || 173 <= u && u <= 174 || 176 <= u && u <= 180 || 182 <= u && u <= 186 || 188 <= u && u <= 191 || u == 198 || u == 208 || 215 <= u && u <= 216 || 222 <= u && u <= 225 || u == 230 || 232 <= u && u <= 234 || 236 <= u && u <= 237 || u == 240 || 242 <= u && u <= 243 || 247 <= u && u <= 250 || u == 252 || u == 254 || u == 257 || u == 273 || u == 275 || u == 283 || 294 <= u && u <= 295 || u == 299 || 305 <= u && u <= 307 || u == 312 || 319 <= u && u <= 322 || u == 324 || 328 <= u && u <= 331 || u == 333 || 338 <= u && u <= 339 || 358 <= u && u <= 359 || u == 363 || u == 462 || u == 464 || u == 466 || u == 468 || u == 470 || u == 472 || u == 474 || u == 476 || u == 593 || u == 609 || u == 708 || u == 711 || 713 <= u && u <= 715 || u == 717 || u == 720 || 728 <= u && u <= 731 || u == 733 || u == 735 || 768 <= u && u <= 879 || 913 <= u && u <= 929 || 931 <= u && u <= 937 || 945 <= u && u <= 961 || 963 <= u && u <= 969 || u == 1025 || 1040 <= u && u <= 1103 || u == 1105 || u == 8208 || 8211 <= u && u <= 8214 || 8216 <= u && u <= 8217 || 8220 <= u && u <= 8221 || 8224 <= u && u <= 8226 || 8228 <= u && u <= 8231 || u == 8240 || 8242 <= u && u <= 8243 || u == 8245 || u == 8251 || u == 8254 || u == 8308 || u == 8319 || 8321 <= u && u <= 8324 || u == 8364 || u == 8451 || u == 8453 || u == 8457 || u == 8467 || u == 8470 || 8481 <= u && u <= 8482 || u == 8486 || u == 8491 || 8531 <= u && u <= 8532 || 8539 <= u && u <= 8542 || 8544 <= u && u <= 8555 || 8560 <= u && u <= 8569 || u == 8585 || 8592 <= u && u <= 8601 || 8632 <= u && u <= 8633 || u == 8658 || u == 8660 || u == 8679 || u == 8704 || 8706 <= u && u <= 8707 || 8711 <= u && u <= 8712 || u == 8715 || u == 8719 || u == 8721 || u == 8725 || u == 8730 || 8733 <= u && u <= 8736 || u == 8739 || u == 8741 || 8743 <= u && u <= 8748 || u == 8750 || 8756 <= u && u <= 8759 || 8764 <= u && u <= 8765 || u == 8776 || u == 8780 || u == 8786 || 8800 <= u && u <= 8801 || 8804 <= u && u <= 8807 || 8810 <= u && u <= 8811 || 8814 <= u && u <= 8815 || 8834 <= u && u <= 8835 || 8838 <= u && u <= 8839 || u == 8853 || u == 8857 || u == 8869 || u == 8895 || u == 8978 || 9312 <= u && u <= 9449 || 9451 <= u && u <= 9547 || 9552 <= u && u <= 9587 || 9600 <= u && u <= 9615 || 9618 <= u && u <= 9621 || 9632 <= u && u <= 9633 || 9635 <= u && u <= 9641 || 9650 <= u && u <= 9651 || 9654 <= u && u <= 9655 || 9660 <= u && u <= 9661 || 9664 <= u && u <= 9665 || 9670 <= u && u <= 9672 || u == 9675 || 9678 <= u && u <= 9681 || 9698 <= u && u <= 9701 || u == 9711 || 9733 <= u && u <= 9734 || u == 9737 || 9742 <= u && u <= 9743 || 9748 <= u && u <= 9749 || u == 9756 || u == 9758 || u == 9792 || u == 9794 || 9824 <= u && u <= 9825 || 9827 <= u && u <= 9829 || 9831 <= u && u <= 9834 || 9836 <= u && u <= 9837 || u == 9839 || 9886 <= u && u <= 9887 || 9918 <= u && u <= 9919 || 9924 <= u && u <= 9933 || 9935 <= u && u <= 9953 || u == 9955 || 9960 <= u && u <= 9983 || u == 10045 || u == 10071 || 10102 <= u && u <= 10111 || 11093 <= u && u <= 11097 || 12872 <= u && u <= 12879 || 57344 <= u && u <= 63743 || 65024 <= u && u <= 65039 || u == 65533 || 127232 <= u && u <= 127242 || 127248 <= u && u <= 127277 || 127280 <= u && u <= 127337 || 127344 <= u && u <= 127386 || 917760 <= u && u <= 917999 || 983040 <= u && u <= 1048573 || 1048576 <= u && u <= 1114109 ? "A" : "N";
}, D$1.characterLength = function(s) {
var i = this.eastAsianWidth(s);
return i == "F" || i == "W" || i == "A" ? 2 : 1;
};
function t(s) {
return s.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
}
D$1.length = function(s) {
for (var i = t(s), F$1 = 0, u = 0; u < i.length; u++) F$1 = F$1 + this.characterLength(i[u]);
return F$1;
}, D$1.slice = function(s, i, F$1) {
textLen = D$1.length(s), i = i || 0, F$1 = F$1 || 1, i < 0 && (i = textLen + i), F$1 < 0 && (F$1 = textLen + F$1);
for (var u = "", r = 0, a = t(s), n$1 = 0; n$1 < a.length; n$1++) {
var l = a[n$1], o$1 = D$1.length(l);
if (r >= i - (o$1 == 2 ? 1 : 0)) if (r + o$1 <= F$1) u += l;
else break;
r += o$1;
}
return u;
};
})(q$1);
var xu = q$1.exports;
const Bu = Z(xu);
var pu = function() {
return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
};
const Au = Z(pu);
function b(e$1, D$1 = {}) {
if (typeof e$1 != "string" || e$1.length === 0 || (D$1 = {
ambiguousIsNarrow: !0,
...D$1
}, e$1 = Y(e$1), e$1.length === 0)) return 0;
e$1 = e$1.replace(Au(), " ");
const t = D$1.ambiguousIsNarrow ? 1 : 2;
let s = 0;
for (const i of e$1) {
const F$1 = i.codePointAt(0);
if (F$1 <= 31 || F$1 >= 127 && F$1 <= 159 || F$1 >= 768 && F$1 <= 879) continue;
switch (Bu.eastAsianWidth(i)) {
case "F":
case "W":
s += 2;
break;
case "A":
s += t;
break;
default: s += 1;
}
}
return s;
}
const M = 10, H$1 = (e$1 = 0) => (D$1) => `\x1B[${D$1 + e$1}m`, J$1 = (e$1 = 0) => (D$1) => `\x1B[${38 + e$1};5;${D$1}m`, Q = (e$1 = 0) => (D$1, t, s) => `\x1B[${38 + e$1};2;${D$1};${t};${s}m`, C$1 = {
modifier: {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
overline: [53, 55],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
blackBright: [90, 39],
gray: [90, 39],
grey: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgBlackBright: [100, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
Object.keys(C$1.modifier);
const fu = Object.keys(C$1.color), du = Object.keys(C$1.bgColor);
[...fu, ...du];
function gu() {
const e$1 = new Map();
for (const [D$1, t] of Object.entries(C$1)) {
for (const [s, i] of Object.entries(t)) C$1[s] = {
open: `\x1B[${i[0]}m`,
close: `\x1B[${i[1]}m`
}, t[s] = C$1[s], e$1.set(i[0], i[1]);
Object.defineProperty(C$1, D$1, {
value: t,
enumerable: !1
});
}
return Object.defineProperty(C$1, "codes", {
value: e$1,
enumerable: !1
}), C$1.color.close = "\x1B[39m", C$1.bgColor.close = "\x1B[49m", C$1.color.ansi = H$1(), C$1.color.ansi256 = J$1(), C$1.color.ansi16m = Q(), C$1.bgColor.ansi = H$1(M), C$1.bgColor.ansi256 = J$1(M), C$1.bgColor.ansi16m = Q(M), Object.defineProperties(C$1, {
rgbToAnsi256: {
value: (D$1, t, s) => D$1 === t && t === s ? D$1 < 8 ? 16 : D$1 > 248 ? 231 : Math.round((D$1 - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(D$1 / 255 * 5) + 6 * Math.round(t / 255 * 5) + Math.round(s / 255 * 5),
enumerable: !1
},
hexToRgb: {
value: (D$1) => {
const t = /[a-f\d]{6}|[a-f\d]{3}/i.exec(D$1.toString(16));
if (!t) return [
0,
0,
0
];
let [s] = t;
s.length === 3 && (s = [...s].map((F$1) => F$1 + F$1).join(""));
const i = Number.parseInt(s, 16);
return [
i >> 16 & 255,
i >> 8 & 255,
i & 255
];
},
enumerable: !1
},
hexToAnsi256: {
value: (D$1) => C$1.rgbToAnsi256(...C$1.hexToRgb(D$1)),
enumerable: !1
},
ansi256ToAnsi: {
value: (D$1) => {
if (D$1 < 8) return 30 + D$1;
if (D$1 < 16) return 90 + (D$1 - 8);
let t, s, i;
if (D$1 >= 232) t = ((D$1 - 232) * 10 + 8) / 255, s = t, i = t;
else {
D$1 -= 16;
const r = D$1 % 36;
t = Math.floor(D$1 / 36) / 5, s = Math.floor(r / 6) / 5, i = r % 6 / 5;
}
const F$1 = Math.max(t, s, i) * 2;
if (F$1 === 0) return 30;
let u = 30 + (Math.round(i) << 2 | Math.round(s) << 1 | Math.round(t));
return F$1 === 2 && (u += 60), u;
},
enumerable: !1
},
rgbToAnsi: {
value: (D$1, t, s) => C$1.ansi256ToAnsi(C$1.rgbToAnsi256(D$1, t, s)),
enumerable: !1
},
hexToAnsi: {
value: (D$1) => C$1.ansi256ToAnsi(C$1.hexToAnsi256(D$1)),
enumerable: !1
}
}), C$1;
}
const mu = gu(), $ = new Set(["\x1B", ""]), vu = 39, O$1 = "\x07", X$1 = "[", bu = "]", uu = "m", T$1 = `${bu}8;;`, Du = (e$1) => `${$.values().next().value}${X$1}${e$1}${uu}`, tu = (e$1) => `${$.values().next().value}${T$1}${e$1}${O$1}`, wu = (e$1) => e$1.split(" ").map((D$1) => b(D$1)), j$1 = (e$1, D$1, t) => {
const s = [...D$1];
let i = !1, F$1 = !1, u = b(Y(e$1[e$1.length - 1]));
for (const [r, a] of s.entries()) {
const n$1 = b(a);
if (u + n$1 <= t ? e$1[e$1.length - 1] += a : (e$1.push(a), u = 0), $.has(a) && (i = !0, F$1 = s.slice(r + 1).join("").startsWith(T$1)), i) {
F$1 ? a === O$1 && (i = !1, F$1 = !1) : a === uu && (i = !1);
continue;
}
u += n$1, u === t && r < s.length - 1 && (e$1.push(""), u = 0);
}
!u && e$1[e$1.length - 1].length > 0 && e$1.length > 1 && (e$1[e$1.length - 2] += e$1.pop());
}, yu = (e$1) => {
const D$1 = e$1.split(" ");
let t = D$1.length;
for (; t > 0 && !(b(D$1[t - 1]) > 0);) t--;
return t === D$1.length ? e$1 : D$1.slice(0, t).join(" ") + D$1.slice(t).join("");
}, _u = (e$1, D$1, t = {}) => {
if (t.trim !== !1 && e$1.trim() === "") return "";
let s = "", i, F$1;
const u = wu(e$1);
let r = [""];
for (const [n$1, l] of e$1.split(" ").entries()) {
t.trim !== !1 && (r[r.length - 1] = r[r.length - 1].trimStart());
let o$1 = b(r[r.length - 1]);
if (n$1 !== 0 && (o$1 >= D$1 && (t.wordWrap === !1 || t.trim === !1) && (r.push(""), o$1 = 0), (o$1 > 0 || t.trim === !1) && (r[r.length - 1] += " ", o$1++)), t.hard && u[n$1] > D$1) {
const A = D$1 - o$1, y = 1 + Math.floor((u[n$1] - A - 1) / D$1);
Math.floor((u[n$1] - 1) / D$1) < y && r.push(""), j$1(r, l, D$1);
continue;
}
if (o$1 + u[n$1] > D$1 && o$1 > 0 && u[n$1] > 0) {
if (t.wordWrap === !1 && o$1 < D$1) {
j$1(r, l, D$1);
continue;
}
r.push("");
}
if (o$1 + u[n$1] > D$1 && t.wordWrap === !1) {
j$1(r, l, D$1);
continue;
}
r[r.length - 1] += l;
}
t.trim !== !1 && (r = r.map((n$1) => yu(n$1)));
const a = [...r.join(`
`)];
for (const [n$1, l] of a.entries()) {
if (s += l, $.has(l)) {
const { groups: A } = new RegExp(`(?:\\${X$1}(?<code>\\d+)m|\\${T$1}(?<uri>.*)${O$1})`).exec(a.slice(n$1).join("")) || { groups: {} };
if (A.code !== void 0) {
const y = Number.parseFloat(A.code);
i = y === vu ? void 0 : y;
} else A.uri !== void 0 && (F$1 = A.uri.length === 0 ? void 0 : A.uri);
}
const o$1 = mu.codes.get(Number(i));
a[n$1 + 1] === `
` ? (F$1 && (s += tu("")), i && o$1 && (s += Du(o$1))) : l === `
` && (i && o$1 && (s += Du(i)), F$1 && (s += tu(F$1)));
}
return s;
};
function eu(e$1, D$1, t) {
return String(e$1).normalize().replace(/\r\n/g, `
`).split(`
`).map((s) => _u(s, D$1, t)).join(`
`);
}
const $u = [
"up",
"down",
"left",
"right",
"space",
"enter",
"cancel"
], c = {
actions: new Set($u),
aliases: new Map([
["k", "up"],
["j", "down"],
["h", "left"],
["l", "right"],
["", "cancel"],
["escape", "cancel"]
]),
messages: {
cancel: "Canceled",
error: "Something went wrong"
}
};
function W(e$1, D$1) {
if (typeof e$1 == "string") return c.aliases.get(e$1) === D$1;
for (const t of e$1) if (t !== void 0 && W(t, D$1)) return !0;
return !1;
}
function ku(e$1, D$1) {
if (e$1 === D$1) return;
const t = e$1.split(`
`), s = D$1.split(`
`), i = [];
for (let F$1 = 0; F$1 < Math.max(t.length, s.length); F$1++) t[F$1] !== s[F$1] && i.push(F$1);
return i;
}
const Iu = globalThis.process.platform.startsWith("win"), L$1 = Symbol("clack:cancel");
function Vu(e$1) {
return e$1 === L$1;
}
function S(e$1, D$1) {
const t = e$1;
t.isTTY && t.setRawMode(D$1);
}
function Mu({ input: e$1 = stdin, output: D$1 = stdout, overwrite: t = !0, hideCursor: s = !0 } = {}) {
const i = _.createInterface({
input: e$1,
output: D$1,
prompt: "",
tabSize: 1
});
_.emitKeypressEvents(e$1, i), e$1 instanceof ReadStream && e$1.isTTY && e$1.setRawMode(!0);
const F$1 = (u, { name: r, sequence: a }) => {
const n$1 = String(u);
if (W([
n$1,
r,
a
], "cancel")) {
s && D$1.write(import_src$1.cursor.show), process.exit(0);
return;
}
if (!t) return;
const l = r === "return" ? 0 : -1, o$1 = r === "return" ? -1 : 0;
_.moveCursor(D$1, l, o$1, () => {
_.clearLine(D$1, 1, () => {
e$1.once("keypress", F$1);
});
});
};
return s && D$1.write(import_src$1.cursor.hide), e$1.once("keypress", F$1), () => {
e$1.off("keypress", F$1), s && D$1.write(import_src$1.cursor.show), e$1 instanceof ReadStream && e$1.isTTY && !Iu && e$1.setRawMode(!1), i.terminal = !1, i.close();
};
}
const Ou = (e$1) => e$1 instanceof WriteStream && e$1.columns ? e$1.columns : 80;
var Tu = Object.defineProperty, ju = (e$1, D$1, t) => D$1 in e$1 ? Tu(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, E$1 = (e$1, D$1, t) => (ju(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t);
let p = class {
constructor(D$1, t = !0) {
E$1(this, "input"), E$1(this, "output"), E$1(this, "_abortSignal"), E$1(this, "rl"), E$1(this, "opts"), E$1(this, "_render"), E$1(this, "_track", !1), E$1(this, "_prevFrame", ""), E$1(this, "_subscribers", new Map()), E$1(this, "_cursor", 0), E$1(this, "state", "initial"), E$1(this, "error", ""), E$1(this, "value"), E$1(this, "userInput", "");
const { input: s = stdin, output: i = stdout, render: F$1, signal: u,...r } = D$1;
this.opts = r, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = F$1.bind(this), this._track = t, this._abortSignal = u, this.input = s, this.output = i;
}
unsubscribe() {
this._subscribers.clear();
}
setSubscriber(D$1, t) {
const s = this._subscribers.get(D$1) ?? [];
s.push(t), this._subscribers.set(D$1, s);
}
on(D$1, t) {
this.setSubscriber(D$1, { cb: t });
}
once(D$1, t) {
this.setSubscriber(D$1, {
cb: t,
once: !0
});
}
emit(D$1, ...t) {
const s = this._subscribers.get(D$1) ?? [], i = [];
for (const F$1 of s) F$1.cb(...t), F$1.once && i.push(() => s.splice(s.indexOf(F$1), 1));
for (const F$1 of i) F$1();
}
prompt() {
return new Promise((D$1) => {
if (this._abortSignal) {
if (this._abortSignal.aborted) return this.state = "cancel", this.close(), D$1(L$1);
this._abortSignal.addEventListener("abort", () => {
this.state = "cancel", this.close();
}, { once: !0 });
}
this.rl = Eu.createInterface({
input: this.input,
tabSize: 2,
prompt: "",
escapeCodeTimeout: 50,
terminal: !0
}), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, !0), this.input.on("keypress", this.onKeypress), S(this.input, !0), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
this.output.write(import_src$1.cursor.show), this.output.off("resize", this.render), S(this.input, !1), D$1(this.value);
}), this.once("cancel", () => {
this.output.write(import_src$1.cursor.show), this.output.off("resize", this.render), S(this.input, !1), D$1(L$1);
});
});
}
_isActionKey(D$1, t) {
return D$1 === " ";
}
_setValue(D$1) {
this.value = D$1, this.emit("value", this.value);
}
_setUserInput(D$1, t) {
this.userInput = D$1 ?? "", this.emit("userInput", this.userInput), t && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
}
onKeypress(D$1, t) {
if (this._track && t.name !== "return" && (t.name && this._isActionKey(D$1, t) && this.rl?.write(null, {
ctrl: !0,
name: "h"
}), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), t?.name && (!this._track && c.aliases.has(t.name) && this.emit("cursor", c.aliases.get(t.name)), c.actions.has(t.name) && this.emit("cursor", t.name)), D$1 && (D$1.toLowerCase() === "y" || D$1.toLowerCase() === "n") && this.emit("confirm", D$1.toLowerCase() === "y"), this.emit("key", D$1?.toLowerCase(), t), t?.name === "return") {
if (this.opts.validate) {
const s = this.opts.validate(this.value);
s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
}
this.state !== "error" && (this.state = "submit");
}
W([
D$1,
t?.name,
t?.sequence
], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
}
close() {
this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
`), S(this.input, !1), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
}
restoreCursor() {
const D$1 = eu(this._prevFrame, process.stdout.columns, { hard: !0 }).split(`
`).length - 1;
this.output.write(import_src$1.cursor.move(-999, D$1 * -1));
}
render() {
const D$1 = eu(this._render(this) ?? "", process.stdout.columns, { hard: !0 });
if (D$1 !== this._prevFrame) {
if (this.state === "initial") this.output.write(import_src$1.cursor.hide);
else {
const t = ku(this._prevFrame, D$1);
if (this.restoreCursor(), t && t?.length === 1) {
const s = t[0];
this.output.write(import_src$1.cursor.move(0, s)), this.output.write(import_src$1.erase.lines(1));
const i = D$1.split(`
`);
this.output.write(i[s]), this._prevFrame = D$1, this.output.write(import_src$1.cursor.move(0, i.length - s - 1));
return;
}
if (t && t?.length > 1) {
const s = t[0];
this.output.write(import_src$1.cursor.move(0, s)), this.output.write(import_src$1.erase.down());
const i = D$1.split(`
`).slice(s);
this.output.write(i.join(`
`)), this._prevFrame = D$1;
return;
}
this.output.write(import_src$1.erase.down());
}
this.output.write(D$1), this.state === "initial" && (this.state = "active"), this._prevFrame = D$1;
}
}
}, Wu = class extends p {
get cursor() {
return this.value ? 0 : 1;
}
get _value() {
return this.cursor === 0;
}
constructor(D$1) {
super(D$1, !1), this.value = !!D$1.initialValue, this.on("userInput", () => {
this.value = this._value;
}), this.on("confirm", (t) => {
this.output.write(import_src$1.cursor.move(0, -1)), this.value = t, this.state = "submit", this.close();
}), this.on("cursor", () => {
this.value = !this.value;
});
}
};
var Lu = Object.defineProperty, Nu = (e$1, D$1, t) => D$1 in e$1 ? Lu(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, su = (e$1, D$1, t) => (Nu(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t), iu = (e$1, D$1, t) => {
if (!D$1.has(e$1)) throw TypeError("Cannot " + t);
}, N$1 = (e$1, D$1, t) => (iu(e$1, D$1, "read from private field"), t ? t.call(e$1) : D$1.get(e$1)), Pu = (e$1, D$1, t) => {
if (D$1.has(e$1)) throw TypeError("Cannot add the same private member more than once");
D$1 instanceof WeakSet ? D$1.add(e$1) : D$1.set(e$1, t);
}, Ru = (e$1, D$1, t, s) => (iu(e$1, D$1, "write to private field"), s ? s.call(e$1, t) : D$1.set(e$1, t), t), d;
let Ku = class extends p {
constructor(D$1) {
super(D$1, !1), su(this, "options"), su(this, "cursor", 0), Pu(this, d, void 0);
const { options: t } = D$1;
Ru(this, d, D$1.selectableGroups !== !1), this.options = Object.entries(t).flatMap(([s, i]) => [{
value: s,
group: !0,
label: s
}, ...i.map((F$1) => ({
...F$1,
group: s
}))]), this.value = [...D$1.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: s }) => s === D$1.cursorAt), N$1(this, d) ? 0 : 1), this.on("cursor", (s) => {
switch (s) {
case "left":
case "up": {
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
const i = this.options[this.cursor]?.group === !0;
!N$1(this, d) && i && (this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1);
break;
}
case "down":
case "right": {
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
const i = this.options[this.cursor]?.group === !0;
!N$1(this, d) && i && (this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1);
break;
}
case "space":
this.toggleValue();
break;
}
});
}
getGroupItems(D$1) {
return this.options.filter((t) => t.group === D$1);
}
isGroupSelected(D$1) {
const t = this.getGroupItems(D$1), s = this.value;
return s === void 0 ? !1 : t.every((i) => s.includes(i.value));
}
toggleValue() {
const D$1 = this.options[this.cursor];
if (this.value === void 0 && (this.value = []), D$1.group === !0) {
const t = D$1.value, s = this.getGroupItems(t);
this.isGroupSelected(t) ? this.value = this.value.filter((i) => s.findIndex((F$1) => F$1.value === i) === -1) : this.value = [...this.value, ...s.map((i) => i.value)], this.value = Array.from(new Set(this.value));
} else {
const t = this.value.includes(D$1.value);
this.value = t ? this.value.filter((s) => s !== D$1.value) : [...this.value, D$1.value];
}
}
};
d = new WeakMap();
var Gu = Object.defineProperty, zu = (e$1, D$1, t) => D$1 in e$1 ? Gu(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, Fu = (e$1, D$1, t) => (zu(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t);
let Uu = class extends p {
constructor(D$1) {
super(D$1, !1), Fu(this, "options"), Fu(this, "cursor", 0), this.options = D$1.options, this.value = [...D$1.initialValues ?? []], this.cursor = Math.max(this.options.findIndex(({ value: t }) => t === D$1.cursorAt), 0), this.on("key", (t) => {
t === "a" && this.toggleAll();
}), this.on("cursor", (t) => {
switch (t) {
case "left":
case "up":
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
break;
case "down":
case "right":
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
break;
case "space":
this.toggleValue();
break;
}
});
}
get _value() {
return this.options[this.cursor].value;
}
toggleAll() {
const D$1 = this.value !== void 0 && this.value.length === this.options.length;
this.value = D$1 ? [] : this.options.map((t) => t.value);
}
toggleValue() {
this.value === void 0 && (this.value = []);
const D$1 = this.value.includes(this._value);
this.value = D$1 ? this.value.filter((t) => t !== this._value) : [...this.value, this._value];
}
};
var Yu = Object.defineProperty, Zu = (e$1, D$1, t) => D$1 in e$1 ? Yu(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, qu = (e$1, D$1, t) => (Zu(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t);
let Hu = class extends p {
constructor({ mask: D$1,...t }) {
super(t), qu(this, "_mask", "•"), this._mask = D$1 ?? "•", this.on("userInput", (s) => {
this._setValue(s);
});
}
get cursor() {
return this._cursor;
}
get masked() {
return this.userInput.replaceAll(/./g, this._mask);
}
get userInputWithCursor() {
if (this.state === "submit" || this.state === "cancel") return this.masked;
const D$1 = this.userInput;
if (this.cursor >= D$1.length) return `${this.masked}${import_picocolors$3.default.inverse(import_picocolors$3.default.hidden("_"))}`;
const t = this.masked, s = t.slice(0, this.cursor), i = t.slice(this.cursor);
return `${s}${import_picocolors$3.default.inverse(i[0])}${i.slice(1)}`;
}
};
var Ju = Object.defineProperty, Qu = (e$1, D$1, t) => D$1 in e$1 ? Ju(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, ru = (e$1, D$1, t) => (Qu(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t);
let Xu = class extends p {
constructor(D$1) {
super(D$1, !1), ru(this, "options"), ru(this, "cursor", 0), this.options = D$1.options, this.cursor = this.options.findIndex(({ value: t }) => t === D$1.initialValue), this.cursor === -1 && (this.cursor = 0), this.changeValue(), this.on("cursor", (t) => {
switch (t) {
case "left":
case "up":
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
break;
case "down":
case "right":
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
break;
}
this.changeValue();
});
}
get _selectedValue() {
return this.options[this.cursor];
}
changeValue() {
this.value = this._selectedValue.value;
}
};
var uD = Object.defineProperty, DD = (e$1, D$1, t) => D$1 in e$1 ? uD(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, Cu = (e$1, D$1, t) => (DD(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t);
let tD = class extends p {
constructor(D$1) {
super(D$1, !1), Cu(this, "options"), Cu(this, "cursor", 0), this.options = D$1.options;
const t = this.options.map(({ value: [s] }) => s?.toLowerCase());
this.cursor = Math.max(t.indexOf(D$1.initialValue), 0), this.on("key", (s) => {
if (!s || !t.includes(s)) return;
const i = this.options.find(({ value: [F$1] }) => F$1?.toLowerCase() === s);
i && (this.value = i.value, this.state = "submit", this.emit("submit"));
});
}
};
var eD = class extends p {
get userInputWithCursor() {
if (this.state === "submit") return this.userInput;
const D$1 = this.userInput;
if (this.cursor >= D$1.length) return `${this.userInput}\u2588`;
const t = D$1.slice(0, this.cursor), [s, ...i] = D$1.slice(this.cursor);
return `${t}${import_picocolors$3.default.inverse(s)}${i.join("")}`;
}
get cursor() {
return this._cursor;
}
constructor(D$1) {
super({
...D$1,
initialUserInput: D$1.initialUserInput ?? D$1.initialValue
}), this.on("userInput", (t) => {
this._setValue(t);
}), this.on("finalize", () => {
this.value || (this.value = D$1.defaultValue), this.value === void 0 && (this.value = "");
});
}
};
var sD = Object.defineProperty, iD = (e$1, D$1, t) => D$1 in e$1 ? sD(e$1, D$1, {
enumerable: !0,
configurable: !0,
writable: !0,
value: t
}) : e$1[D$1] = t, w = (e$1, D$1, t) => (iD(e$1, typeof D$1 != "symbol" ? D$1 + "" : D$1, t), t), P$1 = (e$1, D$1, t) => {
if (!D$1.has(e$1)) throw TypeError("Cannot " + t);
}, x$1 = (e$1, D$1, t) => (P$1(e$1, D$1, "read from private field"), t ? t.call(e$1) : D$1.get(e$1)), g = (e$1, D$1, t) => {
if (D$1.has(e$1)) throw TypeError("Cannot add the same private member more than once");
D$1 instanceof WeakSet ? D$1.add(e$1) : D$1.set(e$1, t);
}, m = (e$1, D$1, t, s) => (P$1(e$1, D$1, "write to private field"), s ? s.call(e$1, t) : D$1.set(e$1, t), t), nu = (e$1, D$1, t) => (P$1(e$1, D$1, "access private method"), t), B$1, k$1, I, v$1, R$1, ou, K$1, au;
function FD(e$1, D$1) {
if (e$1 === void 0 || D$1.length === 0) return 0;
const t = D$1.findIndex((s) => s.value === e$1);
return t !== -1 ? t : 0;
}
function rD(e$1, D$1) {
return (D$1.label ?? String(D$1.value)).toLowerCase().includes(e$1.toLowerCase());
}
function CD(e$1, D$1) {
if (D$1) return e$1 ? D$1 : D$1[0];
}
var nD = class extends p {
constructor(D$1) {
super(D$1), g(this, R$1), g(this, K$1), w(this, "filteredOptions"), w(this, "multiple"), w(this, "isNavigating", !1), w(this, "selectedValues", []), w(this, "focusedValue"), g(this, B$1, 0), g(this, k$1, ""), g(this, I, void 0), g(this, v$1, void 0), m(this, v$1, D$1.options);
const t = this.options;
this.filteredOptions = [...t], this.multiple = D$1.multiple === !0, m(this, I, D$1.filter ?? rD);
let s;
if (D$1.initialValue && Array.isArray(D$1.initialValue) ? this.multiple ? s = D$1.initialValue : s = D$1.initialValue.slice(0, 1) : !this.multiple && this.options.length > 0 && (s = [this.options[0].value]), s) for (const i of s) {
const F$1 = t.findIndex((u) => u.value === i);
F$1 !== -1 && (this.toggleSelected(i), m(this, B$1, F$1));
}
this.focusedValue = this.options[x$1(this, B$1)]?.value, this.on("key", (i, F$1) => nu(this, R$1, ou).call(this, i, F$1)), this.on("userInput", (i) => nu(this, K$1, au).call(this, i));
}
get cursor() {
return x$1(this, B$1);
}
get userInputWithCursor() {
if (!this.userInput) return import_picocolors$3.default.inverse(import_picocolors$3.default.hidden("_"));
if (this._cursor >= this.userInput.length) return `${this.userInput}\u2588`;
const D$1 = this.userInput.slice(0, this._cursor), [t, ...s] = this.userInput.slice(this._cursor);
return `${D$1}${import_picocolors$3.default.inverse(t)}${s.join("")}`;
}
get options() {
return typeof x$1(this, v$1) == "function" ? x$1(this, v$1).call(this) : x$1(this, v$1);
}
_isActionKey(D$1, t) {
return D$1 === " " || this.multiple && this.isNavigating && t.name === "space" && D$1 !== void 0 && D$1 !== "";
}
deselectAll() {
this.selectedValues = [];
}
toggleSelected(D$1) {
this.filteredOptions.length !== 0 && (this.multiple ? this.selectedValues.includes(D$1) ? this.selectedValues = this.selectedValues.filter((t) => t !== D$1) : this.selectedValues = [...this.selectedValues, D$1] : this.selectedValues = [D$1]);
}
};
B$1 = new WeakMap(), k$1 = new WeakMap(), I = new WeakMap(), v$1 = new WeakMap(), R$1 = new WeakSet(), ou = function(e$1, D$1) {
const t = D$1.name === "up", s = D$1.name === "down", i = D$1.name === "return";
t || s ? (m(this, B$1, Math.max(0, Math.min(x$1(this, B$1) + (t ? -1 : 1), this.filteredOptions.length - 1))), this.focusedValue = this.filteredOptions[x$1(this, B$1)]?.value, this.multiple || (this.selectedValues = [this.focusedValue]), this.isNavigating = !0) : i ? this.value = CD(this.multiple, this.selectedValues) : this.multiple ? this.focusedValue !== void 0 && (D$1.name === "tab" || this.isNavigating && D$1.name === "space") ? this.toggleSelected(this.focusedValue) : this.isNavigating = !1 : this.focusedValue && (this.selectedValues = [this.focusedValue]);
}, K$1 = new WeakSet(), au = function(e$1) {
if (e$1 !== x$1(this, k$1)) {
m(this, k$1, e$1);
const D$1 = this.options;
e$1 ? this.filteredOptions = D$1.filter((t) => x$1(this, I).call(this, e$1, t)) : this.filteredOptions = [...D$1], m(this, B$1, FD(this.focusedValue, this.filteredOptions)), this.focusedValue = this.filteredOptions[x$1(this, B$1)]?.value, this.multiple || (this.focusedValue !== void 0 ? this.toggleSelected(this.focusedValue) : this.deselectAll());
}
};
var import_picocolors$1 = __toESM$1(require_picocolors$1(), 1);
var import_picocolors$2 = __toESM$1(require_picocolors$1(), 1);
var import_src = __toESM$1(require_src(), 1);
function Pe() {
return process$1.platform !== "win32" ? process$1.env.TERM !== "linux" : !!process$1.env.CI || !!process$1.env.WT_SESSION || !!process$1.env.TERMINUS_SUBLIME || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
}
const N = Pe(), D = () => process.env.CI === "true", v = (t, i) => N ? t : i, ne = v("◆", "*"), G = v("■", "x"), F = v("▲", "x"), O = v("◇", "o"), oe = v("┌", "T"), o = v("│", "|"), f = v("└", "—"), P = v("●", ">"), L = v("○", " "), k = v("◻", "[•]"), x = v("◼", "[+]"), B = v("◻", "[ ]"), ae = v("▪", "•"), U = v("─", "-"), ue = v("╮", "+"), ce = v("├", "+"), le = v("╯", "+"), H = v("●", "•"), K = v("◆", "*"), q = v("▲", "!"), X = v("■", "x"), E = (t) => {
switch (t) {
case "initial":
case "active": return import_picocolors$2.default.cyan(ne);
case "cancel": return import_picocolors$2.default.red(G);
case "error": return import_picocolors$2.default.yellow(F);
case "submit": return import_picocolors$2.default.green(O);
}
}, j = (t) => {
const { cursor: i, options: r, style: s } = t, n$1 = t.output ?? process.stdout, a = n$1 instanceof WriteStream && n$1.rows !== void 0 ? n$1.rows : 10, l = import_picocolors$2.default.dim("..."), c$1 = t.maxItems ?? Number.POSITIVE_INFINITY, u = Math.max(a - 4, 0), $$1 = Math.min(u, Math.max(c$1, 5));
let m$1 = 0;
i >= m$1 + $$1 - 3 ? m$1 = Math.max(Math.min(i - $$1 + 3, r.length - $$1), 0) : i < m$1 + 2 && (m$1 = Math.max(i - 2, 0));
const h$1 = $$1 < r.length && m$1 > 0, g$1 = $$1 < r.length && m$1 + $$1 < r.length;
return r.slice(m$1, m$1 + $$1).map((p$1, d$1, y) => {
const w$1 = d$1 === 0 && h$1, b$1 = d$1 === y.length - 1 && g$1;
return w$1 || b$1 ? l : s(p$1, d$1 + m$1 === i);
});
};
function $e(t) {
return t.label ?? String(t.value ?? "");
}
function pe(t, i) {
if (!t) return !0;
const r = (i.label ?? String(i.value ?? "")).toLowerCase(), s = (i.hint ?? "").toLowerCase(), n$1 = String(i.value).toLowerCase(), a = t.toLowerCase();
return r.includes(a) || s.includes(a) || n$1.includes(a);
}
function Le(t, i) {
const r = [];
for (const s of i) t.includes(s.value) && r.push(s);
return r;
}
const me = (t) => new nD({
options: t.options,
initialValue: t.initialValue ? [t.initialValue] : void 0,
initialUserInput: t.initialUserInput,
filter: (i, r) => pe(i, r),
signal: t.signal,
input: t.input,
output: t.output,
validate: t.validate,
render() {
const i = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, r = this.userInput, s = String(this.value ?? ""), n$1 = this.options, a = t.placeholder, l = s === "" && a !== void 0;
switch (this.state) {
case "submit": {
const c$1 = Le(this.selectedValues, n$1), u = c$1.length > 0 ? c$1.map($e).join(", ") : "";
return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.dim(u)}`;
}
case "cancel": return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(r))}`;
default: {
const c$1 = this.isNavigating || l ? import_picocolors$2.default.dim(l ? a : r) : this.userInputWithCursor, u = this.filteredOptions.length !== n$1.length ? import_picocolors$2.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? "" : "es"})`) : "", $$1 = this.filteredOptions.length === 0 ? [] : j({
cursor: this.cursor,
options: this.filteredOptions,
style: (p$1, d$1) => {
const y = $e(p$1), w$1 = p$1.hint && p$1.value === this.focusedValue ? import_picocolors$2.default.dim(` (${p$1.hint})`) : "";
return d$1 ? `${import_picocolors$2.default.green(P)} ${y}${w$1}` : `${import_picocolors$2.default.dim(L)} ${import_picocolors$2.default.dim(y)}${w$1}`;
},
maxItems: t.maxItems,
output: t.output
}), m$1 = [
`${import_picocolors$2.default.dim("↑/↓")} to select`,
`${import_picocolors$2.default.dim("Enter:")} confirm`,
`${import_picocolors$2.default.dim("Type:")} to search`
], h$1 = this.filteredOptions.length === 0 && r ? [`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.yellow("No matches found")}`] : [], g$1 = this.state === "error" ? [`${import_picocolors$2.default.yellow(o)} ${import_picocolors$2.default.yellow(this.error)}`] : [];
return [
i,
`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.dim("Search:")} ${c$1}${u}`,
...h$1,
...g$1,
...$$1.map((p$1) => `${import_picocolors$2.default.cyan(o)} ${p$1}`),
`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.dim(m$1.join(" • "))}`,
`${import_picocolors$2.default.cyan(f)}`
].join(`
`);
}
}
}
}).prompt(), Ne = (t) => {
const i = (s, n$1, a, l) => {
const c$1 = a.includes(s.value), u = s.label ?? String(s.value ?? ""), $$1 = s.hint && l !== void 0 && s.value === l ? import_picocolors$2.default.dim(` (${s.hint})`) : "", m$1 = c$1 ? import_picocolors$2.default.green(x) : import_picocolors$2.default.dim(B);
return n$1 ? `${m$1} ${u}${$$1}` : `${m$1} ${import_picocolors$2.default.dim(u)}`;
}, r = new nD({
options: t.options,
multiple: !0,
filter: (s, n$1) => pe(s, n$1),
validate: () => {
if (t.required && r.selectedValues.length === 0) return "Please select at least one item";
},
initialValue: t.initialValues,
signal: t.signal,
input: t.input,
output: t.output,
render() {
const s = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, n$1 = this.userInput, a = t.placeholder, l = n$1 === "" && a !== void 0, c$1 = this.isNavigating || l ? import_picocolors$2.default.dim(l ? a : n$1) : this.userInputWithCursor, u = this.options, $$1 = this.filteredOptions.length !== u.length ? import_picocolors$2.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? "" : "es"})`) : "";
switch (this.state) {
case "submit": return `${s}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.dim(`${this.selectedValues.length} items selected`)}`;
case "cancel": return `${s}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(n$1))}`;
default: {
const m$1 = [
`${import_picocolors$2.default.dim("↑/↓")} to navigate`,
`${import_picocolors$2.default.dim("Space:")} select`,
`${import_picocolors$2.default.dim("Enter:")} confirm`,
`${import_picocolors$2.default.dim("Type:")} to search`
], h$1 = this.filteredOptions.length === 0 && n$1 ? [`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.yellow("No matches found")}`] : [], g$1 = this.state === "error" ? [`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.yellow(this.error)}`] : [], p$1 = j({
cursor: this.cursor,
options: this.filteredOptions,
style: (d$1, y) => i(d$1, y, this.selectedValues, this.focusedValue),
maxItems: t.maxItems,
output: t.output
});
return [
s,
`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.dim("Search:")} ${c$1}${$$1}`,
...h$1,
...g$1,
...p$1.map((d$1) => `${import_picocolors$2.default.cyan(o)} ${d$1}`),
`${import_picocolors$2.default.cyan(o)} ${import_picocolors$2.default.dim(m$1.join(" • "))}`,
`${import_picocolors$2.default.cyan(f)}`
].join(`
`);
}
}
}
});
return r.prompt();
}, ke = (t) => {
const i = t.active ?? "Yes", r = t.inactive ?? "No";
return new Wu({
active: i,
inactive: r,
signal: t.signal,
input: t.input,
output: t.output,
initialValue: t.initialValue ?? !0,
render() {
const s = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, n$1 = this.value ? i : r;
switch (this.state) {
case "submit": return `${s}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.dim(n$1)}`;
case "cancel": return `${s}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(n$1))}
${import_picocolors$2.default.gray(o)}`;
default: return `${s}${import_picocolors$2.default.cyan(o)} ${this.value ? `${import_picocolors$2.default.green(P)} ${i}` : `${import_picocolors$2.default.dim(L)} ${import_picocolors$2.default.dim(i)}`} ${import_picocolors$2.default.dim("/")} ${this.value ? `${import_picocolors$2.default.dim(L)} ${import_picocolors$2.default.dim(r)}` : `${import_picocolors$2.default.green(P)} ${r}`}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
}, Be = (t) => {
const { selectableGroups: i = !0, groupSpacing: r = 0 } = t, s = (a, l, c$1 = []) => {
const u = a.label ?? String(a.value), $$1 = typeof a.group == "string", m$1 = $$1 && (c$1[c$1.indexOf(a) + 1] ?? { group: !0 }), h$1 = $$1 && m$1.group === !0, g$1 = $$1 ? i ? `${h$1 ? f : o} ` : " " : "", p$1 = r > 0 && !$$1 ? `
${import_picocolors$2.default.cyan(o)} `.repeat(r) : "";
if (l === "active") return `${p$1}${import_picocolors$2.default.dim(g$1)}${import_picocolors$2.default.cyan(k)} ${u} ${a.hint ? import_picocolors$2.default.dim(`(${a.hint})`) : ""}`;
if (l === "group-active") return `${p$1}${g$1}${import_picocolors$2.default.cyan(k)} ${import_picocolors$2.default.dim(u)}`;
if (l === "group-active-selected") return `${p$1}${g$1}${import_picocolors$2.default.green(x)} ${import_picocolors$2.default.dim(u)}`;
if (l === "selected") {
const y = $$1 || i ? import_picocolors$2.default.green(x) : "";
return `${p$1}${import_picocolors$2.default.dim(g$1)}${y} ${import_picocolors$2.default.dim(u)} ${a.hint ? import_picocolors$2.default.dim(`(${a.hint})`) : ""}`;
}
if (l === "cancelled") return `${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(u))}`;
if (l === "active-selected") return `${p$1}${import_picocolors$2.default.dim(g$1)}${import_picocolors$2.default.green(x)} ${u} ${a.hint ? import_picocolors$2.default.dim(`(${a.hint})`) : ""}`;
if (l === "submitted") return `${import_picocolors$2.default.dim(u)}`;
const d$1 = $$1 || i ? import_picocolors$2.default.dim(B) : "";
return `${p$1}${import_picocolors$2.default.dim(g$1)}${d$1} ${import_picocolors$2.default.dim(u)}`;
}, n$1 = t.required ?? !0;
return new Ku({
options: t.options,
signal: t.signal,
input: t.input,
output: t.output,
initialValues: t.initialValues,
required: n$1,
cursorAt: t.cursorAt,
selectableGroups: i,
validate(a) {
if (n$1 && (a === void 0 || a.length === 0)) return `Please select at least one option.
${import_picocolors$2.default.reset(import_picocolors$2.default.dim(`Press ${import_picocolors$2.default.gray(import_picocolors$2.default.bgWhite(import_picocolors$2.default.inverse(" space ")))} to select, ${import_picocolors$2.default.gray(import_picocolors$2.default.bgWhite(import_picocolors$2.default.inverse(" enter ")))} to submit`))}`;
},
render() {
const a = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, l = this.value ?? [];
switch (this.state) {
case "submit": return `${a}${import_picocolors$2.default.gray(o)} ${this.options.filter(({ value: c$1 }) => l.includes(c$1)).map((c$1) => s(c$1, "submitted")).join(import_picocolors$2.default.dim(", "))}`;
case "cancel": {
const c$1 = this.options.filter(({ value: u }) => l.includes(u)).map((u) => s(u, "cancelled")).join(import_picocolors$2.default.dim(", "));
return `${a}${import_picocolors$2.default.gray(o)} ${c$1.trim() ? `${c$1}
${import_picocolors$2.default.gray(o)}` : ""}`;
}
case "error": {
const c$1 = this.error.split(`
`).map((u, $$1) => $$1 === 0 ? `${import_picocolors$2.default.yellow(f)} ${import_picocolors$2.default.yellow(u)}` : ` ${u}`).join(`
`);
return `${a}${import_picocolors$2.default.yellow(o)} ${this.options.map((u, $$1, m$1) => {
const h$1 = l.includes(u.value) || u.group === !0 && this.isGroupSelected(`${u.value}`), g$1 = $$1 === this.cursor;
return !g$1 && typeof u.group == "string" && this.options[this.cursor].value === u.group ? s(u, h$1 ? "group-active-selected" : "group-active", m$1) : g$1 && h$1 ? s(u, "active-selected", m$1) : h$1 ? s(u, "selected", m$1) : s(u, g$1 ? "active" : "inactive", m$1);
}).join(`
${import_picocolors$2.default.yellow(o)} `)}
${c$1}
`;
}
default: return `${a}${import_picocolors$2.default.cyan(o)} ${this.options.map((c$1, u, $$1) => {
const m$1 = l.includes(c$1.value) || c$1.group === !0 && this.isGroupSelected(`${c$1.value}`), h$1 = u === this.cursor;
return !h$1 && typeof c$1.group == "string" && this.options[this.cursor].value === c$1.group ? s(c$1, m$1 ? "group-active-selected" : "group-active", $$1) : h$1 && m$1 ? s(c$1, "active-selected", $$1) : m$1 ? s(c$1, "selected", $$1) : s(c$1, h$1 ? "active" : "inactive", $$1);
}).join(`
${import_picocolors$2.default.cyan(o)} `)}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
}, We = async (t, i) => {
const r = {}, s = Object.keys(t);
for (const n$1 of s) {
const a = t[n$1], l = await a({ results: r })?.catch((c$1) => {
throw c$1;
});
if (typeof i?.onCancel == "function" && Vu(l)) {
r[n$1] = "canceled", i.onCancel({ results: r });
continue;
}
r[n$1] = l;
}
return r;
}, T$2 = {
message: (t = [], { symbol: i = import_picocolors$2.default.gray(o), secondarySymbol: r = import_picocolors$2.default.gray(o), output: s = process.stdout, spacing: n$1 = 1 } = {}) => {
const a = [];
for (let c$1 = 0; c$1 < n$1; c$1++) a.push(`${r}`);
const l = Array.isArray(t) ? t : t.split(`
`);
if (l.length > 0) {
const [c$1, ...u] = l;
c$1.length > 0 ? a.push(`${i} ${c$1}`) : a.push(i);
for (const $$1 of u) $$1.length > 0 ? a.push(`${r} ${$$1}`) : a.push(r);
}
s.write(`${a.join(`
`)}
`);
},
info: (t, i) => {
T$2.message(t, {
...i,
symbol: import_picocolors$2.default.blue(H)
});
},
success: (t, i) => {
T$2.message(t, {
...i,
symbol: import_picocolors$2.default.green(K)
});
},
step: (t, i) => {
T$2.message(t, {
...i,
symbol: import_picocolors$2.default.green(O)
});
},
warn: (t, i) => {
T$2.message(t, {
...i,
symbol: import_picocolors$2.default.yellow(q)
});
},
warning: (t, i) => {
T$2.warn(t, i);
},
error: (t, i) => {
T$2.message(t, {
...i,
symbol: import_picocolors$2.default.red(X)
});
}
}, De = (t = "", i) => {
(i?.output ?? process.stdout).write(`${import_picocolors$2.default.gray(f)} ${import_picocolors$2.default.red(t)}
`);
}, Ge = (t = "", i) => {
(i?.output ?? process.stdout).write(`${import_picocolors$2.default.gray(oe)} ${t}
`);
}, Fe = (t = "", i) => {
(i?.output ?? process.stdout).write(`${import_picocolors$2.default.gray(o)}
${import_picocolors$2.default.gray(f)} ${t}
`);
}, Ue = (t) => {
const i = (s, n$1) => {
const a = s.label ?? String(s.value);
return n$1 === "active" ? `${import_picocolors$2.default.cyan(k)} ${a} ${s.hint ? import_picocolors$2.default.dim(`(${s.hint})`) : ""}` : n$1 === "selected" ? `${import_picocolors$2.default.green(x)} ${import_picocolors$2.default.dim(a)} ${s.hint ? import_picocolors$2.default.dim(`(${s.hint})`) : ""}` : n$1 === "cancelled" ? `${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(a))}` : n$1 === "active-selected" ? `${import_picocolors$2.default.green(x)} ${a} ${s.hint ? import_picocolors$2.default.dim(`(${s.hint})`) : ""}` : n$1 === "submitted" ? `${import_picocolors$2.default.dim(a)}` : `${import_picocolors$2.default.dim(B)} ${import_picocolors$2.default.dim(a)}`;
}, r = t.required ?? !0;
return new Uu({
options: t.options,
signal: t.signal,
input: t.input,
output: t.output,
initialValues: t.initialValues,
required: r,
cursorAt: t.cursorAt,
validate(s) {
if (r && (s === void 0 || s.length === 0)) return `Please select at least one option.
${import_picocolors$2.default.reset(import_picocolors$2.default.dim(`Press ${import_picocolors$2.default.gray(import_picocolors$2.default.bgWhite(import_picocolors$2.default.inverse(" space ")))} to select, ${import_picocolors$2.default.gray(import_picocolors$2.default.bgWhite(import_picocolors$2.default.inverse(" enter ")))} to submit`))}`;
},
render() {
const s = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, n$1 = this.value ?? [], a = (l, c$1) => {
const u = n$1.includes(l.value);
return c$1 && u ? i(l, "active-selected") : u ? i(l, "selected") : i(l, c$1 ? "active" : "inactive");
};
switch (this.state) {
case "submit": return `${s}${import_picocolors$2.default.gray(o)} ${this.options.filter(({ value: l }) => n$1.includes(l)).map((l) => i(l, "submitted")).join(import_picocolors$2.default.dim(", ")) || import_picocolors$2.default.dim("none")}`;
case "cancel": {
const l = this.options.filter(({ value: c$1 }) => n$1.includes(c$1)).map((c$1) => i(c$1, "cancelled")).join(import_picocolors$2.default.dim(", "));
return `${s}${import_picocolors$2.default.gray(o)} ${l.trim() ? `${l}
${import_picocolors$2.default.gray(o)}` : ""}`;
}
case "error": {
const l = this.error.split(`
`).map((c$1, u) => u === 0 ? `${import_picocolors$2.default.yellow(f)} ${import_picocolors$2.default.yellow(c$1)}` : ` ${c$1}`).join(`
`);
return `${s + import_picocolors$2.default.yellow(o)} ${j({
output: t.output,
options: this.options,
cursor: this.cursor,
maxItems: t.maxItems,
style: a
}).join(`
${import_picocolors$2.default.yellow(o)} `)}
${l}
`;
}
default: return `${s}${import_picocolors$2.default.cyan(o)} ${j({
output: t.output,
options: this.options,
cursor: this.cursor,
maxItems: t.maxItems,
style: a
}).join(`
${import_picocolors$2.default.cyan(o)} `)}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
}, He = (t) => import_picocolors$2.default.dim(t), Ke = (t = "", i = "", r) => {
const s = r?.format ?? He, n$1 = [
"",
...t.split(`
`).map(s),
""
], a = stripVTControlCharacters(i).length, l = r?.output ?? process.stdout, c$1 = Math.max(n$1.reduce(($$1, m$1) => {
const h$1 = stripVTControlCharacters(m$1);
return h$1.length > $$1 ? h$1.length : $$1;
}, 0), a) + 2, u = n$1.map(($$1) => `${import_picocolors$2.default.gray(o)} ${$$1}${" ".repeat(c$1 - stripVTControlCharacters($$1).length)}${import_picocolors$2.default.gray(o)}`).join(`
`);
l.write(`${import_picocolors$2.default.gray(o)}
${import_picocolors$2.default.green(O)} ${import_picocolors$2.default.reset(i)} ${import_picocolors$2.default.gray(U.repeat(Math.max(c$1 - a - 1, 1)) + ue)}
${u}
${import_picocolors$2.default.gray(ce + U.repeat(c$1 + 2) + le)}
`);
}, qe = (t) => new Hu({
validate: t.validate,
mask: t.mask ?? ae,
signal: t.signal,
input: t.input,
output: t.output,
render() {
const i = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, r = this.userInputWithCursor, s = this.masked;
switch (this.state) {
case "error": return `${i.trim()}
${import_picocolors$2.default.yellow(o)} ${s}
${import_picocolors$2.default.yellow(f)} ${import_picocolors$2.default.yellow(this.error)}
`;
case "submit": return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.dim(s)}`;
case "cancel": return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(s))}${s ? `
${import_picocolors$2.default.gray(o)}` : ""}`;
default: return `${i}${import_picocolors$2.default.cyan(o)} ${r}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt(), Xe = (t) => {
const i = t.validate;
return me({
...t,
initialUserInput: t.initialValue ?? t.root ?? process.cwd(),
maxItems: 5,
validate(r) {
if (!Array.isArray(r)) {
if (!r) return "Please select a path";
if (i) return i(r);
}
},
options() {
const r = this.userInput;
if (r === "") return [];
try {
let s;
return existsSync(r) ? lstatSync(r).isDirectory() ? s = r : s = dirname(r) : s = dirname(r), readdirSync(s).map((n$1) => {
const a = join(s, n$1), l = lstatSync(a);
return {
name: n$1,
path: a,
isDirectory: l.isDirectory()
};
}).filter(({ path: n$1, isDirectory: a }) => n$1.startsWith(r) && (t.directory || !a)).map((n$1) => ({ value: n$1.path }));
} catch {
return [];
}
}
});
}, J = ({ indicator: t = "dots", onCancel: i, output: r = process.stdout, cancelMessage: s, errorMessage: n$1, frames: a = N ? [
"◒",
"◐",
"◓",
"◑"
] : [
"•",
"o",
"O",
"0"
], delay: l = N ? 80 : 120, signal: c$1 } = {}) => {
const u = D();
let $$1, m$1, h$1 = !1, g$1 = !1, p$1 = "", d$1, y = performance.now();
const w$1 = (S$1) => {
const I$1 = S$1 > 1 ? n$1 ?? c.messages.error : s ?? c.messages.cancel;
g$1 = S$1 === 1, h$1 && (Z$1(I$1, S$1), g$1 && typeof i == "function" && i());
}, b$1 = () => w$1(2), M$1 = () => w$1(1), ge = () => {
process.on("uncaughtExceptionMonitor", b$1), process.on("unhandledRejection", b$1), process.on("SIGINT", M$1), process.on("SIGTERM", M$1), process.on("exit", w$1), c$1 && c$1.addEventListener("abort", M$1);
}, ye = () => {
process.removeListener("uncaughtExceptionMonitor", b$1), process.removeListener("unhandledRejection", b$1), process.removeListener("SIGINT", M$1), process.removeListener("SIGTERM", M$1), process.removeListener("exit", w$1), c$1 && c$1.removeEventListener("abort", M$1);
}, Y$1 = () => {
if (d$1 === void 0) return;
u && r.write(`
`);
const S$1 = d$1.split(`
`);
r.write(import_src.cursor.move(-999, S$1.length - 1)), r.write(import_src.erase.down(S$1.length));
}, z = (S$1) => S$1.replace(/\.+$/, ""), Q$1 = (S$1) => {
const I$1 = (performance.now() - S$1) / 1e3, _$1 = Math.floor(I$1 / 60), A = Math.floor(I$1 % 60);
return _$1 > 0 ? `[${_$1}m ${A}s]` : `[${A}s]`;
}, ve = (S$1 = "") => {
h$1 = !0, $$1 = Mu({ output: r }), p$1 = z(S$1), y = performance.now(), r.write(`${import_picocolors$2.default.gray(o)}
`);
let I$1 = 0, _$1 = 0;
ge(), m$1 = setInterval(() => {
if (u && p$1 === d$1) return;
Y$1(), d$1 = p$1;
const A = import_picocolors$2.default.magenta(a[I$1]);
if (u) r.write(`${A} ${p$1}...`);
else if (t === "timer") r.write(`${A} ${p$1} ${Q$1(y)}`);
else {
const fe = ".".repeat(Math.floor(_$1)).slice(0, 3);
r.write(`${A} ${p$1}${fe}`);
}
I$1 = I$1 + 1 < a.length ? I$1 + 1 : 0, _$1 = _$1 < 4 ? _$1 + .125 : 0;
}, l);
}, Z$1 = (S$1 = "", I$1 = 0) => {
h$1 = !1, clearInterval(m$1), Y$1();
const _$1 = I$1 === 0 ? import_picocolors$2.default.green(O) : I$1 === 1 ? import_picocolors$2.default.red(G) : import_picocolors$2.default.red(F);
p$1 = S$1 ?? p$1, t === "timer" ? r.write(`${_$1} ${p$1} ${Q$1(y)}
`) : r.write(`${_$1} ${p$1}
`), ye(), $$1();
};
return {
start: ve,
stop: Z$1,
message: (S$1 = "") => {
p$1 = z(S$1 ?? p$1);
},
get isCancelled() {
return g$1;
}
};
}, de = {
light: v("─", "-"),
heavy: v("━", "="),
block: v("█", "#")
};
const Ye = (t) => {
const i = (r, s = "inactive") => {
const n$1 = r.label ?? String(r.value);
return s === "selected" ? `${import_picocolors$2.default.dim(n$1)}` : s === "cancelled" ? `${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(n$1))}` : s === "active" ? `${import_picocolors$2.default.bgCyan(import_picocolors$2.default.gray(` ${r.value} `))} ${n$1} ${r.hint ? import_picocolors$2.default.dim(`(${r.hint})`) : ""}` : `${import_picocolors$2.default.gray(import_picocolors$2.default.bgWhite(import_picocolors$2.default.inverse(` ${r.value} `)))} ${n$1} ${r.hint ? import_picocolors$2.default.dim(`(${r.hint})`) : ""}`;
};
return new tD({
options: t.options,
signal: t.signal,
input: t.input,
output: t.output,
initialValue: t.initialValue,
render() {
const r = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`;
switch (this.state) {
case "submit": return `${r}${import_picocolors$2.default.gray(o)} ${i(this.options.find((s) => s.value === this.value) ?? t.options[0], "selected")}`;
case "cancel": return `${r}${import_picocolors$2.default.gray(o)} ${i(this.options[0], "cancelled")}
${import_picocolors$2.default.gray(o)}`;
default: return `${r}${import_picocolors$2.default.cyan(o)} ${this.options.map((s, n$1) => i(s, n$1 === this.cursor ? "active" : "inactive")).join(`
${import_picocolors$2.default.cyan(o)} `)}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
}, ze = (t) => {
const i = (r, s) => {
const n$1 = r.label ?? String(r.value);
switch (s) {
case "selected": return `${import_picocolors$2.default.dim(n$1)}`;
case "active": return `${import_picocolors$2.default.green(P)} ${n$1} ${r.hint ? import_picocolors$2.default.dim(`(${r.hint})`) : ""}`;
case "cancelled": return `${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(n$1))}`;
default: return `${import_picocolors$2.default.dim(L)} ${import_picocolors$2.default.dim(n$1)}`;
}
};
return new Xu({
options: t.options,
signal: t.signal,
input: t.input,
output: t.output,
initialValue: t.initialValue,
render() {
const r = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`;
switch (this.state) {
case "submit": return `${r}${import_picocolors$2.default.gray(o)} ${i(this.options[this.cursor], "selected")}`;
case "cancel": return `${r}${import_picocolors$2.default.gray(o)} ${i(this.options[this.cursor], "cancelled")}
${import_picocolors$2.default.gray(o)}`;
default: return `${r}${import_picocolors$2.default.cyan(o)} ${j({
output: t.output,
cursor: this.cursor,
options: this.options,
maxItems: t.maxItems,
style: (s, n$1) => i(s, n$1 ? "active" : "inactive")
}).join(`
${import_picocolors$2.default.cyan(o)} `)}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
}, he = `${import_picocolors$2.default.gray(o)} `, R = {
message: async (t, { symbol: i = import_picocolors$2.default.gray(o) } = {}) => {
process.stdout.write(`${import_picocolors$2.default.gray(o)}
${i} `);
let r = 3;
for await (let s of t) {
s = s.replace(/\n/g, `
${he}`), s.includes(`
`) && (r = 3 + stripVTControlCharacters(s.slice(s.lastIndexOf(`
`))).length);
const n$1 = stripVTControlCharacters(s).length;
r + n$1 < process.stdout.columns ? (r += n$1, process.stdout.write(s)) : (process.stdout.write(`
${he}${s.trimStart()}`), r = 3 + stripVTControlCharacters(s.trimStart()).length);
}
process.stdout.write(`
`);
},
info: (t) => R.message(t, { symbol: import_picocolors$2.default.blue(H) }),
success: (t) => R.message(t, { symbol: import_picocolors$2.default.green(K) }),
step: (t) => R.message(t, { symbol: import_picocolors$2.default.green(O) }),
warn: (t) => R.message(t, { symbol: import_picocolors$2.default.yellow(q) }),
warning: (t) => R.warn(t),
error: (t) => R.message(t, { symbol: import_picocolors$2.default.red(X) })
}, Qe = async (t, i) => {
for (const r of t) {
if (r.enabled === !1) continue;
const s = J(i);
s.start(r.title);
const n$1 = await r.task(s.message);
s.stop(n$1 || r.title);
}
}, Ze = (t) => {
const i = t.output ?? process.stdout, r = Ou(i), s = import_picocolors$1.gray(o), n$1 = t.spacing ?? 1, a = 3, l = t.retainLog === !0, c$1 = D();
i.write(`${s}
`), i.write(`${import_picocolors$1.green(O)} ${t.title}
`);
for (let d$1 = 0; d$1 < n$1; d$1++) i.write(`${s}
`);
let u = "", $$1 = "", m$1 = !1;
const h$1 = (d$1) => {
if (u.length === 0) return;
const y = u.split(`
`).reduce((w$1, b$1) => b$1 === "" ? w$1 + 1 : w$1 + Math.ceil((b$1.length + a) / r), 0) + 1 + (d$1 ? n$1 + 2 : 0);
i.write(import_src.erase.lines(y));
}, g$1 = (d$1, y) => {
T$2.message(d$1.split(`
`).map(import_picocolors$1.dim), {
output: i,
secondarySymbol: s,
symbol: s,
spacing: y ?? n$1
});
}, p$1 = () => {
l === !0 && $$1.length > 0 ? g$1(`${$$1}
${u}`) : g$1(u);
};
return {
message(d$1, y) {
if (h$1(!1), (y?.raw !== !0 || !m$1) && u !== "" && (u += `
`), u += d$1, m$1 = y?.raw === !0, t.limit !== void 0) {
const w$1 = u.split(`
`), b$1 = w$1.length - t.limit;
if (b$1 > 0) {
const M$1 = w$1.splice(0, b$1);
l && ($$1 += ($$1 === "" ? "" : `
`) + M$1.join(`
`));
}
u = w$1.join(`
`);
}
c$1 || g$1(u, 0);
},
error(d$1, y) {
h$1(!0), T$2.error(d$1, {
output: i,
secondarySymbol: s,
spacing: 1
}), y?.showLog !== !1 && p$1(), u = $$1 = "";
},
success(d$1, y) {
h$1(!0), T$2.success(d$1, {
output: i,
secondarySymbol: s,
spacing: 1
}), y?.showLog === !0 && p$1(), u = $$1 = "";
}
};
}, et = (t) => new eD({
validate: t.validate,
placeholder: t.placeholder,
defaultValue: t.defaultValue,
initialValue: t.initialValue,
output: t.output,
signal: t.signal,
input: t.input,
render() {
const i = `${import_picocolors$2.default.gray(o)}
${E(this.state)} ${t.message}
`, r = t.placeholder ? import_picocolors$2.default.inverse(t.placeholder[0]) + import_picocolors$2.default.dim(t.placeholder.slice(1)) : import_picocolors$2.default.inverse(import_picocolors$2.default.hidden("_")), s = this.userInput ? this.userInputWithCursor : r, n$1 = this.value ?? "";
switch (this.state) {
case "error": return `${i.trim()}
${import_picocolors$2.default.yellow(o)} ${s}
${import_picocolors$2.default.yellow(f)} ${import_picocolors$2.default.yellow(this.error)}
`;
case "submit": return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.dim(n$1)}`;
case "cancel": return `${i}${import_picocolors$2.default.gray(o)} ${import_picocolors$2.default.strikethrough(import_picocolors$2.default.dim(n$1))}${n$1.trim() ? `
${import_picocolors$2.default.gray(o)}` : ""}`;
default: return `${i}${import_picocolors$2.default.cyan(o)} ${s}
${import_picocolors$2.default.cyan(f)}
`;
}
}
}).prompt();
var utils_exports = {};
__export(utils_exports, { createPrinter: () => createPrinter });
function createPrinter(...conditions) {
const printers = conditions.map((condition) => {
return (content, alt = "") => condition ? content : alt;
});
return printers;
}
function splitVersion(str) {
const [major, minor, patch] = str?.split(".") ?? [];
function toVersionNumber(val) {
return val !== undefined && val !== "" && !isNaN(Number(val)) ? Number(val) : undefined;
}
return {
major: toVersionNumber(major),
minor: toVersionNumber(minor),
patch: toVersionNumber(patch)
};
}
function isVersionUnsupportedBelow(versionStr, belowStr) {
const version = splitVersion(versionStr);
const below = splitVersion(belowStr);
if (version.major === undefined || below.major === undefined) return undefined;
if (version.major < below.major) return true;
if (version.major > below.major) return false;
if (version.minor === undefined || below.minor === undefined) if (version.major === below.major) return false;
else return true;
if (version.minor < below.minor) return true;
if (version.minor > below.minor) return false;
if (version.patch === undefined || below.patch === undefined) if (version.minor === below.minor) return false;
else return true;
if (version.patch < below.patch) return true;
if (version.patch > below.patch) return false;
if (version.patch === below.patch) return false;
return undefined;
}
var import_picocolors = __toESM$1(require_picocolors$1(), 1);
var colors = import_picocolors.default;
//#endregion
//#region packages/addons/devtools-json/index.ts
var devtools_json_default = defineAddon({
id: "devtools-json",
shortDescription: "devtools json",
homepage: "https://github.com/ChromeDevTools/vite-plugin-devtools-json",
options: {},
run: ({ sv, viteConfigFile }) => {
sv.devDependency("vite-plugin-devtools-json", "^1.0.0");
sv.file(viteConfigFile, (content) => {
const { ast, generateCode } = parseScript$1(content);
const vitePluginName = "devtoolsJson";
imports_exports.addDefault(ast, {
as: vitePluginName,
from: "vite-plugin-devtools-json"
});
vite_exports.addPlugin(ast, { code: `${vitePluginName}()` });
return generateCode();
});
}
});
//#endregion
//#region packages/addons/common.ts
function addEslintConfigPrettier(content) {
const { ast, generateCode } = parseScript$1(content);
const importNodes = ast.body.filter((n$1) => n$1.type === "ImportDeclaration");
const sveltePluginImport = importNodes.find((n$1) => n$1.type === "ImportDeclaration" && n$1.source.value === "eslint-plugin-svelte" && n$1.specifiers?.some((n$2) => n$2.type === "ImportDefaultSpecifier"));
let svelteImportName;
for (const specifier of sveltePluginImport?.specifiers ?? []) if (specifier.type === "ImportDefaultSpecifier" && specifier.local?.name) svelteImportName = specifier.local.name;
svelteImportName ??= "svelte";
imports_exports.addDefault(ast, {
from: "eslint-plugin-svelte",
as: svelteImportName
});
imports_exports.addDefault(ast, {
from: "eslint-config-prettier",
as: "prettier"
});
const fallbackConfig = common_exports.parseExpression("[]");
const defaultExport = exports_exports.createDefault(ast, { fallback: fallbackConfig });
const eslintConfig = defaultExport.value;
if (eslintConfig.type !== "ArrayExpression" && eslintConfig.type !== "CallExpression") return content;
const prettier = common_exports.parseExpression("prettier");
const sveltePrettierConfig = common_exports.parseExpression(`${svelteImportName}.configs.prettier`);
const configSpread = common_exports.createSpread(sveltePrettierConfig);
const nodesToInsert = [];
if (!common_exports.contains(eslintConfig, prettier)) nodesToInsert.push(prettier);
if (!common_exports.contains(eslintConfig, configSpread)) nodesToInsert.push(configSpread);
const elements = eslintConfig.type === "ArrayExpression" ? eslintConfig.elements : eslintConfig.arguments;
const idx = elements.findIndex((el) => el?.type === "SpreadElement" && el.argument.type === "MemberExpression" && el.argument.object.type === "MemberExpression" && el.argument.object.property.type === "Identifier" && el.argument.object.property.name === "configs" && el.argument.object.object.type === "Identifier" && el.argument.object.object.name === svelteImportName);
if (idx !== -1) elements.splice(idx + 1, 0, ...nodesToInsert);
else elements.push(...nodesToInsert);
return generateCode();
}
function addToDemoPage(content, path$1) {
const { template, generateCode } = parseSvelte(content);
for (const node of template.ast.childNodes) if (node.type === "tag" && node.attribs["href"] === `/demo/${path$1}`) return content;
const newLine = template.source ? "\n" : "";
const src = template.source + `${newLine}<a href="/demo/${path$1}">${path$1}</a>`;
return generateCode({ template: src });
}
function getNodeTypesVersion() {
const nodeVersion = process$1.versions.node;
const isDenoOrBun = Boolean(process$1.versions.deno ?? process$1.versions.bun);
const [major] = nodeVersion.split(".");
const majorNum = Number(major);
const isEvenMajor = majorNum % 2 === 0;
const isLTS = !!process$1.release.lts || isDenoOrBun && isEvenMajor;
if (isLTS) return `^${major}`;
const previousLTSMajor = isEvenMajor ? majorNum - 2 : majorNum - 1;
return `^${previousLTSMajor}`;
}
//#endregion
//#region packages/addons/drizzle/index.ts
const PORTS = {
mysql: "3306",
postgresql: "5432",
sqlite: ""
};
const options$5 = defineAddonOptions({
database: {
question: "Which database would you like to use?",
type: "select",
default: "sqlite",
options: [
{
value: "postgresql",
label: "PostgreSQL"
},
{
value: "mysql",
label: "MySQL"
},
{
value: "sqlite",
label: "SQLite"
}
]
},
postgresql: {
question: "Which PostgreSQL client would you like to use?",
type: "select",
group: "client",
default: "postgres.js",
options: [{
value: "postgres.js",
label: "Postgres.JS",
hint: "recommended for most users"
}, {
value: "neon",
label: "Neon",
hint: "popular hosted platform"
}],
condition: ({ database }) => database === "postgresql"
},
mysql: {
question: "Which MySQL client would you like to use?",
type: "select",
group: "client",
default: "mysql2",
options: [{
value: "mysql2",
hint: "recommended for most users"
}, {
value: "planetscale",
label: "PlanetScale",
hint: "popular hosted platform"
}],
condition: ({ database }) => database === "mysql"
},
sqlite: {
question: "Which SQLite client would you like to use?",
type: "select",
group: "client",
default: "libsql",
options: [
{
value: "better-sqlite3",
hint: "for traditional Node environments"
},
{
value: "libsql",
label: "libSQL",
hint: "for serverless environments"
},
{
value: "turso",
label: "Turso",
hint: "popular hosted platform"
}
],
condition: ({ database }) => database === "sqlite"
},
docker: {
question: "Do you want to run the database locally with docker-compose?",
default: false,
type: "boolean",
condition: ({ database, mysql, postgresql }) => database === "mysql" && mysql === "mysql2" || database === "postgresql" && postgresql === "postgres.js"
}
});
var drizzle_default = defineAddon({
id: "drizzle",
shortDescription: "database orm",
homepage: "https://orm.drizzle.team",
options: options$5,
setup: ({ kit, unsupported, runsAfter, cwd, typescript }) => {
runsAfter("prettier");
const ext = typescript ? "ts" : "js";
if (!kit) return unsupported("Requires SvelteKit");
const baseDBPath = path.resolve(kit.libDirectory, "server", "db");
const paths = {
"drizzle config": path.relative(cwd, path.resolve(cwd, `drizzle.config.${ext}`)),
"database schema": path.relative(cwd, path.resolve(baseDBPath, `schema.${ext}`)),
database: path.relative(cwd, path.resolve(baseDBPath, `index.${ext}`))
};
for (const [fileType, filePath] of Object.entries(paths)) if (fs.existsSync(filePath)) unsupported(`Preexisting ${fileType} file at '${filePath}'`);
},
run: ({ sv, typescript, options: options$6, kit, dependencyVersion }) => {
const ext = typescript ? "ts" : "js";
sv.dependency("drizzle-orm", "^0.40.0");
sv.devDependency("drizzle-kit", "^0.30.2");
sv.devDependency("@types/node", getNodeTypesVersion());
if (options$6.mysql === "mysql2") sv.dependency("mysql2", "^3.12.0");
if (options$6.mysql === "planetscale") sv.dependency("@planetscale/database", "^1.19.0");
if (options$6.postgresql === "neon") sv.dependency("@neondatabase/serverless", "^0.10.4");
if (options$6.postgresql === "postgres.js") sv.dependency("postgres", "^3.4.5");
if (options$6.sqlite === "better-sqlite3") {
sv.dependency("better-sqlite3", "^11.8.0");
sv.devDependency("@types/better-sqlite3", "^7.6.12");
sv.pnpmBuildDependendency("better-sqlite3");
}
if (options$6.sqlite === "libsql" || options$6.sqlite === "turso") sv.dependency("@libsql/client", "^0.14.0");
sv.file(".env", (content) => generateEnvFileContent(content, options$6));
sv.file(".env.example", (content) => generateEnvFileContent(content, options$6));
if (options$6.docker && (options$6.mysql === "mysql2" || options$6.postgresql === "postgres.js")) sv.file("docker-compose.yml", (content) => {
if (content.length > 0) return content;
const imageName = options$6.database === "mysql" ? "mysql" : "postgres";
const port = PORTS[options$6.database];
const USER = "root";
const PASSWORD = "mysecretpassword";
const DB_NAME = "local";
let dbSpecificContent = "";
if (options$6.mysql === "mysql2") dbSpecificContent = `
MYSQL_ROOT_PASSWORD: ${PASSWORD}
MYSQL_DATABASE: ${DB_NAME}
volumes:
- mysqldata:/var/lib/mysql
volumes:
mysqldata:
`;
if (options$6.postgresql === "postgres.js") dbSpecificContent = `
POSTGRES_USER: ${USER}
POSTGRES_PASSWORD: ${PASSWORD}
POSTGRES_DB: ${DB_NAME}
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
`;
content = dedent_default`
services:
db:
image: ${imageName}
restart: always
ports:
- ${port}:${port}
environment: ${dbSpecificContent}
`;
return content;
});
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
data.scripts ??= {};
const scripts = data.scripts;
if (options$6.docker) scripts["db:start"] ??= "docker compose up";
scripts["db:push"] ??= "drizzle-kit push";
scripts["db:generate"] ??= "drizzle-kit generate";
scripts["db:migrate"] ??= "drizzle-kit migrate";
scripts["db:studio"] ??= "drizzle-kit studio";
return generateCode();
});
const hasPrettier = Boolean(dependencyVersion("prettier"));
if (hasPrettier) sv.file(".prettierignore", (content) => {
if (!content.includes(`/drizzle/`)) return content.trimEnd() + "\n/drizzle/";
return content;
});
if (options$6.database === "sqlite") sv.file(".gitignore", (content) => {
if (content.length === 0) return content;
if (!content.includes("\n*.db")) content = content.trimEnd() + "\n\n# SQLite\n*.db";
return content;
});
sv.file(`drizzle.config.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamed(ast, {
from: "drizzle-kit",
imports: { defineConfig: "defineConfig" }
});
ast.body.push(common_exports.parseStatement("if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not set');"));
exports_exports.createDefault(ast, { fallback: common_exports.parseExpression(`
defineConfig({
schema: "./src/lib/server/db/schema.${typescript ? "ts" : "js"}",
dialect: "${options$6.sqlite === "turso" ? "turso" : options$6.database}",
dbCredentials: {
${options$6.sqlite === "turso" ? "authToken: process.env.DATABASE_AUTH_TOKEN," : ""}
url: process.env.DATABASE_URL
},
verbose: true,
strict: true
})`) });
return generateCode();
});
sv.file(`${kit?.libDirectory}/server/db/schema.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
let userSchemaExpression;
if (options$6.database === "sqlite") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/sqlite-core",
imports: ["sqliteTable", "integer"]
});
userSchemaExpression = common_exports.parseExpression(`sqliteTable('user', {
id: integer('id').primaryKey(),
age: integer('age')
})`);
}
if (options$6.database === "mysql") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/mysql-core",
imports: [
"mysqlTable",
"serial",
"int"
]
});
userSchemaExpression = common_exports.parseExpression(`mysqlTable('user', {
id: serial('id').primaryKey(),
age: int('age'),
})`);
}
if (options$6.database === "postgresql") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/pg-core",
imports: [
"pgTable",
"serial",
"integer"
]
});
userSchemaExpression = common_exports.parseExpression(`pgTable('user', {
id: serial('id').primaryKey(),
age: integer('age'),
})`);
}
if (!userSchemaExpression) throw new Error("unreachable state...");
const userIdentifier = variables_exports.declaration(ast, {
kind: "const",
name: "user",
value: userSchemaExpression
});
exports_exports.createNamed(ast, {
name: "user",
fallback: userIdentifier
});
return generateCode();
});
sv.file(`${kit?.libDirectory}/server/db/index.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamed(ast, {
from: "$env/dynamic/private",
imports: ["env"]
});
imports_exports.addNamespace(ast, {
from: "./schema",
as: "schema"
});
const dbURLCheck = common_exports.parseStatement("if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');");
ast.body.push(dbURLCheck);
let clientExpression;
if (options$6.sqlite === "better-sqlite3") {
imports_exports.addDefault(ast, {
from: "better-sqlite3",
as: "Database"
});
imports_exports.addNamed(ast, {
from: "drizzle-orm/better-sqlite3",
imports: ["drizzle"]
});
clientExpression = common_exports.parseExpression("new Database(env.DATABASE_URL)");
}
if (options$6.sqlite === "libsql" || options$6.sqlite === "turso") {
imports_exports.addNamed(ast, {
from: "@libsql/client",
imports: ["createClient"]
});
imports_exports.addNamed(ast, {
from: "drizzle-orm/libsql",
imports: ["drizzle"]
});
if (options$6.sqlite === "turso") {
imports_exports.addNamed(ast, {
from: "$app/environment",
imports: ["dev"]
});
const authTokenCheck = common_exports.parseStatement("if (!dev && !env.DATABASE_AUTH_TOKEN) throw new Error('DATABASE_AUTH_TOKEN is not set');");
ast.body.push(authTokenCheck);
clientExpression = common_exports.parseExpression("createClient({ url: env.DATABASE_URL, authToken: env.DATABASE_AUTH_TOKEN })");
} else clientExpression = common_exports.parseExpression("createClient({ url: env.DATABASE_URL })");
}
if (options$6.mysql === "mysql2" || options$6.mysql === "planetscale") {
imports_exports.addDefault(ast, {
from: "mysql2/promise",
as: "mysql"
});
imports_exports.addNamed(ast, {
from: "drizzle-orm/mysql2",
imports: ["drizzle"]
});
clientExpression = common_exports.parseExpression("mysql.createPool(env.DATABASE_URL)");
}
if (options$6.postgresql === "neon") {
imports_exports.addNamed(ast, {
from: "@neondatabase/serverless",
imports: ["neon"]
});
imports_exports.addNamed(ast, {
from: "drizzle-orm/neon-http",
imports: ["drizzle"]
});
clientExpression = common_exports.parseExpression("neon(env.DATABASE_URL)");
}
if (options$6.postgresql === "postgres.js") {
imports_exports.addDefault(ast, {
from: "postgres",
as: "postgres"
});
imports_exports.addNamed(ast, {
from: "drizzle-orm/postgres-js",
imports: ["drizzle"]
});
clientExpression = common_exports.parseExpression("postgres(env.DATABASE_URL)");
}
if (!clientExpression) throw new Error("unreachable state...");
ast.body.push(variables_exports.declaration(ast, {
kind: "const",
name: "client",
value: clientExpression
}));
const drizzleCall = function_exports.createCall({
name: "drizzle",
args: ["client"],
useIdentifiers: true
});
const paramObject = object_exports.create({ schema: variables_exports.createIdentifier("schema") });
if (options$6.database === "mysql") {
const mode = options$6.mysql === "planetscale" ? "planetscale" : "default";
object_exports.property(paramObject, {
name: "mode",
fallback: common_exports.createLiteral(mode)
});
}
drizzleCall.arguments.push(paramObject);
const db = variables_exports.declaration(ast, {
kind: "const",
name: "db",
value: drizzleCall
});
exports_exports.createNamed(ast, {
name: "db",
fallback: db
});
return generateCode();
});
},
nextSteps: ({ options: options$6, highlighter, packageManager }) => {
const steps = [`You will need to set ${highlighter.env("DATABASE_URL")} in your production environment`];
if (options$6.docker) {
const { command: command$1, args: args$1 } = resolveCommand(packageManager, "run", ["db:start"]);
steps.push(`Run ${highlighter.command(`${command$1} ${args$1.join(" ")}`)} to start the docker container`);
} else steps.push(`Check ${highlighter.env("DATABASE_URL")} in ${highlighter.path(".env")} and adjust it to your needs`);
const { command, args } = resolveCommand(packageManager, "run", ["db:push"]);
steps.push(`Run ${highlighter.command(`${command} ${args.join(" ")}`)} to update your database schema`);
return steps;
}
});
function generateEnvFileContent(content, opts) {
const DB_URL_KEY = "DATABASE_URL";
if (opts.docker) {
const protocol = opts.database === "mysql" ? "mysql" : "postgres";
const port = PORTS[opts.database];
content = addEnvVar(content, DB_URL_KEY, `"${protocol}://root:mysecretpassword@localhost:${port}/local"`);
return content;
}
if (opts.sqlite === "better-sqlite3" || opts.sqlite === "libsql") {
const dbFile = opts.sqlite === "libsql" ? "file:local.db" : "local.db";
content = addEnvVar(content, DB_URL_KEY, dbFile);
return content;
}
content = addEnvComment(content, "Replace with your DB credentials!");
if (opts.sqlite === "turso") {
content = addEnvVar(content, DB_URL_KEY, "\"libsql://db-name-user.turso.io\"");
content = addEnvVar(content, "DATABASE_AUTH_TOKEN", "\"\"");
content = addEnvComment(content, "A local DB can also be used in dev as well");
content = addEnvComment(content, `${DB_URL_KEY}="file:local.db"`);
}
if (opts.database === "mysql") content = addEnvVar(content, DB_URL_KEY, "\"mysql://user:password@host:port/db-name\"");
if (opts.database === "postgresql") content = addEnvVar(content, DB_URL_KEY, "\"postgres://user:password@host:port/db-name\"");
return content;
}
function addEnvVar(content, key, value) {
if (!content.includes(key + "=")) content = appendEnvContent(content, `${key}=${value}`);
return content;
}
function addEnvComment(content, comment) {
const commented = `# ${comment}`;
if (!content.includes(commented)) content = appendEnvContent(content, commented);
return content;
}
function appendEnvContent(existing, content) {
const withNewLine = !existing.length || existing.endsWith("\n") ? existing : existing + "\n";
return withNewLine + content + "\n";
}
//#endregion
//#region packages/addons/eslint/index.ts
var eslint_default = defineAddon({
id: "eslint",
shortDescription: "linter",
homepage: "https://eslint.org",
options: {},
run: ({ sv, typescript, dependencyVersion }) => {
const prettierInstalled = Boolean(dependencyVersion("prettier"));
sv.devDependency("eslint", "^9.18.0");
sv.devDependency("@eslint/compat", "^1.2.5");
sv.devDependency("eslint-plugin-svelte", "^3.0.0");
sv.devDependency("globals", "^16.0.0");
sv.devDependency("@eslint/js", "^9.18.0");
if (typescript) sv.devDependency("typescript-eslint", "^8.20.0");
if (prettierInstalled) sv.devDependency("eslint-config-prettier", "^10.0.1");
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
data.scripts ??= {};
const scripts = data.scripts;
const LINT_CMD = "eslint .";
scripts["lint"] ??= LINT_CMD;
if (!scripts["lint"].includes(LINT_CMD)) scripts["lint"] += ` && ${LINT_CMD}`;
return generateCode();
});
sv.file(".vscode/settings.json", (content) => {
if (!content) return content;
const { data, generateCode } = parseJson$1(content);
const validate = data["eslint.validate"];
if (validate && !validate.includes("svelte")) validate.push("svelte");
return generateCode();
});
sv.file("eslint.config.js", (content) => {
const { ast, generateCode } = parseScript$1(content);
const eslintConfigs = [];
imports_exports.addDefault(ast, {
from: "./svelte.config.js",
as: "svelteConfig"
});
const gitIgnorePathStatement = common_exports.parseStatement("\nconst gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));");
common_exports.appendStatement(ast, { statement: gitIgnorePathStatement });
const ignoresConfig = common_exports.parseExpression("includeIgnoreFile(gitignorePath)");
eslintConfigs.push(ignoresConfig);
const jsConfig = common_exports.parseExpression("js.configs.recommended");
eslintConfigs.push(jsConfig);
if (typescript) {
const tsConfig = common_exports.parseExpression("ts.configs.recommended");
eslintConfigs.push(common_exports.createSpread(tsConfig));
}
const svelteConfig = common_exports.parseExpression("svelte.configs.recommended");
eslintConfigs.push(common_exports.createSpread(svelteConfig));
const globalsBrowser = common_exports.createSpread(common_exports.parseExpression("globals.browser"));
const globalsNode = common_exports.createSpread(common_exports.parseExpression("globals.node"));
const globalsObjLiteral = object_exports.create({});
globalsObjLiteral.properties = [globalsBrowser, globalsNode];
const rules = object_exports.create({ "\"no-undef\"": "off" });
if (rules.properties[0].type !== "Property") throw new Error("rules.properties[0].type !== \"Property\"");
rules.properties[0].key.leadingComments = [{
type: "Line",
value: " typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects."
}, {
type: "Line",
value: " see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors"
}];
const globalsConfig = object_exports.create({
languageOptions: { globals: globalsObjLiteral },
rules: typescript ? rules : undefined
});
eslintConfigs.push(globalsConfig);
if (typescript) {
const svelteTSParserConfig = object_exports.create({
files: [
"**/*.svelte",
"**/*.svelte.ts",
"**/*.svelte.js"
],
languageOptions: { parserOptions: {
projectService: true,
extraFileExtensions: [".svelte"],
parser: variables_exports.createIdentifier("ts.parser"),
svelteConfig: variables_exports.createIdentifier("svelteConfig")
} }
});
eslintConfigs.push(svelteTSParserConfig);
} else {
const svelteTSParserConfig = object_exports.create({
files: ["**/*.svelte", "**/*.svelte.js"],
languageOptions: { parserOptions: { svelteConfig: variables_exports.createIdentifier("svelteConfig") } }
});
eslintConfigs.push(svelteTSParserConfig);
}
let exportExpression;
if (typescript) {
const tsConfigCall = function_exports.createCall({
name: "ts.config",
args: []
});
tsConfigCall.arguments.push(...eslintConfigs);
exportExpression = tsConfigCall;
} else {
const eslintArray = array_exports.create();
eslintConfigs.map((x$2) => array_exports.append(eslintArray, x$2));
exportExpression = eslintArray;
}
const { value: defaultExport, astNode } = exports_exports.createDefault(ast, { fallback: exportExpression });
if (defaultExport !== exportExpression) {
T$2.warn("An eslint config is already defined. Skipping initialization.");
return content;
}
if (!typescript) common_exports.addJsDocTypeComment(astNode, { type: "import('eslint').Linter.Config[]" });
if (typescript) imports_exports.addDefault(ast, {
from: "typescript-eslint",
as: "ts"
});
imports_exports.addNamed(ast, {
from: "node:url",
imports: ["fileURLToPath"]
});
imports_exports.addDefault(ast, {
from: "globals",
as: "globals"
});
imports_exports.addDefault(ast, {
from: "eslint-plugin-svelte",
as: "svelte"
});
imports_exports.addDefault(ast, {
from: "@eslint/js",
as: "js"
});
imports_exports.addNamed(ast, {
from: "@eslint/compat",
imports: ["includeIgnoreFile"]
});
return generateCode();
});
if (prettierInstalled) sv.file("eslint.config.js", addEslintConfigPrettier);
}
});
//#endregion
//#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
const comma = ",".charCodeAt(0);
const semicolon = ";".charCodeAt(0);
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const intToChar = new Uint8Array(64);
const charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
const c$1 = chars.charCodeAt(i);
intToChar[i] = c$1;
charToInt[c$1] = i;
}
function encodeInteger(builder, num, relative) {
let delta = num - relative;
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
do {
let clamped = delta & 31;
delta >>>= 5;
if (delta > 0) clamped |= 32;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
const bufLength = 16384;
const td = typeof TextDecoder !== "undefined" ? /* #__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
return out.toString();
} } : { decode(buf) {
let out = "";
for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
return out;
} };
var StringWriter = class {
constructor() {
this.pos = 0;
this.out = "";
this.buffer = new Uint8Array(bufLength);
}
write(v$2) {
const { buffer } = this;
buffer[this.pos++] = v$2;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
};
function encode(decoded) {
const writer = new StringWriter();
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
if (i > 0) writer.write(semicolon);
if (line.length === 0) continue;
let genColumn = 0;
for (let j$2 = 0; j$2 < line.length; j$2++) {
const segment = line[j$2];
if (j$2 > 0) writer.write(comma);
genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) continue;
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
sourceLine = encodeInteger(writer, segment[2], sourceLine);
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) continue;
namesIndex = encodeInteger(writer, segment[4], namesIndex);
}
}
return writer.flush();
}
//#endregion
//#region node_modules/.pnpm/magic-string@0.30.17/node_modules/magic-string/dist/magic-string.es.mjs
var BitSet = class BitSet {
constructor(arg) {
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
}
add(n$1) {
this.bits[n$1 >> 5] |= 1 << (n$1 & 31);
}
has(n$1) {
return !!(this.bits[n$1 >> 5] & 1 << (n$1 & 31));
}
};
var Chunk = class Chunk {
constructor(start, end, content) {
this.start = start;
this.end = end;
this.original = content;
this.intro = "";
this.outro = "";
this.content = content;
this.storeName = false;
this.edited = false;
{
this.previous = null;
this.next = null;
}
}
appendLeft(content) {
this.outro += content;
}
appendRight(content) {
this.intro = this.intro + content;
}
clone() {
const chunk = new Chunk(this.start, this.end, this.original);
chunk.intro = this.intro;
chunk.outro = this.outro;
chunk.content = this.content;
chunk.storeName = this.storeName;
chunk.edited = this.edited;
return chunk;
}
contains(index) {
return this.start < index && index < this.end;
}
eachNext(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.next;
}
}
eachPrevious(fn) {
let chunk = this;
while (chunk) {
fn(chunk);
chunk = chunk.previous;
}
}
edit(content, storeName, contentOnly) {
this.content = content;
if (!contentOnly) {
this.intro = "";
this.outro = "";
}
this.storeName = storeName;
this.edited = true;
return this;
}
prependLeft(content) {
this.outro = content + this.outro;
}
prependRight(content) {
this.intro = content + this.intro;
}
reset() {
this.intro = "";
this.outro = "";
if (this.edited) {
this.content = this.original;
this.storeName = false;
this.edited = false;
}
}
split(index) {
const sliceIndex = index - this.start;
const originalBefore = this.original.slice(0, sliceIndex);
const originalAfter = this.original.slice(sliceIndex);
this.original = originalBefore;
const newChunk = new Chunk(index, this.end, originalAfter);
newChunk.outro = this.outro;
this.outro = "";
this.end = index;
if (this.edited) {
newChunk.edit("", false);
this.content = "";
} else this.content = originalBefore;
newChunk.next = this.next;
if (newChunk.next) newChunk.next.previous = newChunk;
newChunk.previous = this;
this.next = newChunk;
return newChunk;
}
toString() {
return this.intro + this.content + this.outro;
}
trimEnd(rx) {
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
this.split(this.start + trimmed.length).edit("", undefined, true);
if (this.edited) this.edit(trimmed, this.storeName, true);
}
return true;
} else {
this.edit("", undefined, true);
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
}
}
trimStart(rx) {
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
const trimmed = this.content.replace(rx, "");
if (trimmed.length) {
if (trimmed !== this.content) {
const newChunk = this.split(this.end - trimmed.length);
if (this.edited) newChunk.edit(trimmed, this.storeName, true);
this.edit("", undefined, true);
}
return true;
} else {
this.edit("", undefined, true);
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
}
}
};
function getBtoa() {
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
else return () => {
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
};
}
const btoa = /*#__PURE__*/ getBtoa();
var SourceMap = class {
constructor(properties) {
this.version = 3;
this.file = properties.file;
this.sources = properties.sources;
this.sourcesContent = properties.sourcesContent;
this.names = properties.names;
this.mappings = encode(properties.mappings);
if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
}
toString() {
return JSON.stringify(this);
}
toUrl() {
return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
}
};
function guessIndent(code) {
const lines = code.split("\n");
const tabbed = lines.filter((line) => /^\t+/.test(line));
const spaced = lines.filter((line) => /^ {2,}/.test(line));
if (tabbed.length === 0 && spaced.length === 0) return null;
if (tabbed.length >= spaced.length) return " ";
const min = spaced.reduce((previous, current) => {
const numSpaces = /^ +/.exec(current)[0].length;
return Math.min(numSpaces, previous);
}, Infinity);
return new Array(min + 1).join(" ");
}
function getRelativePath(from, to) {
const fromParts = from.split(/[/\\]/);
const toParts = to.split(/[/\\]/);
fromParts.pop();
while (fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
if (fromParts.length) {
let i = fromParts.length;
while (i--) fromParts[i] = "..";
}
return fromParts.concat(toParts).join("/");
}
const toString = Object.prototype.toString;
function isObject(thing) {
return toString.call(thing) === "[object Object]";
}
function getLocator(source) {
const originalLines = source.split("\n");
const lineOffsets = [];
for (let i = 0, pos = 0; i < originalLines.length; i++) {
lineOffsets.push(pos);
pos += originalLines[i].length + 1;
}
return function locate(index) {
let i = 0;
let j$2 = lineOffsets.length;
while (i < j$2) {
const m$1 = i + j$2 >> 1;
if (index < lineOffsets[m$1]) j$2 = m$1;
else i = m$1 + 1;
}
const line = i - 1;
const column = index - lineOffsets[line];
return {
line,
column
};
};
}
const wordRegex = /\w/;
var Mappings = class {
constructor(hires) {
this.hires = hires;
this.generatedCodeLine = 0;
this.generatedCodeColumn = 0;
this.raw = [];
this.rawSegments = this.raw[this.generatedCodeLine] = [];
this.pending = null;
}
addEdit(sourceIndex, content, loc, nameIndex) {
if (content.length) {
const contentLengthMinusOne = content.length - 1;
let contentLineEnd = content.indexOf("\n", 0);
let previousContentLineEnd = -1;
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
const segment$1 = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment$1.push(nameIndex);
this.rawSegments.push(segment$1);
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
previousContentLineEnd = contentLineEnd;
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
}
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (nameIndex >= 0) segment.push(nameIndex);
this.rawSegments.push(segment);
this.advance(content.slice(previousContentLineEnd + 1));
} else if (this.pending) {
this.rawSegments.push(this.pending);
this.advance(content);
}
this.pending = null;
}
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
let originalCharIndex = chunk.start;
let first = true;
let charInHiresBoundary = false;
while (originalCharIndex < chunk.end) {
if (original[originalCharIndex] === "\n") {
loc.line += 1;
loc.column = 0;
this.generatedCodeLine += 1;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
this.generatedCodeColumn = 0;
first = true;
charInHiresBoundary = false;
} else {
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
const segment = [
this.generatedCodeColumn,
sourceIndex,
loc.line,
loc.column
];
if (this.hires === "boundary") if (wordRegex.test(original[originalCharIndex])) {
if (!charInHiresBoundary) {
this.rawSegments.push(segment);
charInHiresBoundary = true;
}
} else {
this.rawSegments.push(segment);
charInHiresBoundary = false;
}
else this.rawSegments.push(segment);
}
loc.column += 1;
this.generatedCodeColumn += 1;
first = false;
}
originalCharIndex += 1;
}
this.pending = null;
}
advance(str) {
if (!str) return;
const lines = str.split("\n");
if (lines.length > 1) {
for (let i = 0; i < lines.length - 1; i++) {
this.generatedCodeLine++;
this.raw[this.generatedCodeLine] = this.rawSegments = [];
}
this.generatedCodeColumn = 0;
}
this.generatedCodeColumn += lines[lines.length - 1].length;
}
};
const n = "\n";
const warned = {
insertLeft: false,
insertRight: false,
storeName: false
};
var MagicString = class MagicString {
constructor(string, options$6 = {}) {
const chunk = new Chunk(0, string.length, string);
Object.defineProperties(this, {
original: {
writable: true,
value: string
},
outro: {
writable: true,
value: ""
},
intro: {
writable: true,
value: ""
},
firstChunk: {
writable: true,
value: chunk
},
lastChunk: {
writable: true,
value: chunk
},
lastSearchedChunk: {
writable: true,
value: chunk
},
byStart: {
writable: true,
value: {}
},
byEnd: {
writable: true,
value: {}
},
filename: {
writable: true,
value: options$6.filename
},
indentExclusionRanges: {
writable: true,
value: options$6.indentExclusionRanges
},
sourcemapLocations: {
writable: true,
value: new BitSet()
},
storedNames: {
writable: true,
value: {}
},
indentStr: {
writable: true,
value: undefined
},
ignoreList: {
writable: true,
value: options$6.ignoreList
},
offset: {
writable: true,
value: options$6.offset || 0
}
});
this.byStart[0] = chunk;
this.byEnd[string.length] = chunk;
}
addSourcemapLocation(char) {
this.sourcemapLocations.add(char);
}
append(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.outro += content;
return this;
}
appendLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.appendLeft(content);
else this.intro += content;
return this;
}
appendRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.appendRight(content);
else this.outro += content;
return this;
}
clone() {
const cloned = new MagicString(this.original, {
filename: this.filename,
offset: this.offset
});
let originalChunk = this.firstChunk;
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
while (originalChunk) {
cloned.byStart[clonedChunk.start] = clonedChunk;
cloned.byEnd[clonedChunk.end] = clonedChunk;
const nextOriginalChunk = originalChunk.next;
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
if (nextClonedChunk) {
clonedChunk.next = nextClonedChunk;
nextClonedChunk.previous = clonedChunk;
clonedChunk = nextClonedChunk;
}
originalChunk = nextOriginalChunk;
}
cloned.lastChunk = clonedChunk;
if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
cloned.intro = this.intro;
cloned.outro = this.outro;
return cloned;
}
generateDecodedMap(options$6) {
options$6 = options$6 || {};
const sourceIndex = 0;
const names = Object.keys(this.storedNames);
const mappings = new Mappings(options$6.hires);
const locate = getLocator(this.original);
if (this.intro) mappings.advance(this.intro);
this.firstChunk.eachNext((chunk) => {
const loc = locate(chunk.start);
if (chunk.intro.length) mappings.advance(chunk.intro);
if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
if (chunk.outro.length) mappings.advance(chunk.outro);
});
return {
file: options$6.file ? options$6.file.split(/[/\\]/).pop() : undefined,
sources: [options$6.source ? getRelativePath(options$6.file || "", options$6.source) : options$6.file || ""],
sourcesContent: options$6.includeContent ? [this.original] : undefined,
names,
mappings: mappings.raw,
x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
};
}
generateMap(options$6) {
return new SourceMap(this.generateDecodedMap(options$6));
}
_ensureindentStr() {
if (this.indentStr === undefined) this.indentStr = guessIndent(this.original);
}
_getRawIndentString() {
this._ensureindentStr();
return this.indentStr;
}
getIndentString() {
this._ensureindentStr();
return this.indentStr === null ? " " : this.indentStr;
}
indent(indentStr, options$6) {
const pattern = /^[^\r\n]/gm;
if (isObject(indentStr)) {
options$6 = indentStr;
indentStr = undefined;
}
if (indentStr === undefined) {
this._ensureindentStr();
indentStr = this.indentStr || " ";
}
if (indentStr === "") return this;
options$6 = options$6 || {};
const isExcluded = {};
if (options$6.exclude) {
const exclusions = typeof options$6.exclude[0] === "number" ? [options$6.exclude] : options$6.exclude;
exclusions.forEach((exclusion) => {
for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
});
}
let shouldIndentNextCharacter = options$6.indentStart !== false;
const replacer = (match) => {
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
shouldIndentNextCharacter = true;
return match;
};
this.intro = this.intro.replace(pattern, replacer);
let charIndex = 0;
let chunk = this.firstChunk;
while (chunk) {
const end = chunk.end;
if (chunk.edited) {
if (!isExcluded[charIndex]) {
chunk.content = chunk.content.replace(pattern, replacer);
if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
}
} else {
charIndex = chunk.start;
while (charIndex < end) {
if (!isExcluded[charIndex]) {
const char = this.original[charIndex];
if (char === "\n") shouldIndentNextCharacter = true;
else if (char !== "\r" && shouldIndentNextCharacter) {
shouldIndentNextCharacter = false;
if (charIndex === chunk.start) chunk.prependRight(indentStr);
else {
this._splitChunk(chunk, charIndex);
chunk = chunk.next;
chunk.prependRight(indentStr);
}
}
}
charIndex += 1;
}
}
charIndex = chunk.end;
chunk = chunk.next;
}
this.outro = this.outro.replace(pattern, replacer);
return this;
}
insert() {
throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
}
insertLeft(index, content) {
if (!warned.insertLeft) {
console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
warned.insertLeft = true;
}
return this.appendLeft(index, content);
}
insertRight(index, content) {
if (!warned.insertRight) {
console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
warned.insertRight = true;
}
return this.prependRight(index, content);
}
move(start, end, index) {
start = start + this.offset;
end = end + this.offset;
index = index + this.offset;
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
this._split(start);
this._split(end);
this._split(index);
const first = this.byStart[start];
const last = this.byEnd[end];
const oldLeft = first.previous;
const oldRight = last.next;
const newRight = this.byStart[index];
if (!newRight && last === this.lastChunk) return this;
const newLeft = newRight ? newRight.previous : this.lastChunk;
if (oldLeft) oldLeft.next = oldRight;
if (oldRight) oldRight.previous = oldLeft;
if (newLeft) newLeft.next = first;
if (newRight) newRight.previous = last;
if (!first.previous) this.firstChunk = last.next;
if (!last.next) {
this.lastChunk = first.previous;
this.lastChunk.next = null;
}
first.previous = newLeft;
last.next = newRight || null;
if (!newLeft) this.firstChunk = first;
if (!newRight) this.lastChunk = last;
return this;
}
overwrite(start, end, content, options$6) {
options$6 = options$6 || {};
return this.update(start, end, content, {
...options$6,
overwrite: !options$6.contentOnly
});
}
update(start, end, content, options$6) {
start = start + this.offset;
end = end + this.offset;
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (end > this.original.length) throw new Error("end is out of bounds");
if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
this._split(start);
this._split(end);
if (options$6 === true) {
if (!warned.storeName) {
console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
warned.storeName = true;
}
options$6 = { storeName: true };
}
const storeName = options$6 !== undefined ? options$6.storeName : false;
const overwrite = options$6 !== undefined ? options$6.overwrite : false;
if (storeName) {
const original = this.original.slice(start, end);
Object.defineProperty(this.storedNames, original, {
writable: true,
value: true,
enumerable: true
});
}
const first = this.byStart[start];
const last = this.byEnd[end];
if (first) {
let chunk = first;
while (chunk !== last) {
if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
chunk = chunk.next;
chunk.edit("", false);
}
first.edit(content, storeName, !overwrite);
} else {
const newChunk = new Chunk(start, end, "").edit(content, storeName);
last.next = newChunk;
newChunk.previous = last;
}
return this;
}
prepend(content) {
if (typeof content !== "string") throw new TypeError("outro content must be a string");
this.intro = content + this.intro;
return this;
}
prependLeft(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byEnd[index];
if (chunk) chunk.prependLeft(content);
else this.intro = content + this.intro;
return this;
}
prependRight(index, content) {
index = index + this.offset;
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
this._split(index);
const chunk = this.byStart[index];
if (chunk) chunk.prependRight(content);
else this.outro = content + this.outro;
return this;
}
remove(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.intro = "";
chunk.outro = "";
chunk.edit("");
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
reset(start, end) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
if (start === end) return this;
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
if (start > end) throw new Error("end must be greater than start");
this._split(start);
this._split(end);
let chunk = this.byStart[start];
while (chunk) {
chunk.reset();
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
}
return this;
}
lastChar() {
if (this.outro.length) return this.outro[this.outro.length - 1];
let chunk = this.lastChunk;
do {
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
} while (chunk = chunk.previous);
if (this.intro.length) return this.intro[this.intro.length - 1];
return "";
}
lastLine() {
let lineIndex = this.outro.lastIndexOf(n);
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
let lineStr = this.outro;
let chunk = this.lastChunk;
do {
if (chunk.outro.length > 0) {
lineIndex = chunk.outro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.outro + lineStr;
}
if (chunk.content.length > 0) {
lineIndex = chunk.content.lastIndexOf(n);
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
lineStr = chunk.content + lineStr;
}
if (chunk.intro.length > 0) {
lineIndex = chunk.intro.lastIndexOf(n);
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
lineStr = chunk.intro + lineStr;
}
} while (chunk = chunk.previous);
lineIndex = this.intro.lastIndexOf(n);
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
return this.intro + lineStr;
}
slice(start = 0, end = this.original.length - this.offset) {
start = start + this.offset;
end = end + this.offset;
if (this.original.length !== 0) {
while (start < 0) start += this.original.length;
while (end < 0) end += this.original.length;
}
let result = "";
let chunk = this.firstChunk;
while (chunk && (chunk.start > start || chunk.end <= start)) {
if (chunk.start < end && chunk.end >= end) return result;
chunk = chunk.next;
}
if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
const startChunk = chunk;
while (chunk) {
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
const containsEnd = chunk.start < end && chunk.end >= end;
if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
result += chunk.content.slice(sliceStart, sliceEnd);
if (chunk.outro && (!containsEnd || chunk.end === end)) result += chunk.outro;
if (containsEnd) break;
chunk = chunk.next;
}
return result;
}
snip(start, end) {
const clone = this.clone();
clone.remove(0, start);
clone.remove(end, clone.original.length);
return clone;
}
_split(index) {
if (this.byStart[index] || this.byEnd[index]) return;
let chunk = this.lastSearchedChunk;
const searchForward = index > chunk.end;
while (chunk) {
if (chunk.contains(index)) return this._splitChunk(chunk, index);
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
}
}
_splitChunk(chunk, index) {
if (chunk.edited && chunk.content.length) {
const loc = getLocator(this.original)(index);
throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
}
const newChunk = chunk.split(index);
this.byEnd[index] = chunk;
this.byStart[index] = newChunk;
this.byEnd[newChunk.end] = newChunk;
if (chunk === this.lastChunk) this.lastChunk = newChunk;
this.lastSearchedChunk = chunk;
return true;
}
toString() {
let str = this.intro;
let chunk = this.firstChunk;
while (chunk) {
str += chunk.toString();
chunk = chunk.next;
}
return str + this.outro;
}
isEmpty() {
let chunk = this.firstChunk;
do
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
while (chunk = chunk.next);
return true;
}
length() {
let chunk = this.firstChunk;
let length = 0;
do
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
while (chunk = chunk.next);
return length;
}
trimLines() {
return this.trim("[\\r\\n]");
}
trim(charType) {
return this.trimStart(charType).trimEnd(charType);
}
trimEndAborted(charType) {
const rx = new RegExp((charType || "\\s") + "+$");
this.outro = this.outro.replace(rx, "");
if (this.outro.length) return true;
let chunk = this.lastChunk;
do {
const end = chunk.end;
const aborted = chunk.trimEnd(rx);
if (chunk.end !== end) {
if (this.lastChunk === chunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.previous;
} while (chunk);
return false;
}
trimEnd(charType) {
this.trimEndAborted(charType);
return this;
}
trimStartAborted(charType) {
const rx = new RegExp("^" + (charType || "\\s") + "+");
this.intro = this.intro.replace(rx, "");
if (this.intro.length) return true;
let chunk = this.firstChunk;
do {
const end = chunk.end;
const aborted = chunk.trimStart(rx);
if (chunk.end !== end) {
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
this.byEnd[chunk.end] = chunk;
this.byStart[chunk.next.start] = chunk.next;
this.byEnd[chunk.next.end] = chunk.next;
}
if (aborted) return true;
chunk = chunk.next;
} while (chunk);
return false;
}
trimStart(charType) {
this.trimStartAborted(charType);
return this;
}
hasChanged() {
return this.original !== this.toString();
}
_replaceRegexp(searchValue, replacement) {
function getReplacement(match, str) {
if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_$1, i) => {
if (i === "$") return "$";
if (i === "&") return match[0];
const num = +i;
if (num < match.length) return match[+i];
return `$${i}`;
});
else return replacement(...match, match.index, str, match.groups);
}
function matchAll(re, str) {
let match;
const matches = [];
while (match = re.exec(str)) matches.push(match);
return matches;
}
if (searchValue.global) {
const matches = matchAll(searchValue, this.original);
matches.forEach((match) => {
if (match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
});
} else {
const match = this.original.match(searchValue);
if (match && match.index != null) {
const replacement$1 = getReplacement(match, this.original);
if (replacement$1 !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement$1);
}
}
return this;
}
_replaceString(string, replacement) {
const { original } = this;
const index = original.indexOf(string);
if (index !== -1) this.overwrite(index, index + string.length, replacement);
return this;
}
replace(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
return this._replaceRegexp(searchValue, replacement);
}
_replaceAllString(string, replacement) {
const { original } = this;
const stringLength = string.length;
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
const previous = original.slice(index, index + stringLength);
if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
}
return this;
}
replaceAll(searchValue, replacement) {
if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
return this._replaceRegexp(searchValue, replacement);
}
};
//#endregion
//#region packages/addons/lucia/index.ts
const TABLE_TYPE = {
mysql: "mysqlTable",
postgresql: "pgTable",
sqlite: "sqliteTable",
turso: "sqliteTable"
};
let drizzleDialect;
let schemaPath;
const options$4 = defineAddonOptions({ demo: {
type: "boolean",
default: true,
question: `Do you want to include a demo? ${colors.dim("(includes a login/register page)")}`
} });
var lucia_default = defineAddon({
id: "lucia",
shortDescription: "auth guide",
homepage: "https://lucia-auth.com",
options: options$4,
setup: ({ kit, dependencyVersion, unsupported, dependsOn, runsAfter }) => {
if (!kit) unsupported("Requires SvelteKit");
if (!dependencyVersion("drizzle-orm")) dependsOn("drizzle");
runsAfter("tailwindcss");
},
run: ({ sv, typescript, options: options$6, kit, dependencyVersion }) => {
const ext = typescript ? "ts" : "js";
sv.dependency("@oslojs/crypto", "^1.0.1");
sv.dependency("@oslojs/encoding", "^1.1.0");
if (options$6.demo) sv.dependency("@node-rs/argon2", "^2.0.2");
sv.file(`drizzle.config.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
const isProp = (name, node) => node.key.type === "Identifier" && node.key.name === name;
walk_exports.walk(ast, null, { Property(node) {
if (isProp("dialect", node) && node.value.type === "Literal" && typeof node.value.value === "string") drizzleDialect = node.value.value;
if (isProp("schema", node) && node.value.type === "Literal" && typeof node.value.value === "string") schemaPath = node.value.value;
} });
if (!drizzleDialect) throw new Error("Failed to detect DB dialect in your `drizzle.config.[js|ts]` file");
if (!schemaPath) throw new Error("Failed to find schema path in your `drizzle.config.[js|ts]` file");
return generateCode();
});
sv.file(schemaPath, (content) => {
const { ast, generateCode } = parseScript$1(content);
const createTable = (name) => function_exports.createCall({
name: TABLE_TYPE[drizzleDialect],
args: [name]
});
const userDecl = variables_exports.declaration(ast, {
kind: "const",
name: "user",
value: createTable("user")
});
const sessionDecl = variables_exports.declaration(ast, {
kind: "const",
name: "session",
value: createTable("session")
});
const user = exports_exports.createNamed(ast, {
name: "user",
fallback: userDecl
});
const session = exports_exports.createNamed(ast, {
name: "session",
fallback: sessionDecl
});
const userTable = getCallExpression(user);
const sessionTable = getCallExpression(session);
if (!userTable || !sessionTable) throw new Error("failed to find call expression of `user` or `session`");
if (userTable.arguments.length === 1) userTable.arguments.push(object_exports.create({}));
if (sessionTable.arguments.length === 1) sessionTable.arguments.push(object_exports.create({}));
const userAttributes = userTable.arguments[1];
const sessionAttributes = sessionTable.arguments[1];
if (userAttributes?.type !== "ObjectExpression" || sessionAttributes?.type !== "ObjectExpression") throw new Error("unexpected shape of `user` or `session` table definition");
if (drizzleDialect === "sqlite" || drizzleDialect === "turso") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/sqlite-core",
imports: [
"sqliteTable",
"text",
"integer"
]
});
object_exports.overrideProperties(userAttributes, { properties: { id: common_exports.parseExpression("text('id').primaryKey()") } });
if (options$6.demo) object_exports.overrideProperties(userAttributes, { properties: {
username: common_exports.parseExpression("text('username').notNull().unique()"),
passwordHash: common_exports.parseExpression("text('password_hash').notNull()")
} });
object_exports.overrideProperties(sessionAttributes, { properties: {
id: common_exports.parseExpression("text('id').primaryKey()"),
userId: common_exports.parseExpression("text('user_id').notNull().references(() => user.id)"),
expiresAt: common_exports.parseExpression("integer('expires_at', { mode: 'timestamp' }).notNull()")
} });
}
if (drizzleDialect === "mysql") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/mysql-core",
imports: [
"mysqlTable",
"varchar",
"datetime"
]
});
object_exports.overrideProperties(userAttributes, { properties: { id: common_exports.parseExpression("varchar('id', { length: 255 }).primaryKey()") } });
if (options$6.demo) object_exports.overrideProperties(userAttributes, { properties: {
username: common_exports.parseExpression("varchar('username', { length: 32 }).notNull().unique()"),
passwordHash: common_exports.parseExpression("varchar('password_hash', { length: 255 }).notNull()")
} });
object_exports.overrideProperties(sessionAttributes, { properties: {
id: common_exports.parseExpression("varchar('id', { length: 255 }).primaryKey()"),
userId: common_exports.parseExpression("varchar('user_id', { length: 255 }).notNull().references(() => user.id)"),
expiresAt: common_exports.parseExpression("datetime('expires_at').notNull()")
} });
}
if (drizzleDialect === "postgresql") {
imports_exports.addNamed(ast, {
from: "drizzle-orm/pg-core",
imports: [
"pgTable",
"text",
"timestamp"
]
});
object_exports.overrideProperties(userAttributes, { properties: { id: common_exports.parseExpression("text('id').primaryKey()") } });
if (options$6.demo) object_exports.overrideProperties(userAttributes, { properties: {
username: common_exports.parseExpression("text('username').notNull().unique()"),
passwordHash: common_exports.parseExpression("text('password_hash').notNull()")
} });
object_exports.overrideProperties(sessionAttributes, { properties: {
id: common_exports.parseExpression("text('id').primaryKey()"),
userId: common_exports.parseExpression("text('user_id').notNull().references(() => user.id)"),
expiresAt: common_exports.parseExpression("timestamp('expires_at', { withTimezone: true, mode: 'date' }).notNull()")
} });
}
let code = generateCode();
if (typescript) {
if (!code.includes("export type Session =")) code += "\n\nexport type Session = typeof session.$inferSelect;";
if (!code.includes("export type User =")) code += "\n\nexport type User = typeof user.$inferSelect;";
}
return code;
});
sv.file(`${kit?.libDirectory}/server/auth.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamespace(ast, {
from: "$lib/server/db/schema",
as: "table"
});
imports_exports.addNamed(ast, {
from: "$lib/server/db",
imports: ["db"]
});
imports_exports.addNamed(ast, {
from: "@oslojs/encoding",
imports: ["encodeBase64url", "encodeHexLowerCase"]
});
imports_exports.addNamed(ast, {
from: "@oslojs/crypto/sha2",
imports: ["sha256"]
});
imports_exports.addNamed(ast, {
from: "drizzle-orm",
imports: ["eq"]
});
if (typescript) imports_exports.addNamed(ast, {
from: "@sveltejs/kit",
imports: ["RequestEvent"],
isType: true
});
const ms = new MagicString(generateCode().trim());
const [ts] = utils_exports.createPrinter(typescript);
if (!ms.original.includes("const DAY_IN_MS")) ms.append("\n\nconst DAY_IN_MS = 1000 * 60 * 60 * 24;");
if (!ms.original.includes("export const sessionCookieName")) ms.append("\n\nexport const sessionCookieName = 'auth-session';");
if (!ms.original.includes("export function generateSessionToken")) {
const generateSessionToken = dedent_default`
export function generateSessionToken() {
const bytes = crypto.getRandomValues(new Uint8Array(18));
const token = encodeBase64url(bytes);
return token;
}`;
ms.append(`\n\n${generateSessionToken}`);
}
if (!ms.original.includes("async function createSession")) {
const createSession = dedent_default`
${ts("", "/**")}
${ts("", " * @param {string} token")}
${ts("", " * @param {string} userId")}
${ts("", " */")}
export async function createSession(token${ts(": string")}, userId${ts(": string")}) {
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
const session${ts(": table.Session")} = {
id: sessionId,
userId,
expiresAt: new Date(Date.now() + DAY_IN_MS * 30)
};
await db.insert(table.session).values(session);
return session;
}`;
ms.append(`\n\n${createSession}`);
}
if (!ms.original.includes("async function validateSessionToken")) {
const validateSessionToken = dedent_default`
${ts("", "/** @param {string} token */")}
export async function validateSessionToken(token${ts(": string")}) {
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
const [result] = await db
.select({
// Adjust user table here to tweak returned data
user: { id: table.user.id, username: table.user.username },
session: table.session
})
.from(table.session)
.innerJoin(table.user, eq(table.session.userId, table.user.id))
.where(eq(table.session.id, sessionId));
if (!result) {
return { session: null, user: null };
}
const { session, user } = result;
const sessionExpired = Date.now() >= session.expiresAt.getTime();
if (sessionExpired) {
await db.delete(table.session).where(eq(table.session.id, session.id));
return { session: null, user: null };
}
const renewSession = Date.now() >= session.expiresAt.getTime() - DAY_IN_MS * 15;
if (renewSession) {
session.expiresAt = new Date(Date.now() + DAY_IN_MS * 30);
await db
.update(table.session)
.set({ expiresAt: session.expiresAt })
.where(eq(table.session.id, session.id));
}
return { session, user };
}`;
ms.append(`\n\n${validateSessionToken}`);
}
if (typescript && !ms.original.includes("export type SessionValidationResult")) {
const sessionType = "export type SessionValidationResult = Awaited<ReturnType<typeof validateSessionToken>>;";
ms.append(`\n\n${sessionType}`);
}
if (!ms.original.includes("async function invalidateSession")) {
const invalidateSession = dedent_default`
${ts("", "/** @param {string} sessionId */")}
export async function invalidateSession(sessionId${ts(": string")}) {
await db.delete(table.session).where(eq(table.session.id, sessionId));
}`;
ms.append(`\n\n${invalidateSession}`);
}
if (!ms.original.includes("export function setSessionTokenCookie")) {
const setSessionTokenCookie = dedent_default`
${ts("", "/**")}
${ts("", " * @param {import(\"@sveltejs/kit\").RequestEvent} event")}
${ts("", " * @param {string} token")}
${ts("", " * @param {Date} expiresAt")}
${ts("", " */")}
export function setSessionTokenCookie(event${ts(": RequestEvent")}, token${ts(": string")}, expiresAt${ts(": Date")}) {
event.cookies.set(sessionCookieName, token, {
expires: expiresAt,
path: '/'
});
}`;
ms.append(`\n\n${setSessionTokenCookie}`);
}
if (!ms.original.includes("export function deleteSessionTokenCookie")) {
const deleteSessionTokenCookie = dedent_default`
${ts("", "/** @param {import(\"@sveltejs/kit\").RequestEvent} event */")}
export function deleteSessionTokenCookie(event${ts(": RequestEvent")}) {
event.cookies.delete(sessionCookieName, {
path: '/'
});
}`;
ms.append(`\n\n${deleteSessionTokenCookie}`);
}
return ms.toString();
});
if (typescript) sv.file("src/app.d.ts", (content) => {
const { ast, generateCode } = parseScript$1(content);
const locals = kit_exports.addGlobalAppInterface(ast, { name: "Locals" });
if (!locals) throw new Error("Failed detecting `locals` interface in `src/app.d.ts`");
const user = locals.body.body.find((prop) => common_exports.hasTypeProperty(prop, { name: "user" }));
const session = locals.body.body.find((prop) => common_exports.hasTypeProperty(prop, { name: "session" }));
if (!user) locals.body.body.push(createLuciaType("user"));
if (!session) locals.body.body.push(createLuciaType("session"));
return generateCode();
});
sv.file(`src/hooks.server.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamespace(ast, {
from: "$lib/server/auth",
as: "auth"
});
kit_exports.addHooksHandle(ast, {
typescript,
newHandleName: "handleAuth",
handleContent: getAuthHandleContent()
});
return generateCode();
});
if (options$6.demo) {
sv.file(`${kit?.routesDirectory}/demo/+page.svelte`, (content) => {
return addToDemoPage(content, "lucia");
});
sv.file(`${kit.routesDirectory}/demo/lucia/login/+page.server.${ext}`, (content) => {
if (content) {
const filePath = `${kit.routesDirectory}/demo/lucia/login/+page.server.${typescript ? "ts" : "js"}`;
T$2.warn(`Existing ${colors.yellow(filePath)} file. Could not update.`);
return content;
}
const [ts] = utils_exports.createPrinter(typescript);
return dedent_default`
import { hash, verify } from '@node-rs/argon2';
import { encodeBase32LowerCase } from '@oslojs/encoding';
import { fail, redirect } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
import * as auth from '$lib/server/auth';
import { db } from '$lib/server/db';
import * as table from '$lib/server/db/schema';
${ts("import type { Actions, PageServerLoad } from './$types';\n")}
export const load${ts(": PageServerLoad")} = async (event) => {
if (event.locals.user) {
return redirect(302, '/demo/lucia');
}
return {};
};
export const actions${ts(": Actions")} = {
login: async (event) => {
const formData = await event.request.formData();
const username = formData.get('username');
const password = formData.get('password');
if (!validateUsername(username)) {
return fail(400, { message: 'Invalid username (min 3, max 31 characters, alphanumeric only)' });
}
if (!validatePassword(password)) {
return fail(400, { message: 'Invalid password (min 6, max 255 characters)' });
}
const results = await db
.select()
.from(table.user)
.where(eq(table.user.username, username));
const existingUser = results.at(0);
if (!existingUser) {
return fail(400, { message: 'Incorrect username or password' });
}
const validPassword = await verify(existingUser.passwordHash, password, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
if (!validPassword) {
return fail(400, { message: 'Incorrect username or password' });
}
const sessionToken = auth.generateSessionToken();
const session = await auth.createSession(sessionToken, existingUser.id);
auth.setSessionTokenCookie(event, sessionToken, session.expiresAt);
return redirect(302, '/demo/lucia');
},
register: async (event) => {
const formData = await event.request.formData();
const username = formData.get('username');
const password = formData.get('password');
if (!validateUsername(username)) {
return fail(400, { message: 'Invalid username' });
}
if (!validatePassword(password)) {
return fail(400, { message: 'Invalid password' });
}
const userId = generateUserId();
const passwordHash = await hash(password, {
// recommended minimum parameters
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
try {
await db.insert(table.user).values({ id: userId, username, passwordHash });
const sessionToken = auth.generateSessionToken();
const session = await auth.createSession(sessionToken, userId);
auth.setSessionTokenCookie(event, sessionToken, session.expiresAt);
} catch {
return fail(500, { message: 'An error has occurred' });
}
return redirect(302, '/demo/lucia');
},
};
function generateUserId() {
// ID with 120 bits of entropy, or about the same as UUID v4.
const bytes = crypto.getRandomValues(new Uint8Array(15));
const id = encodeBase32LowerCase(bytes);
return id;
}
function validateUsername(username${ts(": unknown")})${ts(": username is string")} {
return (
typeof username === 'string' &&
username.length >= 3 &&
username.length <= 31 &&
/^[a-z0-9_-]+$/.test(username)
);
}
function validatePassword(password${ts(": unknown")})${ts(": password is string")} {
return (
typeof password === 'string' &&
password.length >= 6 &&
password.length <= 255
);
}
`;
});
sv.file(`${kit.routesDirectory}/demo/lucia/login/+page.svelte`, (content) => {
if (content) {
const filePath = `${kit.routesDirectory}/demo/lucia/login/+page.svelte`;
T$2.warn(`Existing ${colors.yellow(filePath)} file. Could not update.`);
return content;
}
const tailwind = dependencyVersion("@tailwindcss/vite") !== undefined;
const twInputClasses = "class=\"mt-1 px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"";
const twBtnClasses = "class=\"bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition\"";
const svelte5 = !!dependencyVersion("svelte")?.startsWith("5");
const [ts, s5] = utils_exports.createPrinter(typescript, svelte5);
return dedent_default`
<script ${ts("lang='ts'")}>
import { enhance } from '$app/forms';
${ts("import type { ActionData } from './$types';\n")}
${s5(`let { form }${ts(": { form: ActionData }")} = $props();`, `export let form${ts(": ActionData")};`)}
</script>
<h1>Login/Register</h1>
<form method="post" action="?/login" use:enhance>
<label>
Username
<input
name="username"
${tailwind ? twInputClasses : ""}
/>
</label>
<label>
Password
<input
type="password"
name="password"
${tailwind ? twInputClasses : ""}
/>
</label>
<button ${tailwind ? twBtnClasses : ""}
>Login</button>
<button
formaction="?/register"
${tailwind ? twBtnClasses : ""}
>Register</button>
</form>
<p style='color: red'>{form?.message ?? ''}</p>
`;
});
sv.file(`${kit.routesDirectory}/demo/lucia/+page.server.${ext}`, (content) => {
if (content) {
const filePath = `${kit.routesDirectory}/demo/lucia/+page.server.${typescript ? "ts" : "js"}`;
T$2.warn(`Existing ${colors.yellow(filePath)} file. Could not update.`);
return content;
}
const [ts] = utils_exports.createPrinter(typescript);
return dedent_default`
import * as auth from '$lib/server/auth';
import { fail, redirect } from '@sveltejs/kit';
import { getRequestEvent } from '$app/server';
${ts("import type { Actions, PageServerLoad } from './$types';\n")}
export const load${ts(": PageServerLoad")} = async () => {
const user = requireLogin()
return { user };
};
export const actions${ts(": Actions")} = {
logout: async (event) => {
if (!event.locals.session) {
return fail(401);
}
await auth.invalidateSession(event.locals.session.id);
auth.deleteSessionTokenCookie(event);
return redirect(302, '/demo/lucia/login');
},
};
function requireLogin() {
const { locals } = getRequestEvent();
if (!locals.user) {
return redirect(302, "/demo/lucia/login");
}
return locals.user;
}
`;
});
sv.file(`${kit.routesDirectory}/demo/lucia/+page.svelte`, (content) => {
if (content) {
const filePath = `${kit.routesDirectory}/demo/lucia/+page.svelte`;
T$2.warn(`Existing ${colors.yellow(filePath)} file. Could not update.`);
return content;
}
const svelte5 = !!dependencyVersion("svelte")?.startsWith("5");
const [ts, s5] = utils_exports.createPrinter(typescript, svelte5);
return dedent_default`
<script ${ts("lang='ts'")}>
import { enhance } from '$app/forms';
${ts("import type { PageServerData } from './$types';\n")}
${s5(`let { data }${ts(": { data: PageServerData }")} = $props();`, `export let data${ts(": PageServerData")};`)}
</script>
<h1>Hi, {data.user.username}!</h1>
<p>Your user ID is {data.user.id}.</p>
<form method='post' action='?/logout' use:enhance>
<button>Sign out</button>
</form>
`;
});
}
},
nextSteps: ({ highlighter, options: options$6, packageManager }) => {
const { command, args } = resolveCommand(packageManager, "run", ["db:push"]);
const steps = [`Run ${highlighter.command(`${command} ${args.join(" ")}`)} to update your database schema`];
if (options$6.demo) steps.push(`Visit ${highlighter.route("/demo/lucia")} route to view the demo`);
return steps;
}
});
function createLuciaType(name) {
return {
type: "TSPropertySignature",
key: {
type: "Identifier",
name
},
computed: false,
typeAnnotation: {
type: "TSTypeAnnotation",
typeAnnotation: {
type: "TSIndexedAccessType",
objectType: {
type: "TSImportType",
argument: {
type: "Literal",
value: "$lib/server/auth"
},
qualifier: {
type: "Identifier",
name: "SessionValidationResult"
}
},
indexType: {
type: "TSLiteralType",
literal: {
type: "Literal",
value: name
}
}
}
}
};
}
function getAuthHandleContent() {
return `
async ({ event, resolve }) => {
const sessionToken = event.cookies.get(auth.sessionCookieName);
if (!sessionToken) {
event.locals.user = null;
event.locals.session = null;
return resolve(event);
}
const { session, user } = await auth.validateSessionToken(sessionToken);
if (session) {
auth.setSessionTokenCookie(event, sessionToken, session.expiresAt);
} else {
auth.deleteSessionTokenCookie(event);
}
event.locals.user = user;
event.locals.session = session;
return resolve(event);
};`;
}
function getCallExpression(ast) {
let callExpression;
walk_exports.walk(ast, null, { CallExpression(node) {
callExpression ??= node;
} });
return callExpression;
}
//#endregion
//#region packages/addons/mdsvex/index.ts
var mdsvex_default = defineAddon({
id: "mdsvex",
shortDescription: "svelte + markdown",
homepage: "https://mdsvex.pngwn.io",
options: {},
run: ({ sv }) => {
sv.devDependency("mdsvex", "^0.12.3");
sv.file("svelte.config.js", (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamed(ast, {
from: "mdsvex",
imports: ["mdsvex"]
});
const { value: exportDefault } = exports_exports.createDefault(ast, { fallback: object_exports.create({}) });
let preprocessorArray = object_exports.property(exportDefault, {
name: "preprocess",
fallback: array_exports.create()
});
const isArray = preprocessorArray.type === "ArrayExpression";
if (!isArray) {
const previousElement = preprocessorArray;
preprocessorArray = array_exports.create();
array_exports.append(preprocessorArray, previousElement);
object_exports.overrideProperty(exportDefault, {
name: "preprocess",
value: preprocessorArray
});
}
const mdsvexCall = function_exports.createCall({
name: "mdsvex",
args: []
});
array_exports.append(preprocessorArray, mdsvexCall);
const extensionsArray = object_exports.property(exportDefault, {
name: "extensions",
fallback: array_exports.create()
});
array_exports.append(extensionsArray, ".svelte");
array_exports.append(extensionsArray, ".svx");
return generateCode();
});
}
});
//#endregion
//#region packages/core/dist/html.js
function createElement(tagName, attributes = {}) {
const element = new Element(tagName, {}, undefined, Tag);
element.attribs = attributes;
return element;
}
function appendElement(childNodes, elementToAppend) {
childNodes.push(elementToAppend);
}
function addFromRawHtml(childNodes, html) {
const document = parseHtml(html);
for (const childNode of document.childNodes) childNodes.push(childNode);
}
function addSlot(jsAst, options$6) {
const slotSyntax = options$6.svelteVersion && (options$6.svelteVersion.startsWith("4") || options$6.svelteVersion.startsWith("3"));
if (slotSyntax) {
const slot = createElement("slot");
appendElement(options$6.htmlAst.childNodes, slot);
return;
}
appendFromString(jsAst, { code: "let { children } = $props();" });
addFromRawHtml(options$6.htmlAst.childNodes, "{@render children()}");
}
//#endregion
//#region packages/addons/paraglide/index.ts
const DEFAULT_INLANG_PROJECT = {
$schema: "https://inlang.com/schema/project-settings",
modules: ["https://cdn.jsdelivr.net/npm/@inlang/plugin-message-format@4/dist/index.js", "https://cdn.jsdelivr.net/npm/@inlang/plugin-m-function-matcher@2/dist/index.js"],
"plugin.inlang.messageFormat": { pathPattern: "./messages/{locale}.json" }
};
const options$3 = defineAddonOptions({
languageTags: {
question: `Which languages would you like to support? ${colors.gray("(e.g. en,de-ch)")}`,
type: "string",
default: "en, es",
validate(input) {
if (!input) return;
const { invalidLanguageTags, validLanguageTags } = parseLanguageTagInput(input);
if (invalidLanguageTags.length > 0) if (invalidLanguageTags.length === 1) return `The input "${invalidLanguageTags[0]}" is not a valid IETF BCP 47 language tag`;
else {
const listFormat = new Intl.ListFormat("en", {
style: "long",
type: "conjunction"
});
return `The inputs ${listFormat.format(invalidLanguageTags.map((x$2) => `"${x$2}"`))} are not valid BCP47 language tags`;
}
if (validLanguageTags.length === 0) return "Please enter at least one valid BCP47 language tag. Eg: en";
return undefined;
}
},
demo: {
type: "boolean",
default: true,
question: "Do you want to include a demo?"
}
});
var paraglide_default = defineAddon({
id: "paraglide",
shortDescription: "i18n",
homepage: "https://inlang.com/m/gerre34r/library-inlang-paraglideJs",
options: options$3,
setup: ({ kit, unsupported }) => {
if (!kit) unsupported("Requires SvelteKit");
},
run: ({ sv, options: options$6, viteConfigFile, typescript, kit }) => {
const ext = typescript ? "ts" : "js";
if (!kit) throw new Error("SvelteKit is required");
const paraglideOutDir = "src/lib/paraglide";
sv.dependency("@inlang/paraglide-js", "^2.0.0");
sv.file("project.inlang/settings.json", (content) => {
if (content) return content;
const { data, generateCode } = parseJson$1(content);
for (const key in DEFAULT_INLANG_PROJECT) data[key] = DEFAULT_INLANG_PROJECT[key];
const { validLanguageTags: validLanguageTags$1 } = parseLanguageTagInput(options$6.languageTags);
const baseLocale = validLanguageTags$1[0];
data.baseLocale = baseLocale;
data.locales = validLanguageTags$1;
return generateCode();
});
sv.file(viteConfigFile, (content) => {
const { ast, generateCode } = parseScript$1(content);
const vitePluginName = "paraglideVitePlugin";
imports_exports.addNamed(ast, {
imports: [vitePluginName],
from: "@inlang/paraglide-js"
});
vite_exports.addPlugin(ast, { code: `${vitePluginName}({
project: './project.inlang',
outdir: './${paraglideOutDir}'
})` });
return generateCode();
});
sv.file(`src/hooks.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamed(ast, {
from: "$lib/paraglide/runtime",
imports: ["deLocalizeUrl"]
});
const expression = common_exports.parseExpression("(request) => deLocalizeUrl(request.url).pathname");
const rerouteIdentifier = variables_exports.declaration(ast, {
kind: "const",
name: "reroute",
value: expression
});
const existingExport = exports_exports.createNamed(ast, {
name: "reroute",
fallback: rerouteIdentifier
});
if (existingExport.declaration !== rerouteIdentifier) T$2.warn("Adding the reroute hook automatically failed. Add it manually");
return generateCode();
});
sv.file(`src/hooks.server.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
imports_exports.addNamed(ast, {
from: "$lib/paraglide/server",
imports: ["paraglideMiddleware"]
});
const hookHandleContent = `({ event, resolve }) => paraglideMiddleware(event.request, ({ request, locale }) => {
event.request = request;
return resolve(event, {
transformPageChunk: ({ html }) => html.replace('%paraglide.lang%', locale)
});
});`;
kit_exports.addHooksHandle(ast, {
typescript,
newHandleName: "handleParaglide",
handleContent: hookHandleContent
});
return generateCode();
});
sv.file("src/app.html", (content) => {
const { ast, generateCode } = parseHtml$1(content);
const htmlNode = ast.children.find((child) => child.type === esm_exports.Tag && child.name === "html");
if (!htmlNode) {
T$2.warn("Could not find <html> node in app.html. You'll need to add the language placeholder manually");
return generateCode();
}
htmlNode.attribs = {
...htmlNode.attribs,
lang: "%paraglide.lang%"
};
return generateCode();
});
sv.file(".gitignore", (content) => {
if (!content) return content;
if (!content.includes(`\n${paraglideOutDir}`)) content = content.trimEnd() + `\n\n# Paraglide\n${paraglideOutDir}`;
return content;
});
if (options$6.demo) {
sv.file(`${kit.routesDirectory}/demo/+page.svelte`, (content) => {
return addToDemoPage(content, "paraglide");
});
sv.file(`${kit.routesDirectory}/demo/paraglide/+page.svelte`, (content) => {
const { script, template, generateCode } = parseSvelte(content, { typescript });
imports_exports.addNamed(script.ast, {
from: "$lib/paraglide/messages.js",
imports: ["m"]
});
imports_exports.addNamed(script.ast, {
from: "$app/navigation",
imports: ["goto"]
});
imports_exports.addNamed(script.ast, {
from: "$app/state",
imports: ["page"]
});
imports_exports.addNamed(script.ast, {
from: "$lib/paraglide/runtime",
imports: ["setLocale"]
});
const scriptCode = new MagicString(script.generateCode());
const templateCode = new MagicString(template.source);
templateCode.append("\n\n<h1>{m.hello_world({ name: 'SvelteKit User' })}</h1>\n");
const { validLanguageTags: validLanguageTags$1 } = parseLanguageTagInput(options$6.languageTags);
const links = validLanguageTags$1.map((x$2) => `${templateCode.getIndentString()}<button onclick={() => setLocale('${x$2}')}>${x$2}</button>`).join("\n");
templateCode.append(`<div>\n${links}\n</div>`);
templateCode.append("<p>\nIf you use VSCode, install the <a href=\"https://marketplace.visualstudio.com/items?itemName=inlang.vs-code-extension\" target=\"_blank\">Sherlock i18n extension</a> for a better i18n experience.\n</p>");
return generateCode({
script: scriptCode.toString(),
template: templateCode.toString()
});
});
}
const { validLanguageTags } = parseLanguageTagInput(options$6.languageTags);
for (const languageTag of validLanguageTags) sv.file(`messages/${languageTag}.json`, (content) => {
const { data, generateCode } = parseJson$1(content);
data["$schema"] = "https://inlang.com/schema/inlang-message-format";
data.hello_world = `Hello, {name} from ${languageTag}!`;
return generateCode();
});
},
nextSteps: ({ highlighter }) => {
const steps = [`Edit your messages in ${highlighter.path("messages/en.json")}`];
if (options$3.demo) steps.push(`Visit ${highlighter.route("/demo/paraglide")} route to view the demo`);
return steps;
}
});
const isValidLanguageTag = (languageTag) => RegExp("^((?<grandfathered>(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))|((?<language>([A-Za-z]{2,3}(-(?<extlang>[A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?))(-(?<script>[A-Za-z]{4}))?(-(?<region>[A-Za-z]{2}|[0-9]{3}))?(-(?<variant>[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*))$").test(languageTag);
function parseLanguageTagInput(input) {
const probablyLanguageTags = input.replace(/[,:\s]/g, " ").split(" ").filter(Boolean).map((tag) => tag.toLowerCase());
const validLanguageTags = [];
const invalidLanguageTags = [];
for (const tag of probablyLanguageTags) if (isValidLanguageTag(tag)) validLanguageTags.push(tag);
else invalidLanguageTags.push(tag);
return {
validLanguageTags,
invalidLanguageTags
};
}
//#endregion
//#region packages/addons/playwright/index.ts
var playwright_default = defineAddon({
id: "playwright",
shortDescription: "browser testing",
homepage: "https://playwright.dev",
options: {},
run: ({ sv, typescript }) => {
const ext = typescript ? "ts" : "js";
sv.devDependency("@playwright/test", "^1.49.1");
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
data.scripts ??= {};
const scripts = data.scripts;
const TEST_CMD = "playwright test";
const RUN_TEST = "npm run test:e2e";
scripts["test:e2e"] ??= TEST_CMD;
scripts["test"] ??= RUN_TEST;
if (!scripts["test"].includes(RUN_TEST)) scripts["test"] += ` && ${RUN_TEST}`;
return generateCode();
});
sv.file(".gitignore", (content) => {
if (!content) return content;
if (content.includes("test-results")) return content;
return "test-results\n" + content.trim();
});
sv.file(`e2e/demo.test.${ext}`, (content) => {
if (content) return content;
return dedent_default`
import { expect, test } from '@playwright/test';
test('home page has expected h1', async ({ page }) => {
await page.goto('/');
await expect(page.locator('h1')).toBeVisible();
});
`;
});
sv.file(`playwright.config.${ext}`, (content) => {
const { ast, generateCode } = parseScript$1(content);
const defineConfig = common_exports.parseExpression("defineConfig({})");
const { value: defaultExport } = exports_exports.createDefault(ast, { fallback: defineConfig });
const config = {
webServer: object_exports.create({
command: "npm run build && npm run preview",
port: 4173
}),
testDir: common_exports.createLiteral("e2e")
};
if (defaultExport.type === "CallExpression" && defaultExport.arguments[0]?.type === "ObjectExpression") {
imports_exports.addNamed(ast, {
from: "@playwright/test",
imports: ["defineConfig"]
});
object_exports.addProperties(defaultExport.arguments[0], { properties: config });
} else if (defaultExport.type === "ObjectExpression") object_exports.addProperties(defaultExport, { properties: config });
else T$2.warn("Unexpected playwright config for playwright add-on. Could not update.");
return generateCode();
});
}
});
//#endregion
//#region packages/addons/prettier/index.ts
var prettier_default = defineAddon({
id: "prettier",
shortDescription: "formatter",
homepage: "https://prettier.io",
options: {},
run: ({ sv, dependencyVersion }) => {
sv.devDependency("prettier", "^3.4.2");
sv.devDependency("prettier-plugin-svelte", "^3.3.3");
sv.file(".prettierignore", (content) => {
if (content) return content;
return dedent_default`
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
bun.lock
bun.lockb
# Miscellaneous
/static/
`;
});
sv.file(".prettierrc", (content) => {
let data, generateCode;
try {
({data, generateCode} = parseJson$1(content));
} catch {
T$2.warn(`A ${colors.yellow(".prettierrc")} config already exists and cannot be parsed as JSON. Skipping initialization.`);
return content;
}
if (Object.keys(data).length === 0) {
data.useTabs = true;
data.singleQuote = true;
data.trailingComma = "none";
data.printWidth = 100;
}
data.plugins ??= [];
data.overrides ??= [];
const plugins$1 = data.plugins;
if (!plugins$1.includes("prettier-plugin-svelte")) data.plugins.unshift("prettier-plugin-svelte");
const overrides = data.overrides;
const override = overrides.find((o$1) => o$1?.options?.parser === "svelte");
if (!override) overrides.push({
files: "*.svelte",
options: { parser: "svelte" }
});
return generateCode();
});
const eslintVersion = dependencyVersion("eslint");
const eslintInstalled = hasEslint(eslintVersion);
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
data.scripts ??= {};
const scripts = data.scripts;
const CHECK_CMD = "prettier --check .";
scripts["format"] ??= "prettier --write .";
if (eslintInstalled) {
scripts["lint"] ??= `${CHECK_CMD} && eslint .`;
if (!scripts["lint"].includes(CHECK_CMD)) scripts["lint"] += ` && ${CHECK_CMD}`;
} else scripts["lint"] ??= CHECK_CMD;
return generateCode();
});
if (eslintVersion?.startsWith(SUPPORTED_ESLINT_VERSION) === false) T$2.warn(`An older major version of ${colors.yellow("eslint")} was detected. Skipping ${colors.yellow("eslint-config-prettier")} installation.`);
if (eslintInstalled) {
sv.devDependency("eslint-config-prettier", "^10.0.1");
sv.file("eslint.config.js", addEslintConfigPrettier);
}
}
});
const SUPPORTED_ESLINT_VERSION = "9";
function hasEslint(version) {
return !!version && version.startsWith(SUPPORTED_ESLINT_VERSION);
}
//#endregion
//#region packages/addons/storybook/index.ts
var storybook_default = defineAddon({
id: "storybook",
shortDescription: "frontend workshop",
homepage: "https://storybook.js.org",
options: {},
setup: ({ runsAfter }) => {
runsAfter("vitest");
runsAfter("eslint");
},
run: async ({ sv }) => {
const args = [
"create-storybook@latest",
"--skip-install",
"--no-dev"
];
if (process$1.env.NODE_ENV?.toLowerCase() === "test") args.push("--yes");
await sv.execute(args, "inherit");
sv.devDependency(`@types/node`, getNodeTypesVersion());
}
});
//#endregion
//#region packages/addons/sveltekit-adapter/index.ts
const adapters = [
{
id: "auto",
package: "@sveltejs/adapter-auto",
version: "^6.0.0"
},
{
id: "node",
package: "@sveltejs/adapter-node",
version: "^5.2.12"
},
{
id: "static",
package: "@sveltejs/adapter-static",
version: "^3.0.8"
},
{
id: "vercel",
package: "@sveltejs/adapter-vercel",
version: "^5.6.3"
},
{
id: "cloudflare",
package: "@sveltejs/adapter-cloudflare",
version: "^7.0.0"
},
{
id: "netlify",
package: "@sveltejs/adapter-netlify",
version: "^5.0.0"
}
];
const options$2 = defineAddonOptions({ adapter: {
type: "select",
question: "Which SvelteKit adapter would you like to use?",
options: adapters.map((p$1) => ({
value: p$1.id,
label: p$1.id,
hint: p$1.package
})),
default: "auto"
} });
var sveltekit_adapter_default = defineAddon({
id: "sveltekit-adapter",
alias: "adapter",
shortDescription: "deployment",
homepage: "https://svelte.dev/docs/kit/adapters",
options: options$2,
setup: ({ kit, unsupported }) => {
if (!kit) unsupported("Requires SvelteKit");
},
run: ({ sv, options: options$6 }) => {
const adapter = adapters.find((a) => a.id === options$6.adapter);
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
const devDeps = data["devDependencies"];
for (const pkg of Object.keys(devDeps)) if (pkg.startsWith("@sveltejs/adapter-")) delete devDeps[pkg];
return generateCode();
});
sv.devDependency(adapter.package, adapter.version);
sv.file("svelte.config.js", (content) => {
const { ast, generateCode } = parseScript$1(content);
const importDecls = ast.body.filter((n$1) => n$1.type === "ImportDeclaration");
const adapterImportDecl = importDecls.find((importDecl) => typeof importDecl.source.value === "string" && importDecl.source.value.startsWith("@sveltejs/adapter-") && importDecl.importKind === "value");
let adapterName = "adapter";
if (adapterImportDecl) {
adapterImportDecl.source.value = adapter.package;
adapterImportDecl.source.raw = undefined;
adapterName = adapterImportDecl.specifiers?.find((s) => s.type === "ImportDefaultSpecifier")?.local?.name;
} else imports_exports.addDefault(ast, {
from: adapter.package,
as: adapterName
});
const { value: config } = exports_exports.createDefault(ast, { fallback: object_exports.create({}) });
const kitConfig = config.properties.find((p$1) => p$1.type === "Property" && p$1.key.type === "Identifier" && p$1.key.name === "kit");
if (kitConfig && kitConfig.value.type === "ObjectExpression") {
const adapterProp = kitConfig.value.properties.find((p$1) => p$1.type === "Property" && p$1.key.type === "Identifier" && p$1.key.name === "adapter");
if (adapterProp) adapterProp.leadingComments = [];
object_exports.overrideProperties(kitConfig.value, { properties: { adapter: function_exports.createCall({
name: adapterName,
args: [],
useIdentifiers: true
}) } });
} else object_exports.addProperties(config, { properties: { kit: object_exports.create({ adapter: function_exports.createCall({
name: adapterName,
args: [],
useIdentifiers: true
}) }) } });
return generateCode();
});
}
});
//#endregion
//#region packages/addons/tailwindcss/index.ts
const plugins = [{
id: "typography",
package: "@tailwindcss/typography",
version: "^0.5.15",
identifier: "typography"
}, {
id: "forms",
package: "@tailwindcss/forms",
version: "^0.5.9",
identifier: "forms"
}];
const options$1 = defineAddonOptions({ plugins: {
type: "multiselect",
question: "Which plugins would you like to add?",
options: plugins.map((p$1) => ({
value: p$1.id,
label: p$1.id,
hint: p$1.package
})),
default: [],
required: false
} });
var tailwindcss_default = defineAddon({
id: "tailwindcss",
alias: "tailwind",
shortDescription: "css framework",
homepage: "https://tailwindcss.com",
options: options$1,
run: ({ sv, options: options$6, viteConfigFile, typescript, kit, dependencyVersion }) => {
const prettierInstalled = Boolean(dependencyVersion("prettier"));
sv.devDependency("tailwindcss", "^4.0.0");
sv.devDependency("@tailwindcss/vite", "^4.0.0");
if (prettierInstalled) sv.devDependency("prettier-plugin-tailwindcss", "^0.6.11");
for (const plugin of plugins) {
if (!options$6.plugins.includes(plugin.id)) continue;
sv.devDependency(plugin.package, plugin.version);
}
sv.file(viteConfigFile, (content) => {
const { ast, generateCode } = parseScript$1(content);
const vitePluginName = "tailwindcss";
imports_exports.addDefault(ast, {
as: vitePluginName,
from: "@tailwindcss/vite"
});
vite_exports.addPlugin(ast, {
code: `${vitePluginName}()`,
mode: "prepend"
});
return generateCode();
});
sv.file("src/app.css", (content) => {
let atRules = parseCss$1(content).ast.nodes.filter((node) => node.type === "atrule");
const findAtRule = (name, params) => atRules.find((rule) => rule.name === name && rule.params.replace(/['"]/g, "") === params);
let code = content;
const importsTailwind = findAtRule("import", "tailwindcss");
if (!importsTailwind) {
code = "@import 'tailwindcss';\n" + code;
atRules = parseCss$1(code).ast.nodes.filter((node) => node.type === "atrule");
}
const lastAtRule = atRules.findLast((rule) => ["plugin", "import"].includes(rule.name));
const pluginPos = lastAtRule.source.end.offset;
for (const plugin of plugins) {
if (!options$6.plugins.includes(plugin.id)) continue;
const pluginRule = findAtRule("plugin", plugin.package);
if (!pluginRule) {
const pluginImport = `\n@plugin '${plugin.package}';`;
code = code.substring(0, pluginPos) + pluginImport + code.substring(pluginPos);
}
}
return code;
});
if (!kit) sv.file("src/App.svelte", (content) => {
const { script, generateCode } = parseSvelte(content, { typescript });
imports_exports.addEmpty(script.ast, { from: "./app.css" });
return generateCode({ script: script.generateCode() });
});
else sv.file(`${kit?.routesDirectory}/+layout.svelte`, (content) => {
const { script, template, generateCode } = parseSvelte(content, { typescript });
imports_exports.addEmpty(script.ast, { from: "../app.css" });
if (content.length === 0) {
const svelteVersion = dependencyVersion("svelte");
if (!svelteVersion) throw new Error("Failed to determine svelte version");
addSlot(script.ast, {
htmlAst: template.ast,
svelteVersion
});
}
return generateCode({
script: script.generateCode(),
template: content.length === 0 ? template.generateCode() : undefined
});
});
if (dependencyVersion("prettier")) sv.file(".prettierrc", (content) => {
const { data, generateCode } = parseJson$1(content);
const PLUGIN_NAME = "prettier-plugin-tailwindcss";
data.plugins ??= [];
const plugins$1 = data.plugins;
if (!plugins$1.includes(PLUGIN_NAME)) plugins$1.push(PLUGIN_NAME);
data.tailwindStylesheet ??= "./src/app.css";
return generateCode();
});
}
});
//#endregion
//#region packages/addons/vitest-addon/index.ts
const options = defineAddonOptions({ usages: {
question: "What do you want to use vitest for?",
type: "multiselect",
default: ["unit", "component"],
options: [{
value: "unit",
label: "unit testing"
}, {
value: "component",
label: "component testing"
}],
required: true
} });
var vitest_addon_default = defineAddon({
id: "vitest",
shortDescription: "unit testing",
homepage: "https://vitest.dev",
options,
run: ({ sv, viteConfigFile, typescript, kit, options: options$6 }) => {
const ext = typescript ? "ts" : "js";
const unitTesting = options$6.usages.includes("unit");
const componentTesting = options$6.usages.includes("component");
sv.devDependency("vitest", "^3.2.3");
if (componentTesting) {
sv.devDependency("@vitest/browser", "^3.2.3");
sv.devDependency("vitest-browser-svelte", "^0.1.0");
sv.devDependency("playwright", "^1.53.0");
}
sv.file("package.json", (content) => {
const { data, generateCode } = parseJson$1(content);
data.scripts ??= {};
const scripts = data.scripts;
const TEST_CMD = "vitest";
const RUN_TEST = "npm run test:unit -- --run";
scripts["test:unit"] ??= TEST_CMD;
scripts["test"] ??= RUN_TEST;
if (!scripts["test"].includes(RUN_TEST)) scripts["test"] += ` && ${RUN_TEST}`;
return generateCode();
});
if (unitTesting) sv.file(`src/demo.spec.${ext}`, (content) => {
if (content) return content;
return dedent_default`
import { describe, it, expect } from 'vitest';
describe('sum test', () => {
it('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
});
`;
});
if (componentTesting) {
const fileName = kit ? `${kit.routesDirectory}/page.svelte.spec.${ext}` : `src/App.svelte.test.${ext}`;
sv.file(fileName, (content) => {
if (content) return content;
return dedent_default`
import { page } from '@vitest/browser/context';
import { describe, expect, it } from 'vitest';
import { render } from 'vitest-browser-svelte';
${kit ? "import Page from './+page.svelte';" : "import App from './App.svelte';"}
describe('${kit ? "/+page.svelte" : "App.svelte"}', () => {
it('should render h1', async () => {
render(${kit ? "Page" : "App"});
const heading = page.getByRole('heading', { level: 1 });
await expect.element(heading).toBeInTheDocument();
});
});
`;
});
sv.file(`vitest-setup-client.${ext}`, (content) => {
if (content) return content;
return dedent_default`
/// <reference types="@vitest/browser/matchers" />
/// <reference types="@vitest/browser/providers/playwright" />
`;
});
}
sv.file(viteConfigFile, (content) => {
const { ast, generateCode } = parseScript$1(content);
const clientObjectExpression = object_exports.create({
extends: `./${viteConfigFile}`,
test: {
name: "client",
environment: "browser",
browser: {
enabled: true,
provider: "playwright",
instances: [{ browser: "chromium" }]
},
include: ["src/**/*.svelte.{test,spec}.{js,ts}"],
exclude: ["src/lib/server/**"],
setupFiles: [`./vitest-setup-client.${ext}`]
}
});
const serverObjectExpression = object_exports.create({
extends: `./${viteConfigFile}`,
test: {
name: "server",
environment: "node",
include: ["src/**/*.{test,spec}.{js,ts}"],
exclude: ["src/**/*.svelte.{test,spec}.{js,ts}"]
}
});
const defineConfigFallback = function_exports.createCall({
name: "defineConfig",
args: []
});
const { value: defineWorkspaceCall } = exports_exports.createDefault(ast, { fallback: defineConfigFallback });
if (defineWorkspaceCall.type !== "CallExpression") T$2.warn("Unexpected vite config. Could not update.");
const vitestConfig = function_exports.getArgument(defineWorkspaceCall, {
index: 0,
fallback: object_exports.create({})
});
const testObject = object_exports.property(vitestConfig, {
name: "test",
fallback: object_exports.create({ expect: { requireAssertions: true } })
});
const workspaceArray = object_exports.property(testObject, {
name: "projects",
fallback: array_exports.create()
});
if (componentTesting) array_exports.append(workspaceArray, clientObjectExpression);
if (unitTesting) array_exports.append(workspaceArray, serverObjectExpression);
return generateCode();
});
}
});
//#endregion
//#region packages/addons/_config/official.ts
const officialAddons = [
prettier_default,
eslint_default,
vitest_addon_default,
playwright_default,
tailwindcss_default,
sveltekit_adapter_default,
devtools_json_default,
drizzle_default,
lucia_default,
mdsvex_default,
paraglide_default,
storybook_default
];
function getAddonDetails(id) {
const details = officialAddons.find((a) => a.id === id);
if (!details) throw new Error(`Invalid add-on: ${id}`);
return details;
}
//#endregion
//#region packages/addons/_config/community.ts
const communityAddonIds = ["unocss", "unplugin-icons"];
async function getCommunityAddon(name) {
const { default: details } = await import(`../../../community-addons/${name}.ts`);
return details;
}
//#endregion
export { applyAddons, communityAddonIds, createWorkspace, formatFiles, getAddonDetails, getCommunityAddon, getHighlighter, installAddon, isVersionUnsupportedBelow, officialAddons, setupAddons };