free-pi-cli 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/main.ts
4
- import { realpathSync } from "node:fs";
5
- import { dirname as dirname5, join as join5 } from "node:path";
4
+ import { spawn as spawn2 } from "node:child_process";
5
+ import { realpathSync, writeFileSync as writeFileSync2 } from "node:fs";
6
+ import { dirname as dirname5, join as join7 } from "node:path";
6
7
 
7
8
  // src/browser.ts
8
9
  import { spawn } from "node:child_process";
@@ -45,7 +46,7 @@ function openBrowser(url, platform = process.platform, spawnImpl = spawn) {
45
46
  // package.json
46
47
  var package_default = {
47
48
  name: "free-pi-cli",
48
- version: "0.4.6",
49
+ version: "0.4.8",
49
50
  description: "Free, ad-supported distribution of the pi coding agent. Inference paid for by ads.",
50
51
  license: "MIT",
51
52
  type: "module",
@@ -4969,6 +4970,7 @@ var ConfigSchema = object({
4969
4970
  abuseRestrictedCapUsd: number2().default(0.5),
4970
4971
  abuseRestrictedHourlyCap: number2().int().default(5),
4971
4972
  abuseNormalHourlyCap: number2().int().default(30),
4973
+ abuseSignedInNormalHourlyCap: number2().int().default(0),
4972
4974
  abuseFlipAlertThreshold: number2().int().default(10),
4973
4975
  abuseAdBypassMinRequests: number2().int().default(20),
4974
4976
  abuseAdBypassRatio: number2().int().default(10),
@@ -5041,6 +5043,7 @@ function loadConfig(env = process.env) {
5041
5043
  abuseRestrictedCapUsd: envNumber(env.ABUSE_RESTRICTED_CAP_USD),
5042
5044
  abuseRestrictedHourlyCap: envNumber(env.ABUSE_RESTRICTED_HOURLY_CAP),
5043
5045
  abuseNormalHourlyCap: envNumber(env.ABUSE_NORMAL_HOURLY_CAP),
5046
+ abuseSignedInNormalHourlyCap: envNumber(env.ABUSE_SIGNED_IN_NORMAL_HOURLY_CAP),
5044
5047
  abuseFlipAlertThreshold: envNumber(env.ABUSE_FLIP_ALERT_THRESHOLD),
5045
5048
  abuseAdBypassMinRequests: envNumber(env.ABUSE_AD_BYPASS_MIN_REQUESTS),
5046
5049
  abuseAdBypassRatio: envNumber(env.ABUSE_AD_BYPASS_RATIO),
@@ -5085,6 +5088,42 @@ function formatCreditsLeftLine(remaining, allowance, refillAt) {
5085
5088
  return `${left} / ${total} credits left today · refills ${formatRefillEt(refillAt)}`;
5086
5089
  }
5087
5090
  var SLOW_LANE_METER_LINE = "Slow lane: cheapest model until refill";
5091
+ var LIMIT_NOTICE_LABELS = {
5092
+ hourly_ceiling: "hourly limit",
5093
+ daily_cap: "daily limit",
5094
+ rolling_cap: "rolling limit",
5095
+ global_cap: "service daily limit",
5096
+ queue_wait: "queue wait",
5097
+ concurrent: "one request at a time",
5098
+ concurrent_session: "another session is active"
5099
+ };
5100
+ var EXTRA_CREDITS_URL = "freepi.ai/extra-credits";
5101
+ var LIMIT_NOTICE_LOCAL_TIME_AFTER_SECONDS = 90 * 60;
5102
+ function formatLimitNotice(fields, opts = {}) {
5103
+ const slow = fields.lane === "slow" && fields.limit === "hourly_ceiling" && fields.hourly_ceiling != null;
5104
+ const label = slow ? `You've used today's free allowance, so you're on the slow lane (${fields.hourly_ceiling.toLocaleString("en-US")} requests an hour).` : LIMIT_NOTICE_LABELS[fields.limit] ?? fields.limit.replace(/_/g, " ");
5105
+ const parts = [label];
5106
+ const retry = fields.retry_after_seconds;
5107
+ if (retry != null && retry > 0) {
5108
+ const useClock = Boolean(opts.localTime) && Boolean(fields.clears_at) && retry >= LIMIT_NOTICE_LOCAL_TIME_AFTER_SECONDS;
5109
+ if (useClock) {
5110
+ const formatted = new Intl.DateTimeFormat("en-US", {
5111
+ timeZone: opts.timeZone,
5112
+ hour: "numeric",
5113
+ minute: "2-digit"
5114
+ }).format(new Date(fields.clears_at));
5115
+ parts.push(`back at ${formatted}`);
5116
+ } else {
5117
+ parts.push(`back in ${Math.max(1, Math.ceil(retry / 60))} min`);
5118
+ }
5119
+ }
5120
+ if (slow) {
5121
+ const wait = parts.length > 1 ? ` ${parts[1][0].toUpperCase()}${parts[1].slice(1)} — or get` : " Get";
5122
+ return `${label}${wait} credits at ${EXTRA_CREDITS_URL} to keep going at full speed.`;
5123
+ }
5124
+ parts.push(`${fields.remaining_credits_today.toLocaleString("en-US")} credits left today`);
5125
+ return parts.join(", ");
5126
+ }
5088
5127
  // src/gravity-pixel.ts
5089
5128
  var GRAVITY_PIXEL_ID = "6cd74804-0541-4d9b-899d-d7fceb465b6f";
5090
5129
  function userIdFromJwt(jwt) {
@@ -5178,66 +5217,2645 @@ async function authedFetch(deps, path, init) {
5178
5217
  ...deps.sessionId && (path.startsWith("/ads/next") || path === "/ads/impression") ? { "x-session-id": deps.sessionId } : {},
5179
5218
  ...path.startsWith("/ads/next") ? gravityHeader(deps) : {}
5180
5219
  }
5181
- });
5220
+ });
5221
+ }
5222
+ function gravityHeader(deps) {
5223
+ try {
5224
+ const ctx = deps.getGravityContext?.();
5225
+ return ctx ? { [GRAVITY_CONTEXT_HEADER]: ctx } : {};
5226
+ } catch {
5227
+ return {};
5228
+ }
5229
+ }
5230
+ var IMP_TIMEOUT_MS = 3000;
5231
+ function isGravityImpUrl(raw) {
5232
+ if (!raw)
5233
+ return false;
5234
+ try {
5235
+ const u = new URL(raw);
5236
+ return u.protocol === "https:" && /(^|\.)trygravity\.(ai|com)$/.test(u.hostname);
5237
+ } catch {
5238
+ return false;
5239
+ }
5240
+ }
5241
+ function fireGravityImpression(deps, ad) {
5242
+ if (ad.source !== "gravity" || !isGravityImpUrl(ad.imp_url))
5243
+ return false;
5244
+ try {
5245
+ Promise.resolve((deps.fetchImpl ?? fetch)(ad.imp_url, { method: "GET", signal: AbortSignal.timeout(IMP_TIMEOUT_MS) })).catch(() => {});
5246
+ } catch {}
5247
+ return true;
5248
+ }
5249
+ async function fetchAdNext(deps, slot) {
5250
+ try {
5251
+ const res = await authedFetch(deps, `/ads/next?slot=${slot}`);
5252
+ if (res.status === 204 || !res.ok)
5253
+ return;
5254
+ return await res.json();
5255
+ } catch {
5256
+ return;
5257
+ }
5258
+ }
5259
+ async function postImpression(deps, adId, clickToken, impFired = false) {
5260
+ try {
5261
+ await authedFetch(deps, "/ads/impression", {
5262
+ method: "POST",
5263
+ body: JSON.stringify({ ad_id: adId, click_token: clickToken, ...impFired ? { imp_fired: true } : {} })
5264
+ });
5265
+ } catch {}
5266
+ }
5267
+ async function fetchMe(deps) {
5268
+ try {
5269
+ const res = await authedFetch(deps, "/me");
5270
+ if (!res.ok)
5271
+ return;
5272
+ return await res.json();
5273
+ } catch {
5274
+ return;
5275
+ }
5276
+ }
5277
+
5278
+ // ../pi-ads/src/style.ts
5279
+ import { createHash as createHash2 } from "node:crypto";
5280
+
5281
+ // ../../node_modules/.bun/marked@18.0.11/node_modules/marked/lib/marked.esm.js
5282
+ function A() {
5283
+ return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
5284
+ }
5285
+ var R = A();
5286
+ function j(l) {
5287
+ R = l;
5288
+ }
5289
+ var z = { exec: () => null };
5290
+ function I(l) {
5291
+ let e = [];
5292
+ return (t) => {
5293
+ let n = Math.max(0, Math.min(3, t - 1)), s = e[n];
5294
+ return s || (s = l(n), e[n] = s), s;
5295
+ };
5296
+ }
5297
+ function k(l, e = "") {
5298
+ let t = typeof l == "string" ? l : l.source, n = { replace: (s, r) => {
5299
+ let i = typeof r == "string" ? r : r.source;
5300
+ return i = i.replace(m.caret, "$1"), t = t.replace(s, i), n;
5301
+ }, getRegex: () => new RegExp(t, e) };
5302
+ return n;
5303
+ }
5304
+ var Oe = ((l = "") => {
5305
+ try {
5306
+ return !!new RegExp("(?<=1)(?<!1)" + l);
5307
+ } catch {
5308
+ return false;
5309
+ }
5310
+ })();
5311
+ var m = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^<a /i, endATag: /^<\/a>/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^</, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (l) => new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: I((l) => new RegExp(`^ {0,${l}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)), hrRegex: I((l) => new RegExp(`^ {0,${l}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)), fencesBeginRegex: I((l) => new RegExp(`^ {0,${l}}(?:\`\`\`|~~~)`)), headingBeginRegex: I((l) => new RegExp(`^ {0,${l}}#`)), htmlBeginRegex: I((l) => new RegExp(`^ {0,${l}}<(?:[a-z].*>|!--)`, "i")), blockquoteBeginRegex: I((l) => new RegExp(`^ {0,${l}}>`)) };
5312
+ var Te = /^(?:[ \t]*(?:\n|$))+/;
5313
+ var we = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/;
5314
+ var ye = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
5315
+ var q = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
5316
+ var Pe = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
5317
+ var U = / {0,3}(?:[*+-]|\d{1,9}[.)])/;
5318
+ var oe = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/;
5319
+ var ae = k(oe).replace(/bull/g, U).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}(?:\s|$)/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex();
5320
+ var Se = k(oe).replace(/bull/g, U).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}(?:\s|$)/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex();
5321
+ var K = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/;
5322
+ var _e = /^[^\n]+/;
5323
+ var W = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/;
5324
+ var $e = k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", W).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
5325
+ var Le = k(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g, U).getRegex();
5326
+ var Q = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
5327
+ var X = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
5328
+ var Ee = k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))", "i").replace("comment", X).replace("tag", Q).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
5329
+ var le = (l) => k(K).replace("hr", q).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", l).replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", Q).getRegex();
5330
+ var ze = le(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/);
5331
+ var Me = le(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/);
5332
+ var Ae = k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", Me).getRegex();
5333
+ var J = { blockquote: Ae, code: we, def: $e, fences: ye, heading: Pe, hr: q, html: Ee, lheading: ae, list: Le, newline: Te, paragraph: ze, table: z, text: _e };
5334
+ var se = k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", q).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}\t)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", Q).getRegex();
5335
+ var Ie = { ...J, lheading: Se, table: se, paragraph: k(K).replace("hr", q).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", se).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", Q).getRegex() };
5336
+ var Ce = { ...J, html: k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", X).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: z, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: k(K).replace("hr", q).replace("heading", ` *#{1,6} *[^
5337
+ ]`).replace("lheading", ae).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() };
5338
+ var Be = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
5339
+ var De = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
5340
+ var ue = /^( {2,}|\\)\n(?!\s*$)/;
5341
+ var qe = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
5342
+ var _ = /[\p{P}\p{S}]/u;
5343
+ var C = /[\s\p{P}\p{S}]/u;
5344
+ var v = /[^\s\p{P}\p{S}]/u;
5345
+ var ve = k(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, C).getRegex();
5346
+ var He = /[\p{Pi}\p{Ps}"']/u;
5347
+ var pe = /(?!~)[\p{P}\p{S}]/u;
5348
+ var Ze = /(?!~)[\s\p{P}\p{S}]/u;
5349
+ var Ge = /(?:[^\s\p{P}\p{S}]|~)/u;
5350
+ var Qe = k(/link|precode-code|html/, "g").replace("link", /\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", Oe ? "(?<!`)()" : "(^^|[^`])").replace("code", /(?<b>`+)[^`]+\k<b>(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex();
5351
+ var ce = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/;
5352
+ var Ne = k(ce, "u").replace(/punct/g, _).getRegex();
5353
+ var je = k(ce, "u").replace(/punct/g, pe).getRegex();
5354
+ var Fe = /^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/;
5355
+ var Ue = k(Fe, "u").replace(/openQuote/g, He).replace(/punct/g, _).getRegex();
5356
+ var he = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)";
5357
+ var Ke = k(he, "gu").replace(/notPunctSpace/g, v).replace(/punctSpace/g, C).replace(/punct/g, _).getRegex();
5358
+ var We = k(he, "gu").replace(/notPunctSpace/g, Ge).replace(/punctSpace/g, Ze).replace(/punct/g, pe).getRegex();
5359
+ var Xe = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)";
5360
+ var Je = k(Xe, "gu").replace(/notPunctSpace/g, v).replace(/punctSpace/g, C).replace(/punct/g, _).getRegex();
5361
+ var Ve = k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, v).replace(/punctSpace/g, C).replace(/punct/g, _).getRegex();
5362
+ var Ye = "^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)";
5363
+ var et = k(Ye, "gu").replace(/notPunctSpace/g, v).replace(/punctSpace/g, C).replace(/punct/g, _).getRegex();
5364
+ var tt = k(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, _).getRegex();
5365
+ var nt = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)";
5366
+ var rt = k(nt, "gu").replace(/notPunctSpace/g, v).replace(/punctSpace/g, C).replace(/punct/g, _).getRegex();
5367
+ var st = k(/\\(punct)/, "gu").replace(/punct/g, _).getRegex();
5368
+ var it = k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
5369
+ var ot = k(X).replace("(?:-->|$)", "-->").getRegex();
5370
+ var at = k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", ot).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
5371
+ var G = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/;
5372
+ var lt = k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label", G).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
5373
+ var ke = k(/^!?\[(label)\]\[(ref)\]/).replace("label", G).replace("ref", W).getRegex();
5374
+ var de = k(/^!?\[(ref)\](?:\[\])?/).replace("ref", W).getRegex();
5375
+ var ut = k("reflink|nolink(?!\\()", "g").replace("reflink", ke).replace("nolink", de).getRegex();
5376
+ var ie = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;
5377
+ var V = { _backpedal: z, anyPunctuation: st, autolink: it, blockSkip: Qe, br: ue, code: De, del: z, delLDelim: z, delRDelim: z, emStrongLDelim: Ne, emStrongRDelimAst: Ke, emStrongRDelimUnd: Ve, escape: Be, link: lt, nolink: de, punctuation: ve, reflink: ke, reflinkSearch: ut, tag: at, text: qe, url: z };
5378
+ var pt = { ...V, emStrongLDelim: Ue, emStrongRDelimAst: Je, emStrongRDelimUnd: et, link: k(/^!?\[(label)\]\((.*?)\)/).replace("label", G).getRegex(), reflink: k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", G).getRegex() };
5379
+ var F = { ...V, emStrongRDelimAst: We, emStrongLDelim: je, delLDelim: tt, delRDelim: rt, url: k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", ie).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: k(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", ie).getRegex() };
5380
+ var ct = { ...F, br: k(ue).replace("{2,}", "*").getRegex(), text: k(F.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() };
5381
+ var H = { normal: J, gfm: Ie, pedantic: Ce };
5382
+ var B = { normal: V, gfm: F, breaks: ct, pedantic: pt };
5383
+ var ht = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
5384
+ var ge = (l) => ht[l];
5385
+ function T(l, e) {
5386
+ if (e) {
5387
+ if (m.escapeTest.test(l))
5388
+ return l.replace(m.escapeReplace, ge);
5389
+ } else if (m.escapeTestNoEncode.test(l))
5390
+ return l.replace(m.escapeReplaceNoEncode, ge);
5391
+ return l;
5392
+ }
5393
+ function Y(l) {
5394
+ try {
5395
+ l = encodeURI(l).replace(m.percentDecode, "%");
5396
+ } catch {
5397
+ return null;
5398
+ }
5399
+ return l;
5400
+ }
5401
+ function ee(l, e) {
5402
+ let t = l.replace(m.findPipe, (r, i, o) => {
5403
+ let u = false, a = i;
5404
+ for (;--a >= 0 && o[a] === "\\"; )
5405
+ u = !u;
5406
+ return u ? "|" : " |";
5407
+ }), n = t.split(m.splitPipe), s = 0;
5408
+ if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), e)
5409
+ if (n.length > e)
5410
+ n.splice(e);
5411
+ else
5412
+ for (;n.length < e; )
5413
+ n.push("");
5414
+ for (;s < n.length; s++)
5415
+ n[s] = n[s].trim().replace(m.slashPipe, "|");
5416
+ return n;
5417
+ }
5418
+ function $(l, e, t) {
5419
+ let n = l.length;
5420
+ if (n === 0)
5421
+ return "";
5422
+ let s = 0;
5423
+ for (;s < n; ) {
5424
+ let r = l.charAt(n - s - 1);
5425
+ if (r === e && !t)
5426
+ s++;
5427
+ else if (r !== e && t)
5428
+ s++;
5429
+ else
5430
+ break;
5431
+ }
5432
+ return l.slice(0, n - s);
5433
+ }
5434
+ function te(l) {
5435
+ let e = l.split(`
5436
+ `), t = e.length - 1;
5437
+ for (;t >= 0 && m.blankLine.test(e[t]); )
5438
+ t--;
5439
+ return e.length - t <= 2 ? l : e.slice(0, t + 1).join(`
5440
+ `);
5441
+ }
5442
+ function fe(l, e) {
5443
+ if (l.indexOf(e[1]) === -1)
5444
+ return -1;
5445
+ let t = 0;
5446
+ for (let n = 0;n < l.length; n++)
5447
+ if (l[n] === "\\")
5448
+ n++;
5449
+ else if (l[n] === e[0])
5450
+ t++;
5451
+ else if (l[n] === e[1] && (t--, t < 0))
5452
+ return n;
5453
+ return t > 0 ? -2 : -1;
5454
+ }
5455
+ function me(l, e = 0) {
5456
+ let t = e, n = "";
5457
+ for (let s of l)
5458
+ if (s === "\t") {
5459
+ let r = 4 - t % 4;
5460
+ n += " ".repeat(r), t += r;
5461
+ } else
5462
+ n += s, t++;
5463
+ return n;
5464
+ }
5465
+ function xe(l, e, t, n, s) {
5466
+ let r = e.href, i = e.title || null, o = l[1].replace(s.other.outputLinkReplace, "$1"), u = l[0].charAt(0) === "!";
5467
+ n.state.inLink = true;
5468
+ let a = n.state.linkEmitted, p = n.state.inRawBlock;
5469
+ n.state.linkEmitted = false;
5470
+ let c = n.inlineTokens(o), h = n.state.linkEmitted;
5471
+ if (n.state.linkEmitted = a, n.state.inLink = false, !u) {
5472
+ if (h) {
5473
+ n.state.inRawBlock = p;
5474
+ return;
5475
+ }
5476
+ n.state.linkEmitted = true;
5477
+ }
5478
+ return { type: u ? "image" : "link", raw: t, href: r, title: i, text: o, tokens: c };
5479
+ }
5480
+ function kt(l, e, t) {
5481
+ let n = l.match(t.other.indentCodeCompensation);
5482
+ if (n === null)
5483
+ return e;
5484
+ let s = n[1];
5485
+ return e.split(`
5486
+ `).map((r) => {
5487
+ let i = r.match(t.other.beginningSpace);
5488
+ if (i === null)
5489
+ return r;
5490
+ let [o] = i;
5491
+ return o.length >= s.length ? r.slice(s.length) : r;
5492
+ }).join(`
5493
+ `);
5494
+ }
5495
+ var y = class {
5496
+ options;
5497
+ rules;
5498
+ lexer;
5499
+ constructor(e) {
5500
+ this.options = e || R;
5501
+ }
5502
+ space(e) {
5503
+ let t = this.rules.block.newline.exec(e);
5504
+ if (t && t[0].length > 0)
5505
+ return { type: "space", raw: t[0] };
5506
+ }
5507
+ code(e) {
5508
+ let t = this.rules.block.code.exec(e);
5509
+ if (t) {
5510
+ let n = this.options.pedantic ? t[0] : te(t[0]), s = n.replace(this.rules.other.codeRemoveIndent, "");
5511
+ return { type: "code", raw: n, codeBlockStyle: "indented", text: s };
5512
+ }
5513
+ }
5514
+ fences(e) {
5515
+ let t = this.rules.block.fences.exec(e);
5516
+ if (t) {
5517
+ let n = t[0], s = kt(n, t[3] || "", this.rules);
5518
+ return { type: "code", raw: n, lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2], text: s };
5519
+ }
5520
+ }
5521
+ heading(e) {
5522
+ let t = this.rules.block.heading.exec(e);
5523
+ if (t) {
5524
+ let n = t[2].trim();
5525
+ if (this.rules.other.endingHash.test(n)) {
5526
+ let s = $(n, "#");
5527
+ (this.options.pedantic || !s || this.rules.other.endingSpaceChar.test(s)) && (n = s.trim());
5528
+ }
5529
+ return { type: "heading", raw: $(t[0], `
5530
+ `), depth: t[1].length, text: n, tokens: this.lexer.inline(n) };
5531
+ }
5532
+ }
5533
+ hr(e) {
5534
+ let t = this.rules.block.hr.exec(e);
5535
+ if (t)
5536
+ return { type: "hr", raw: $(t[0], `
5537
+ `) };
5538
+ }
5539
+ blockquote(e) {
5540
+ let t = this.rules.block.blockquote.exec(e);
5541
+ if (t) {
5542
+ let n = $(t[0], `
5543
+ `).split(`
5544
+ `), s = "", r = "", i = [];
5545
+ for (;n.length > 0; ) {
5546
+ let o = false, u = [], a;
5547
+ for (a = 0;a < n.length; a++)
5548
+ if (this.rules.other.blockquoteStart.test(n[a]))
5549
+ u.push(n[a]), o = true;
5550
+ else if (!o)
5551
+ u.push(n[a]);
5552
+ else
5553
+ break;
5554
+ n = n.slice(a);
5555
+ let p = u.join(`
5556
+ `), c = p.replace(this.rules.other.blockquoteSetextReplace, `
5557
+ $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
5558
+ s = s ? `${s}
5559
+ ${p}` : p, r = r ? `${r}
5560
+ ${c}` : c;
5561
+ let h = this.lexer.state.top;
5562
+ if (this.lexer.state.top = true, this.lexer.blockTokens(c, i, true), this.lexer.state.top = h, n.length === 0)
5563
+ break;
5564
+ let d = i.at(-1);
5565
+ if (d?.type === "code")
5566
+ break;
5567
+ if (d?.type === "blockquote") {
5568
+ let O = d, g = n.join(`
5569
+ `), w = O.raw + `
5570
+ ` + g.replace(this.rules.other.blockquoteSetextReplace2, ""), E = this.blockquote(w);
5571
+ i[i.length - 1] = E, s = `${s}
5572
+ ${g}`, r = r.substring(0, r.length - O.text.length) + E.text;
5573
+ break;
5574
+ } else if (d?.type === "list") {
5575
+ let O = d, g = O.raw + `
5576
+ ` + n.join(`
5577
+ `), w = this.list(g);
5578
+ i[i.length - 1] = w, s = s.substring(0, s.length - d.raw.length) + w.raw, r = r.substring(0, r.length - O.raw.length) + w.raw, n = g.substring(i.at(-1).raw.length).split(`
5579
+ `);
5580
+ continue;
5581
+ }
5582
+ }
5583
+ return { type: "blockquote", raw: s, tokens: i, text: r };
5584
+ }
5585
+ }
5586
+ list(e) {
5587
+ let t = this.rules.block.list.exec(e);
5588
+ if (t) {
5589
+ let n = t[1].trim(), s = n.length > 1, r = { type: "list", raw: "", ordered: s, start: s ? +n.slice(0, -1) : "", loose: false, items: [] };
5590
+ n = s ? `\\d{1,9}\\${n.slice(-1)}` : `\\${n}`, this.options.pedantic && (n = s ? n : "[*+-]");
5591
+ let i = this.rules.other.listItemRegex(n), o = false;
5592
+ for (;e; ) {
5593
+ let a = false, p = "", c = "";
5594
+ if (!(t = i.exec(e)) || this.rules.block.hr.test(e))
5595
+ break;
5596
+ p = t[0], e = e.substring(p.length);
5597
+ let h = me(t[2].split(`
5598
+ `, 1)[0], t[1].length), d = e.split(`
5599
+ `, 1)[0], O = !h.trim(), g = 0;
5600
+ if (this.options.pedantic ? (g = 2, c = h.trimStart()) : O ? g = t[1].length + 1 : (g = h.search(this.rules.other.nonSpaceChar), g = g > 4 ? 1 : g, c = h.slice(g), g += t[1].length), O && this.rules.other.blankLine.test(d) && (p += d + `
5601
+ `, e = e.substring(d.length + 1), a = true), !a) {
5602
+ let w = this.rules.other.nextBulletRegex(g), E = this.rules.other.hrRegex(g), ne = this.rules.other.fencesBeginRegex(g), re = this.rules.other.headingBeginRegex(g), be = this.rules.other.htmlBeginRegex(g), Re = this.rules.other.blockquoteBeginRegex(g);
5603
+ for (;e; ) {
5604
+ let N = e.split(`
5605
+ `, 1)[0], D;
5606
+ if (d = N, this.options.pedantic ? (d = d.replace(this.rules.other.listReplaceNesting, " "), D = d) : D = d.replace(this.rules.other.tabCharGlobal, " "), ne.test(d) || re.test(d) || be.test(d) || Re.test(d) || w.test(d) || E.test(d))
5607
+ break;
5608
+ if (D.search(this.rules.other.nonSpaceChar) >= g || !d.trim())
5609
+ c += `
5610
+ ` + D.slice(g);
5611
+ else {
5612
+ if (O || h.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || ne.test(h) || re.test(h) || E.test(h))
5613
+ break;
5614
+ c += `
5615
+ ` + d;
5616
+ }
5617
+ O = !d.trim(), p += N + `
5618
+ `, e = e.substring(N.length + 1), h = D.slice(g);
5619
+ }
5620
+ }
5621
+ r.loose || (o ? r.loose = true : this.rules.other.doubleBlankLine.test(p) && (o = true)), r.items.push({ type: "list_item", raw: p, task: !!this.options.gfm && this.rules.other.listIsTask.test(c), loose: false, text: c, tokens: [] }), r.raw += p;
5622
+ }
5623
+ let u = r.items.at(-1);
5624
+ if (u)
5625
+ u.raw = u.raw.trimEnd(), u.text = u.text.trimEnd();
5626
+ else
5627
+ return;
5628
+ r.raw = r.raw.trimEnd();
5629
+ for (let a of r.items)
5630
+ if (this.lexer.state.top = false, a.tokens = this.lexer.blockTokens(a.text, []), !r.loose) {
5631
+ let p = a.tokens.filter((h) => h.type === "space"), c = p.length > 0 && p.some((h) => this.rules.other.anyLine.test(h.raw));
5632
+ r.loose = c;
5633
+ }
5634
+ for (let a of r.items) {
5635
+ let p = a.tokens[0];
5636
+ if (a.task && (p?.type === "text" || p?.type === "paragraph")) {
5637
+ a.text = a.text.replace(this.rules.other.listReplaceTask, ""), p.raw = p.raw.replace(this.rules.other.listReplaceTask, ""), p.text = p.text.replace(this.rules.other.listReplaceTask, "");
5638
+ for (let h = this.lexer.inlineQueue.length - 1;h >= 0; h--)
5639
+ if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)) {
5640
+ this.lexer.inlineQueue[h].src = this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask, "");
5641
+ break;
5642
+ }
5643
+ let c = this.rules.other.listTaskCheckbox.exec(a.raw);
5644
+ if (c) {
5645
+ let h = { type: "checkbox", raw: c[0] + " ", checked: c[0] !== "[ ]" };
5646
+ a.checked = h.checked, r.loose ? a.tokens[0] && ["paragraph", "text"].includes(a.tokens[0].type) && "tokens" in a.tokens[0] && a.tokens[0].tokens ? (a.tokens[0].raw = h.raw + a.tokens[0].raw, a.tokens[0].text = h.raw + a.tokens[0].text, a.tokens[0].tokens.unshift(h)) : a.tokens.unshift({ type: "paragraph", raw: h.raw, text: h.raw, tokens: [h] }) : a.tokens.unshift(h);
5647
+ }
5648
+ } else
5649
+ a.task && (a.task = false);
5650
+ }
5651
+ if (r.loose)
5652
+ for (let a of r.items) {
5653
+ a.loose = true;
5654
+ for (let p of a.tokens)
5655
+ p.type === "text" && (p.type = "paragraph");
5656
+ }
5657
+ return r;
5658
+ }
5659
+ }
5660
+ html(e) {
5661
+ let t = this.rules.block.html.exec(e);
5662
+ if (t) {
5663
+ let n = te(t[0]);
5664
+ return { type: "html", block: true, raw: n, pre: t[1] === "pre" || t[1] === "script" || t[1] === "style", text: n };
5665
+ }
5666
+ }
5667
+ def(e) {
5668
+ let t = this.rules.block.def.exec(e);
5669
+ if (t) {
5670
+ let n = t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), s = t[2] ? t[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", r = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3];
5671
+ return { type: "def", tag: n, raw: $(t[0], `
5672
+ `), href: s, title: r };
5673
+ }
5674
+ }
5675
+ table(e) {
5676
+ let t = this.rules.block.table.exec(e);
5677
+ if (!t || !this.rules.other.tableDelimiter.test(t[2]))
5678
+ return;
5679
+ let n = ee(t[1]), s = t[2].replace(this.rules.other.tableAlignChars, "").split("|"), r = t[3]?.trim() ? t[3].replace(this.rules.other.tableRowBlankLine, "").split(`
5680
+ `) : [], i = { type: "table", raw: $(t[0], `
5681
+ `), header: [], align: [], rows: [] };
5682
+ if (n.length === s.length) {
5683
+ for (let o of s)
5684
+ this.rules.other.tableAlignRight.test(o) ? i.align.push("right") : this.rules.other.tableAlignCenter.test(o) ? i.align.push("center") : this.rules.other.tableAlignLeft.test(o) ? i.align.push("left") : i.align.push(null);
5685
+ for (let o = 0;o < n.length; o++)
5686
+ i.header.push({ text: n[o], tokens: this.lexer.inline(n[o]), header: true, align: i.align[o] });
5687
+ for (let o of r)
5688
+ i.rows.push(ee(o, i.header.length).map((u, a) => ({ text: u, tokens: this.lexer.inline(u), header: false, align: i.align[a] })));
5689
+ return i;
5690
+ }
5691
+ }
5692
+ lheading(e) {
5693
+ let t = this.rules.block.lheading.exec(e);
5694
+ if (t) {
5695
+ let n = t[1].trim();
5696
+ return { type: "heading", raw: $(t[0], `
5697
+ `), depth: t[2].charAt(0) === "=" ? 1 : 2, text: n, tokens: this.lexer.inline(n) };
5698
+ }
5699
+ }
5700
+ paragraph(e) {
5701
+ let t = this.rules.block.paragraph.exec(e);
5702
+ if (t) {
5703
+ let n = t[1].charAt(t[1].length - 1) === `
5704
+ ` ? t[1].slice(0, -1) : t[1];
5705
+ return { type: "paragraph", raw: t[0], text: n, tokens: this.lexer.inline(n) };
5706
+ }
5707
+ }
5708
+ text(e) {
5709
+ let t = this.rules.block.text.exec(e);
5710
+ if (t)
5711
+ return { type: "text", raw: t[0], text: t[0], tokens: this.lexer.inline(t[0]) };
5712
+ }
5713
+ escape(e) {
5714
+ let t = this.rules.inline.escape.exec(e);
5715
+ if (t)
5716
+ return { type: "escape", raw: t[0], text: t[1] };
5717
+ }
5718
+ tag(e) {
5719
+ let t = this.rules.inline.tag.exec(e);
5720
+ if (t)
5721
+ return !this.lexer.state.inLink && this.rules.other.startATag.test(t[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t[0] };
5722
+ }
5723
+ link(e) {
5724
+ let t = this.rules.inline.link.exec(e);
5725
+ if (t) {
5726
+ let n = t[2].trim();
5727
+ if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n)) {
5728
+ if (!this.rules.other.endAngleBracket.test(n))
5729
+ return;
5730
+ let i = $(n.slice(0, -1), "\\");
5731
+ if ((n.length - i.length) % 2 === 0)
5732
+ return;
5733
+ } else {
5734
+ let i = fe(t[2], "()");
5735
+ if (i === -2)
5736
+ return;
5737
+ if (i > -1) {
5738
+ let u = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + i;
5739
+ t[2] = t[2].substring(0, i), t[0] = t[0].substring(0, u).trim(), t[3] = "";
5740
+ }
5741
+ }
5742
+ let s = t[2], r = "";
5743
+ if (this.options.pedantic) {
5744
+ let i = this.rules.other.pedanticHrefTitle.exec(s);
5745
+ i && (s = i[1], r = i[3]);
5746
+ } else
5747
+ r = t[3] ? t[3].slice(1, -1) : "";
5748
+ return s = s.trim(), this.rules.other.startAngleBracket.test(s) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n) ? s = s.slice(1) : s = s.slice(1, -1)), xe(t, { href: s && s.replace(this.rules.inline.anyPunctuation, "$1"), title: r && r.replace(this.rules.inline.anyPunctuation, "$1") }, t[0], this.lexer, this.rules);
5749
+ }
5750
+ }
5751
+ reflink(e, t) {
5752
+ let n;
5753
+ if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) {
5754
+ let s = (n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "), r = t[s.toLowerCase()];
5755
+ if (!r) {
5756
+ let i = n[0].charAt(0);
5757
+ return { type: "text", raw: i, text: i };
5758
+ }
5759
+ return xe(n, r, n[0], this.lexer, this.rules);
5760
+ }
5761
+ }
5762
+ emStrong(e, t, n = "") {
5763
+ let s = this.rules.inline.emStrongLDelim.exec(e);
5764
+ if (!s || !s[1] && !s[2] && !s[3] && !s[4] || s[4] && n.match(this.rules.other.unicodeAlphaNumeric))
5765
+ return;
5766
+ if (!(s[1] || s[3] || "") || !n || this.rules.inline.punctuation.exec(n)) {
5767
+ let i = [...s[0]].length - 1, o, u, a = i, p = 0, c = s[0][0], h = n === c, d = c === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
5768
+ for (d.lastIndex = 0, t = t.slice(-1 * e.length + i);(s = d.exec(t)) !== null; ) {
5769
+ if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o)
5770
+ continue;
5771
+ if (u = [...o].length, s[3] || s[4]) {
5772
+ a += u;
5773
+ continue;
5774
+ } else if (s[5] || s[6]) {
5775
+ if (i % 3 && !((i + u) % 3)) {
5776
+ p += u;
5777
+ continue;
5778
+ }
5779
+ if (h)
5780
+ break;
5781
+ }
5782
+ if (a -= u, a > 0)
5783
+ continue;
5784
+ u = Math.min(u, u + a + p);
5785
+ let O = [...s[0]][0].length, g = e.slice(0, i + s.index + O + u);
5786
+ if (Math.min(i, u) % 2) {
5787
+ let E = g.slice(1, -1);
5788
+ return { type: "em", raw: g, text: E, tokens: this.lexer.inlineTokens(E) };
5789
+ }
5790
+ let w = g.slice(2, -2);
5791
+ return { type: "strong", raw: g, text: w, tokens: this.lexer.inlineTokens(w) };
5792
+ }
5793
+ }
5794
+ }
5795
+ codespan(e) {
5796
+ let t = this.rules.inline.code.exec(e);
5797
+ if (t) {
5798
+ let n = t[2].replace(this.rules.other.newLineCharGlobal, " "), s = this.rules.other.nonSpaceChar.test(n), r = this.rules.other.startingSpaceChar.test(n) && this.rules.other.endingSpaceChar.test(n);
5799
+ return s && r && (n = n.substring(1, n.length - 1)), { type: "codespan", raw: t[0], text: n };
5800
+ }
5801
+ }
5802
+ br(e) {
5803
+ let t = this.rules.inline.br.exec(e);
5804
+ if (t)
5805
+ return { type: "br", raw: t[0] };
5806
+ }
5807
+ del(e, t, n = "") {
5808
+ let s = this.rules.inline.delLDelim.exec(e);
5809
+ if (!s)
5810
+ return;
5811
+ if (!(s[1] || "") || !n || this.rules.inline.punctuation.exec(n)) {
5812
+ let i = [...s[0]].length - 1, o, u, a = i, p = this.rules.inline.delRDelim;
5813
+ for (p.lastIndex = 0, t = t.slice(-1 * e.length + i);(s = p.exec(t)) !== null; ) {
5814
+ if (o = s[1] || s[2] || s[3] || s[4] || s[5] || s[6], !o || (u = [...o].length, u !== i))
5815
+ continue;
5816
+ if (s[3] || s[4]) {
5817
+ a += u;
5818
+ continue;
5819
+ }
5820
+ if (a -= u, a > 0)
5821
+ continue;
5822
+ u = Math.min(u, u + a);
5823
+ let c = [...s[0]][0].length, h = e.slice(0, i + s.index + c + u), d = h.slice(i, -i);
5824
+ return { type: "del", raw: h, text: d, tokens: this.lexer.inlineTokens(d) };
5825
+ }
5826
+ }
5827
+ }
5828
+ autolink(e) {
5829
+ let t = this.rules.inline.autolink.exec(e);
5830
+ if (t) {
5831
+ let n, s;
5832
+ return t[2] === "@" ? (n = t[1], s = "mailto:" + n) : (n = t[1], s = n), { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] };
5833
+ }
5834
+ }
5835
+ url(e) {
5836
+ let t;
5837
+ if (t = this.rules.inline.url.exec(e)) {
5838
+ let n, s;
5839
+ if (t[2] === "@")
5840
+ n = t[0], s = "mailto:" + n;
5841
+ else {
5842
+ let r;
5843
+ do
5844
+ r = t[0], t[0] = this.rules.inline._backpedal.exec(t[0])?.[0] ?? "";
5845
+ while (r !== t[0]);
5846
+ n = t[0], t[1] === "www." ? s = "http://" + t[0] : s = t[0];
5847
+ }
5848
+ return { type: "link", raw: t[0], text: n, href: s, tokens: [{ type: "text", raw: n, text: n }] };
5849
+ }
5850
+ }
5851
+ inlineText(e) {
5852
+ let t = this.rules.inline.text.exec(e);
5853
+ if (t) {
5854
+ let n = this.lexer.state.inRawBlock;
5855
+ return { type: "text", raw: t[0], text: t[0], escaped: n };
5856
+ }
5857
+ }
5858
+ };
5859
+ var x = class l {
5860
+ tokens;
5861
+ options;
5862
+ state;
5863
+ inlineQueue;
5864
+ tokenizer;
5865
+ constructor(e) {
5866
+ this.tokens = [], this.tokens.links = Object.create(null), this.options = e || R, this.options.tokenizer = this.options.tokenizer || new y, this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, linkEmitted: false, top: true };
5867
+ let t = { other: m, block: H.normal, inline: B.normal };
5868
+ this.options.pedantic ? (t.block = H.pedantic, t.inline = B.pedantic) : this.options.gfm && (t.block = H.gfm, this.options.breaks ? t.inline = B.breaks : t.inline = B.gfm), this.tokenizer.rules = t;
5869
+ }
5870
+ static get rules() {
5871
+ return { block: H, inline: B };
5872
+ }
5873
+ static lex(e, t) {
5874
+ return new l(t).lex(e);
5875
+ }
5876
+ static lexInline(e, t) {
5877
+ return new l(t).inlineTokens(e);
5878
+ }
5879
+ lex(e) {
5880
+ e = e.replace(m.carriageReturn, `
5881
+ `), this.blockTokens(e, this.tokens);
5882
+ for (let t = 0;t < this.inlineQueue.length; t++) {
5883
+ let n = this.inlineQueue[t];
5884
+ this.inlineTokens(n.src, n.tokens);
5885
+ }
5886
+ return this.inlineQueue = [], this.tokens;
5887
+ }
5888
+ blockTokens(e, t = [], n = false) {
5889
+ this.tokenizer.lexer = this, this.options.pedantic && (e = e.replace(m.tabCharGlobal, " ").replace(m.spaceLine, ""));
5890
+ let s = 1 / 0;
5891
+ for (;e; ) {
5892
+ if (e.length < s)
5893
+ s = e.length;
5894
+ else {
5895
+ this.infiniteLoopError(e.charCodeAt(0));
5896
+ break;
5897
+ }
5898
+ let r;
5899
+ if (this.options.extensions?.block?.some((o) => (r = o.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), true) : false))
5900
+ continue;
5901
+ if (r = this.tokenizer.space(e)) {
5902
+ e = e.substring(r.raw.length);
5903
+ let o = t.at(-1);
5904
+ r.raw.length === 1 && o !== undefined ? o.raw += `
5905
+ ` : t.push(r);
5906
+ continue;
5907
+ }
5908
+ if (r = this.tokenizer.code(e)) {
5909
+ e = e.substring(r.raw.length);
5910
+ let o = t.at(-1);
5911
+ o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
5912
+ `) ? "" : `
5913
+ `) + r.raw, o.text += `
5914
+ ` + r.text, this.inlineQueue.at(-1).src = o.text) : t.push(r);
5915
+ continue;
5916
+ }
5917
+ if (r = this.tokenizer.fences(e)) {
5918
+ e = e.substring(r.raw.length), t.push(r);
5919
+ continue;
5920
+ }
5921
+ if (r = this.tokenizer.heading(e)) {
5922
+ e = e.substring(r.raw.length), t.push(r);
5923
+ continue;
5924
+ }
5925
+ if (r = this.tokenizer.hr(e)) {
5926
+ e = e.substring(r.raw.length), t.push(r);
5927
+ continue;
5928
+ }
5929
+ if (r = this.tokenizer.blockquote(e)) {
5930
+ e = e.substring(r.raw.length), t.push(r);
5931
+ continue;
5932
+ }
5933
+ if (r = this.tokenizer.list(e)) {
5934
+ e = e.substring(r.raw.length), t.push(r);
5935
+ continue;
5936
+ }
5937
+ if (r = this.tokenizer.html(e)) {
5938
+ e = e.substring(r.raw.length), t.push(r);
5939
+ continue;
5940
+ }
5941
+ if (r = this.tokenizer.def(e)) {
5942
+ e = e.substring(r.raw.length);
5943
+ let o = t.at(-1);
5944
+ o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
5945
+ `) ? "" : `
5946
+ `) + r.raw, o.text += `
5947
+ ` + r.raw, this.inlineQueue.at(-1).src = o.text) : this.tokens.links[r.tag] || (this.tokens.links[r.tag] = { href: r.href, title: r.title }, t.push(r));
5948
+ continue;
5949
+ }
5950
+ if (r = this.tokenizer.table(e)) {
5951
+ e = e.substring(r.raw.length), t.push(r);
5952
+ continue;
5953
+ }
5954
+ if (r = this.tokenizer.lheading(e)) {
5955
+ e = e.substring(r.raw.length), t.push(r);
5956
+ continue;
5957
+ }
5958
+ let i = e;
5959
+ if (this.options.extensions?.startBlock) {
5960
+ let o = 1 / 0, u = e.slice(1), a;
5961
+ this.options.extensions.startBlock.forEach((p) => {
5962
+ a = p.call({ lexer: this }, u), typeof a == "number" && a >= 0 && (o = Math.min(o, a));
5963
+ }), o < 1 / 0 && o >= 0 && (i = e.substring(0, o + 1));
5964
+ }
5965
+ if (this.state.top && (r = this.tokenizer.paragraph(i))) {
5966
+ let o = t.at(-1);
5967
+ n && o?.type === "paragraph" ? (o.raw += (o.raw.endsWith(`
5968
+ `) ? "" : `
5969
+ `) + r.raw, o.text += `
5970
+ ` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r), n = i.length !== e.length, e = e.substring(r.raw.length);
5971
+ continue;
5972
+ }
5973
+ if (r = this.tokenizer.text(e)) {
5974
+ e = e.substring(r.raw.length);
5975
+ let o = t.at(-1);
5976
+ o?.type === "text" ? (o.raw += (o.raw.endsWith(`
5977
+ `) ? "" : `
5978
+ `) + r.raw, o.text += `
5979
+ ` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r);
5980
+ continue;
5981
+ }
5982
+ if (e) {
5983
+ this.infiniteLoopError(e.charCodeAt(0));
5984
+ break;
5985
+ }
5986
+ }
5987
+ return this.state.top = true, t;
5988
+ }
5989
+ inline(e, t = []) {
5990
+ return this.inlineQueue.push({ src: e, tokens: t }), t;
5991
+ }
5992
+ linkInText(e) {
5993
+ if (!e.includes("["))
5994
+ return false;
5995
+ let t = this.tokenizer.rules.inline.link;
5996
+ for (let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))
5997
+ if (t.test(n[0]) && e.charAt(n.index - 1) !== "!")
5998
+ return true;
5999
+ for (let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)) {
6000
+ let s = n[0], r = s.lastIndexOf("[");
6001
+ if (!(s.charAt(0) === "!" || !Object.hasOwn(this.tokens.links, s.slice(r + 1, -1))) && !(r > 1 && this.linkInText(s.slice(1, r - 1))))
6002
+ return true;
6003
+ }
6004
+ return false;
6005
+ }
6006
+ inlineTokens(e, t = []) {
6007
+ this.tokenizer.lexer = this;
6008
+ let n = e;
6009
+ if (this.tokens.links && e.includes("[")) {
6010
+ let o = this.tokenizer.rules.inline.reflinkSearch, u = (a) => {
6011
+ let p = a.lastIndexOf("[");
6012
+ if (!Object.hasOwn(this.tokens.links, a.slice(p + 1, -1)))
6013
+ return a;
6014
+ if (p > 1 && a.charAt(0) !== "!") {
6015
+ let c = a.slice(1, p - 1);
6016
+ if (this.linkInText(c))
6017
+ return "[" + c.replace(o, u) + "][" + "a".repeat(a.length - p - 2) + "]";
6018
+ }
6019
+ return "[" + "a".repeat(a.length - 2) + "]";
6020
+ };
6021
+ n = n.replace(o, u);
6022
+ }
6023
+ n = n.replace(this.tokenizer.rules.inline.anyPunctuation, (o) => "+".repeat(o.length)), n = n.replace(this.tokenizer.rules.inline.blockSkip, (o, u, a) => {
6024
+ let p = a ? a.length : 0;
6025
+ return o.slice(0, p) + "[" + "a".repeat(o.length - p - 2) + "]";
6026
+ }), n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n;
6027
+ let s = false, r = "", i = 1 / 0;
6028
+ for (;e; ) {
6029
+ if (e.length < i)
6030
+ i = e.length;
6031
+ else {
6032
+ this.infiniteLoopError(e.charCodeAt(0));
6033
+ break;
6034
+ }
6035
+ s || (r = ""), s = false;
6036
+ let o;
6037
+ if (this.options.extensions?.inline?.some((a) => (o = a.call({ lexer: this }, e, t)) ? (e = e.substring(o.raw.length), t.push(o), true) : false))
6038
+ continue;
6039
+ if (o = this.tokenizer.escape(e)) {
6040
+ e = e.substring(o.raw.length), t.push(o);
6041
+ continue;
6042
+ }
6043
+ if (o = this.tokenizer.tag(e)) {
6044
+ e = e.substring(o.raw.length), t.push(o);
6045
+ continue;
6046
+ }
6047
+ if (o = this.tokenizer.link(e)) {
6048
+ e = e.substring(o.raw.length), t.push(o);
6049
+ continue;
6050
+ }
6051
+ if (o = this.tokenizer.reflink(e, this.tokens.links)) {
6052
+ e = e.substring(o.raw.length);
6053
+ let a = t.at(-1);
6054
+ o.type === "text" && a?.type === "text" ? (a.raw += o.raw, a.text += o.text) : t.push(o);
6055
+ continue;
6056
+ }
6057
+ if (o = this.tokenizer.emStrong(e, n, r)) {
6058
+ e = e.substring(o.raw.length), t.push(o);
6059
+ continue;
6060
+ }
6061
+ if (o = this.tokenizer.codespan(e)) {
6062
+ e = e.substring(o.raw.length), t.push(o);
6063
+ continue;
6064
+ }
6065
+ if (o = this.tokenizer.br(e)) {
6066
+ e = e.substring(o.raw.length), t.push(o);
6067
+ continue;
6068
+ }
6069
+ if (o = this.tokenizer.del(e, n, r)) {
6070
+ e = e.substring(o.raw.length), t.push(o);
6071
+ continue;
6072
+ }
6073
+ if (o = this.tokenizer.autolink(e)) {
6074
+ e = e.substring(o.raw.length), t.push(o);
6075
+ continue;
6076
+ }
6077
+ if (!this.state.inLink && (o = this.tokenizer.url(e))) {
6078
+ e = e.substring(o.raw.length), t.push(o);
6079
+ continue;
6080
+ }
6081
+ let u = e;
6082
+ if (this.options.extensions?.startInline) {
6083
+ let a = 1 / 0, p = e.slice(1), c;
6084
+ this.options.extensions.startInline.forEach((h) => {
6085
+ c = h.call({ lexer: this }, p), typeof c == "number" && c >= 0 && (a = Math.min(a, c));
6086
+ }), a < 1 / 0 && a >= 0 && (u = e.substring(0, a + 1));
6087
+ }
6088
+ if (o = this.tokenizer.inlineText(u)) {
6089
+ e = e.substring(o.raw.length), o.raw.slice(-1) !== "_" && (r = o.raw.slice(-1)), s = true;
6090
+ let a = t.at(-1);
6091
+ a?.type === "text" ? (a.raw += o.raw, a.text += o.text) : t.push(o);
6092
+ continue;
6093
+ }
6094
+ if (e) {
6095
+ this.infiniteLoopError(e.charCodeAt(0));
6096
+ break;
6097
+ }
6098
+ }
6099
+ return t;
6100
+ }
6101
+ infiniteLoopError(e) {
6102
+ let t = "Infinite loop on byte: " + e;
6103
+ if (this.options.silent)
6104
+ console.error(t);
6105
+ else
6106
+ throw new Error(t);
6107
+ }
6108
+ };
6109
+ var P = class {
6110
+ options;
6111
+ parser;
6112
+ constructor(e) {
6113
+ this.options = e || R;
6114
+ }
6115
+ space(e) {
6116
+ return "";
6117
+ }
6118
+ code({ text: e, lang: t, escaped: n }) {
6119
+ let s = (t || "").match(m.notSpaceStart)?.[0], r = e.replace(m.endingNewline, "") + `
6120
+ `;
6121
+ return s ? '<pre><code class="language-' + T(s) + '">' + (n ? r : T(r, true)) + `</code></pre>
6122
+ ` : "<pre><code>" + (n ? r : T(r, true)) + `</code></pre>
6123
+ `;
6124
+ }
6125
+ blockquote({ tokens: e }) {
6126
+ return `<blockquote>
6127
+ ${this.parser.parse(e)}</blockquote>
6128
+ `;
6129
+ }
6130
+ html({ text: e }) {
6131
+ return e;
6132
+ }
6133
+ def(e) {
6134
+ return "";
6135
+ }
6136
+ heading({ tokens: e, depth: t }) {
6137
+ return `<h${t}>${this.parser.parseInline(e)}</h${t}>
6138
+ `;
6139
+ }
6140
+ hr(e) {
6141
+ return `<hr>
6142
+ `;
6143
+ }
6144
+ list(e) {
6145
+ let { ordered: t, start: n } = e, s = "";
6146
+ for (let o = 0;o < e.items.length; o++) {
6147
+ let u = e.items[o];
6148
+ s += this.listitem(u);
6149
+ }
6150
+ let r = t ? "ol" : "ul", i = t && n !== 1 ? ' start="' + n + '"' : "";
6151
+ return "<" + r + i + `>
6152
+ ` + s + "</" + r + `>
6153
+ `;
6154
+ }
6155
+ listitem(e) {
6156
+ return `<li>${this.parser.parse(e.tokens)}</li>
6157
+ `;
6158
+ }
6159
+ checkbox({ checked: e }) {
6160
+ return "<input " + (e ? 'checked="" ' : "") + 'disabled="" type="checkbox"> ';
6161
+ }
6162
+ paragraph({ tokens: e }) {
6163
+ return `<p>${this.parser.parseInline(e)}</p>
6164
+ `;
6165
+ }
6166
+ table(e) {
6167
+ let t = "", n = "";
6168
+ for (let r = 0;r < e.header.length; r++)
6169
+ n += this.tablecell(e.header[r]);
6170
+ t += this.tablerow({ text: n });
6171
+ let s = "";
6172
+ for (let r = 0;r < e.rows.length; r++) {
6173
+ let i = e.rows[r];
6174
+ n = "";
6175
+ for (let o = 0;o < i.length; o++)
6176
+ n += this.tablecell(i[o]);
6177
+ s += this.tablerow({ text: n });
6178
+ }
6179
+ return s && (s = `<tbody>${s}</tbody>`), `<table>
6180
+ <thead>
6181
+ ` + t + `</thead>
6182
+ ` + s + `</table>
6183
+ `;
6184
+ }
6185
+ tablerow({ text: e }) {
6186
+ return `<tr>
6187
+ ${e}</tr>
6188
+ `;
6189
+ }
6190
+ tablecell(e) {
6191
+ let t = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td";
6192
+ return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t + `</${n}>
6193
+ `;
6194
+ }
6195
+ strong({ tokens: e }) {
6196
+ return `<strong>${this.parser.parseInline(e)}</strong>`;
6197
+ }
6198
+ em({ tokens: e }) {
6199
+ return `<em>${this.parser.parseInline(e)}</em>`;
6200
+ }
6201
+ codespan({ text: e }) {
6202
+ return `<code>${T(e, true)}</code>`;
6203
+ }
6204
+ br(e) {
6205
+ return "<br>";
6206
+ }
6207
+ del({ tokens: e }) {
6208
+ return `<del>${this.parser.parseInline(e)}</del>`;
6209
+ }
6210
+ link({ href: e, title: t, tokens: n }) {
6211
+ let s = this.parser.parseInline(n), r = Y(e);
6212
+ if (r === null)
6213
+ return s;
6214
+ e = r;
6215
+ let i = '<a href="' + e + '"';
6216
+ return t && (i += ' title="' + T(t) + '"'), i += ">" + s + "</a>", i;
6217
+ }
6218
+ image({ href: e, title: t, text: n, tokens: s }) {
6219
+ s && (n = this.parser.parseInline(s, this.parser.textRenderer));
6220
+ let r = Y(e);
6221
+ if (r === null)
6222
+ return T(n);
6223
+ e = r;
6224
+ let i = `<img src="${e}" alt="${T(n)}"`;
6225
+ return t && (i += ` title="${T(t)}"`), i += ">", i;
6226
+ }
6227
+ text(e) {
6228
+ return "tokens" in e && e.tokens ? this.parser.parseInline(e.tokens) : ("escaped" in e) && e.escaped ? e.text : T(e.text);
6229
+ }
6230
+ };
6231
+ var L = class {
6232
+ strong({ text: e }) {
6233
+ return e;
6234
+ }
6235
+ em({ text: e }) {
6236
+ return e;
6237
+ }
6238
+ codespan({ text: e }) {
6239
+ return e;
6240
+ }
6241
+ del({ text: e }) {
6242
+ return e;
6243
+ }
6244
+ html({ text: e }) {
6245
+ return e;
6246
+ }
6247
+ text({ text: e }) {
6248
+ return e;
6249
+ }
6250
+ link({ text: e }) {
6251
+ return "" + e;
6252
+ }
6253
+ image({ text: e }) {
6254
+ return "" + e;
6255
+ }
6256
+ br() {
6257
+ return "";
6258
+ }
6259
+ checkbox({ raw: e }) {
6260
+ return e;
6261
+ }
6262
+ };
6263
+ var b = class l {
6264
+ options;
6265
+ renderer;
6266
+ textRenderer;
6267
+ constructor(e) {
6268
+ this.options = e || R, this.options.renderer = this.options.renderer || new P, this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new L;
6269
+ }
6270
+ static parse(e, t) {
6271
+ return new l(t).parse(e);
6272
+ }
6273
+ static parseInline(e, t) {
6274
+ return new l(t).parseInline(e);
6275
+ }
6276
+ parse(e) {
6277
+ this.renderer.parser = this;
6278
+ let t = "";
6279
+ for (let n = 0;n < e.length; n++) {
6280
+ let s = e[n];
6281
+ if (this.options.extensions?.renderers?.[s.type]) {
6282
+ let i = s, o = this.options.extensions.renderers[i.type].call({ parser: this }, i);
6283
+ if (o !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "checkbox", "html", "def", "paragraph", "text"].includes(i.type)) {
6284
+ t += o || "";
6285
+ continue;
6286
+ }
6287
+ }
6288
+ let r = s;
6289
+ switch (r.type) {
6290
+ case "space": {
6291
+ t += this.renderer.space(r);
6292
+ break;
6293
+ }
6294
+ case "hr": {
6295
+ t += this.renderer.hr(r);
6296
+ break;
6297
+ }
6298
+ case "heading": {
6299
+ t += this.renderer.heading(r);
6300
+ break;
6301
+ }
6302
+ case "code": {
6303
+ t += this.renderer.code(r);
6304
+ break;
6305
+ }
6306
+ case "table": {
6307
+ t += this.renderer.table(r);
6308
+ break;
6309
+ }
6310
+ case "blockquote": {
6311
+ t += this.renderer.blockquote(r);
6312
+ break;
6313
+ }
6314
+ case "list": {
6315
+ t += this.renderer.list(r);
6316
+ break;
6317
+ }
6318
+ case "checkbox": {
6319
+ t += this.renderer.checkbox(r);
6320
+ break;
6321
+ }
6322
+ case "html": {
6323
+ t += this.renderer.html(r);
6324
+ break;
6325
+ }
6326
+ case "def": {
6327
+ t += this.renderer.def(r);
6328
+ break;
6329
+ }
6330
+ case "paragraph": {
6331
+ t += this.renderer.paragraph(r);
6332
+ break;
6333
+ }
6334
+ case "text": {
6335
+ t += this.renderer.text(r);
6336
+ break;
6337
+ }
6338
+ default: {
6339
+ let i = 'Token with "' + r.type + '" type was not found.';
6340
+ if (this.options.silent)
6341
+ return console.error(i), "";
6342
+ throw new Error(i);
6343
+ }
6344
+ }
6345
+ }
6346
+ return t;
6347
+ }
6348
+ parseInline(e, t = this.renderer) {
6349
+ this.renderer.parser = this;
6350
+ let n = "";
6351
+ for (let s = 0;s < e.length; s++) {
6352
+ let r = e[s];
6353
+ if (this.options.extensions?.renderers?.[r.type]) {
6354
+ let o = this.options.extensions.renderers[r.type].call({ parser: this }, r);
6355
+ if (o !== false || !["escape", "html", "link", "image", "checkbox", "strong", "em", "codespan", "br", "del", "text"].includes(r.type)) {
6356
+ n += o || "";
6357
+ continue;
6358
+ }
6359
+ }
6360
+ let i = r;
6361
+ switch (i.type) {
6362
+ case "escape": {
6363
+ n += t.text(i);
6364
+ break;
6365
+ }
6366
+ case "html": {
6367
+ n += t.html(i);
6368
+ break;
6369
+ }
6370
+ case "link": {
6371
+ n += t.link(i);
6372
+ break;
6373
+ }
6374
+ case "image": {
6375
+ n += t.image(i);
6376
+ break;
6377
+ }
6378
+ case "checkbox": {
6379
+ n += t.checkbox(i);
6380
+ break;
6381
+ }
6382
+ case "strong": {
6383
+ n += t.strong(i);
6384
+ break;
6385
+ }
6386
+ case "em": {
6387
+ n += t.em(i);
6388
+ break;
6389
+ }
6390
+ case "codespan": {
6391
+ n += t.codespan(i);
6392
+ break;
6393
+ }
6394
+ case "br": {
6395
+ n += t.br(i);
6396
+ break;
6397
+ }
6398
+ case "del": {
6399
+ n += t.del(i);
6400
+ break;
6401
+ }
6402
+ case "text": {
6403
+ n += t.text(i);
6404
+ break;
6405
+ }
6406
+ default: {
6407
+ let o = 'Token with "' + i.type + '" type was not found.';
6408
+ if (this.options.silent)
6409
+ return console.error(o), "";
6410
+ throw new Error(o);
6411
+ }
6412
+ }
6413
+ }
6414
+ return n;
6415
+ }
6416
+ };
6417
+ var S = class {
6418
+ options;
6419
+ block;
6420
+ constructor(e) {
6421
+ this.options = e || R;
6422
+ }
6423
+ static passThroughHooks = new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
6424
+ static passThroughHooksRespectAsync = new Set(["preprocess", "postprocess", "processAllTokens"]);
6425
+ preprocess(e) {
6426
+ return e;
6427
+ }
6428
+ postprocess(e) {
6429
+ return e;
6430
+ }
6431
+ processAllTokens(e) {
6432
+ return e;
6433
+ }
6434
+ emStrongMask(e) {
6435
+ return e;
6436
+ }
6437
+ provideLexer(e = this.block) {
6438
+ return e ? x.lex : x.lexInline;
6439
+ }
6440
+ provideParser(e = this.block) {
6441
+ return e ? b.parse : b.parseInline;
6442
+ }
6443
+ };
6444
+ var Z = class {
6445
+ defaults = A();
6446
+ options = this.setOptions;
6447
+ parse = this.parseMarkdown(true);
6448
+ parseInline = this.parseMarkdown(false);
6449
+ Parser = b;
6450
+ Renderer = P;
6451
+ TextRenderer = L;
6452
+ Lexer = x;
6453
+ Tokenizer = y;
6454
+ Hooks = S;
6455
+ constructor(...e) {
6456
+ this.use(...e);
6457
+ }
6458
+ walkTokens(e, t) {
6459
+ let n = [];
6460
+ for (let s of e)
6461
+ switch (n = n.concat(t.call(this, s)), s.type) {
6462
+ case "table": {
6463
+ let r = s;
6464
+ for (let i of r.header)
6465
+ n = n.concat(this.walkTokens(i.tokens, t));
6466
+ for (let i of r.rows)
6467
+ for (let o of i)
6468
+ n = n.concat(this.walkTokens(o.tokens, t));
6469
+ break;
6470
+ }
6471
+ case "list": {
6472
+ let r = s;
6473
+ n = n.concat(this.walkTokens(r.items, t));
6474
+ break;
6475
+ }
6476
+ default: {
6477
+ let r = s;
6478
+ this.defaults.extensions?.childTokens?.[r.type] ? this.defaults.extensions.childTokens[r.type].forEach((i) => {
6479
+ let o = r[i].flat(1 / 0);
6480
+ n = n.concat(this.walkTokens(o, t));
6481
+ }) : r.tokens && (n = n.concat(this.walkTokens(r.tokens, t)));
6482
+ }
6483
+ }
6484
+ return n;
6485
+ }
6486
+ use(...e) {
6487
+ let t = this.defaults.extensions || { renderers: {}, childTokens: {} };
6488
+ return e.forEach((n) => {
6489
+ let s = { ...n };
6490
+ if (s.async = this.defaults.async || s.async || false, n.extensions && (n.extensions.forEach((r) => {
6491
+ if (!r.name)
6492
+ throw new Error("extension name required");
6493
+ if ("renderer" in r) {
6494
+ let i = t.renderers[r.name];
6495
+ i ? t.renderers[r.name] = function(...o) {
6496
+ let u = r.renderer.apply(this, o);
6497
+ return u === false && (u = i.apply(this, o)), u;
6498
+ } : t.renderers[r.name] = r.renderer;
6499
+ }
6500
+ if ("tokenizer" in r) {
6501
+ if (!r.level || r.level !== "block" && r.level !== "inline")
6502
+ throw new Error("extension level must be 'block' or 'inline'");
6503
+ let i = t[r.level];
6504
+ i ? i.unshift(r.tokenizer) : t[r.level] = [r.tokenizer], r.start && (r.level === "block" ? t.startBlock ? t.startBlock.push(r.start) : t.startBlock = [r.start] : r.level === "inline" && (t.startInline ? t.startInline.push(r.start) : t.startInline = [r.start]));
6505
+ }
6506
+ "childTokens" in r && r.childTokens && (t.childTokens[r.name] = r.childTokens);
6507
+ }), s.extensions = t), n.renderer) {
6508
+ let r = this.defaults.renderer || new P(this.defaults);
6509
+ for (let i in n.renderer) {
6510
+ if (!(i in r))
6511
+ throw new Error(`renderer '${i}' does not exist`);
6512
+ if (["options", "parser"].includes(i))
6513
+ continue;
6514
+ let o = i, u = n.renderer[o], a = r[o];
6515
+ r[o] = (...p) => {
6516
+ let c = u.apply(r, p);
6517
+ return c === false && (c = a.apply(r, p)), c || "";
6518
+ };
6519
+ }
6520
+ s.renderer = r;
6521
+ }
6522
+ if (n.tokenizer) {
6523
+ let r = this.defaults.tokenizer || new y(this.defaults);
6524
+ for (let i in n.tokenizer) {
6525
+ if (!(i in r))
6526
+ throw new Error(`tokenizer '${i}' does not exist`);
6527
+ if (["options", "rules", "lexer"].includes(i))
6528
+ continue;
6529
+ let o = i, u = n.tokenizer[o], a = r[o];
6530
+ r[o] = (...p) => {
6531
+ let c = u.apply(r, p);
6532
+ return c === false && (c = a.apply(r, p)), c;
6533
+ };
6534
+ }
6535
+ s.tokenizer = r;
6536
+ }
6537
+ if (n.hooks) {
6538
+ let r = this.defaults.hooks || new S;
6539
+ for (let i in n.hooks) {
6540
+ if (!(i in r))
6541
+ throw new Error(`hook '${i}' does not exist`);
6542
+ if (["options", "block"].includes(i))
6543
+ continue;
6544
+ let o = i, u = n.hooks[o], a = r[o];
6545
+ S.passThroughHooks.has(i) ? r[o] = (p) => {
6546
+ if (this.defaults.async && S.passThroughHooksRespectAsync.has(i))
6547
+ return (async () => {
6548
+ let h = await u.call(r, p);
6549
+ return a.call(r, h);
6550
+ })();
6551
+ let c = u.call(r, p);
6552
+ return a.call(r, c);
6553
+ } : r[o] = (...p) => {
6554
+ if (this.defaults.async)
6555
+ return (async () => {
6556
+ let h = await u.apply(r, p);
6557
+ return h === false && (h = await a.apply(r, p)), h;
6558
+ })();
6559
+ let c = u.apply(r, p);
6560
+ return c === false && (c = a.apply(r, p)), c;
6561
+ };
6562
+ }
6563
+ s.hooks = r;
6564
+ }
6565
+ if (n.walkTokens) {
6566
+ let r = this.defaults.walkTokens, i = n.walkTokens;
6567
+ s.walkTokens = function(o) {
6568
+ let u = [];
6569
+ return u.push(i.call(this, o)), r && (u = u.concat(r.call(this, o))), u;
6570
+ };
6571
+ }
6572
+ this.defaults = { ...this.defaults, ...s };
6573
+ }), this;
6574
+ }
6575
+ setOptions(e) {
6576
+ return this.defaults = { ...this.defaults, ...e }, this;
6577
+ }
6578
+ lexer(e, t) {
6579
+ return x.lex(e, t ?? this.defaults);
6580
+ }
6581
+ parser(e, t) {
6582
+ return b.parse(e, t ?? this.defaults);
6583
+ }
6584
+ parseMarkdown(e) {
6585
+ return (n, s) => {
6586
+ let r = { ...s }, i = { ...this.defaults, ...r }, o = this.onError(!!i.silent, !!i.async);
6587
+ if (this.defaults.async === true && r.async === false)
6588
+ return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
6589
+ if (typeof n > "u" || n === null)
6590
+ return o(new Error("marked(): input parameter is undefined or null"));
6591
+ if (typeof n != "string")
6592
+ return o(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n) + ", string expected"));
6593
+ if (i.hooks && (i.hooks.options = i, i.hooks.block = e), i.async)
6594
+ return (async () => {
6595
+ let u = i.hooks ? await i.hooks.preprocess(n) : n, p = await (i.hooks ? await i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(u, i), c = i.hooks ? await i.hooks.processAllTokens(p) : p;
6596
+ i.walkTokens && await Promise.all(this.walkTokens(c, i.walkTokens));
6597
+ let d = await (i.hooks ? await i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(c, i);
6598
+ return i.hooks ? await i.hooks.postprocess(d) : d;
6599
+ })().catch(o);
6600
+ try {
6601
+ i.hooks && (n = i.hooks.preprocess(n));
6602
+ let a = (i.hooks ? i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(n, i);
6603
+ i.hooks && (a = i.hooks.processAllTokens(a)), i.walkTokens && this.walkTokens(a, i.walkTokens);
6604
+ let c = (i.hooks ? i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(a, i);
6605
+ return i.hooks && (c = i.hooks.postprocess(c)), c;
6606
+ } catch (u) {
6607
+ return o(u);
6608
+ }
6609
+ };
6610
+ }
6611
+ onError(e, t) {
6612
+ return (n) => {
6613
+ if (n.message += `
6614
+ Please report this to https://github.com/markedjs/marked.`, e) {
6615
+ let s = "<p>An error occurred:</p><pre>" + T(n.message + "", true) + "</pre>";
6616
+ return t ? Promise.resolve(s) : s;
6617
+ }
6618
+ if (t)
6619
+ return Promise.reject(n);
6620
+ throw n;
6621
+ };
6622
+ }
6623
+ };
6624
+ var M = new Z;
6625
+ function f(l, e) {
6626
+ return M.parse(l, e);
6627
+ }
6628
+ f.options = f.setOptions = function(l) {
6629
+ return M.setOptions(l), f.defaults = M.defaults, j(f.defaults), f;
6630
+ };
6631
+ f.getDefaults = A;
6632
+ f.defaults = R;
6633
+ function dt(...l) {
6634
+ return M.use(...l), f.defaults = M.defaults, j(f.defaults), f;
6635
+ }
6636
+ f.use = dt;
6637
+ f.walkTokens = function(l, e) {
6638
+ return M.walkTokens(l, e);
6639
+ };
6640
+ f.parseInline = M.parseInline;
6641
+ f.Parser = b;
6642
+ f.parser = b.parse;
6643
+ f.Renderer = P;
6644
+ f.TextRenderer = L;
6645
+ f.Lexer = x;
6646
+ f.lexer = x.lex;
6647
+ f.Tokenizer = y;
6648
+ f.Hooks = S;
6649
+ f.parse = f;
6650
+ var nn = f.options;
6651
+ var rn = f.setOptions;
6652
+ var sn = f.walkTokens;
6653
+ var on = f.parseInline;
6654
+ var ln = b.parse;
6655
+ var un = x.lex;
6656
+ // ../../node_modules/.bun/get-east-asian-width@1.6.0/node_modules/get-east-asian-width/lookup-data.js
6657
+ var ambiguousMinimalCodePoint = 161;
6658
+ var ambiguousMaximumCodePoint = 1114109;
6659
+ var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
6660
+ var fullwidthMinimalCodePoint = 12288;
6661
+ var fullwidthMaximumCodePoint = 65510;
6662
+ var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
6663
+ var wideMinimalCodePoint = 4352;
6664
+ var wideMaximumCodePoint = 262141;
6665
+ var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];
6666
+
6667
+ // ../../node_modules/.bun/get-east-asian-width@1.6.0/node_modules/get-east-asian-width/utilities.js
6668
+ var isInRange = (ranges, codePoint) => {
6669
+ let low = 0;
6670
+ let high = Math.floor(ranges.length / 2) - 1;
6671
+ while (low <= high) {
6672
+ const mid = Math.floor((low + high) / 2);
6673
+ const i = mid * 2;
6674
+ if (codePoint < ranges[i]) {
6675
+ high = mid - 1;
6676
+ } else if (codePoint > ranges[i + 1]) {
6677
+ low = mid + 1;
6678
+ } else {
6679
+ return true;
6680
+ }
6681
+ }
6682
+ return false;
6683
+ };
6684
+
6685
+ // ../../node_modules/.bun/get-east-asian-width@1.6.0/node_modules/get-east-asian-width/lookup.js
6686
+ var commonCjkCodePoint = 19968;
6687
+ var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
6688
+ function findWideFastPathRange(ranges) {
6689
+ let fastPathStart = ranges[0];
6690
+ let fastPathEnd = ranges[1];
6691
+ for (let index = 0;index < ranges.length; index += 2) {
6692
+ const start = ranges[index];
6693
+ const end = ranges[index + 1];
6694
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
6695
+ return [start, end];
6696
+ }
6697
+ if (end - start > fastPathEnd - fastPathStart) {
6698
+ fastPathStart = start;
6699
+ fastPathEnd = end;
6700
+ }
6701
+ }
6702
+ return [fastPathStart, fastPathEnd];
6703
+ }
6704
+ var isAmbiguous = (codePoint) => {
6705
+ if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
6706
+ return false;
6707
+ }
6708
+ return isInRange(ambiguousRanges, codePoint);
6709
+ };
6710
+ var isFullWidth = (codePoint) => {
6711
+ if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
6712
+ return false;
6713
+ }
6714
+ return isInRange(fullwidthRanges, codePoint);
6715
+ };
6716
+ var isWide = (codePoint) => {
6717
+ if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
6718
+ return true;
6719
+ }
6720
+ if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
6721
+ return false;
6722
+ }
6723
+ return isInRange(wideRanges, codePoint);
6724
+ };
6725
+
6726
+ // ../../node_modules/.bun/get-east-asian-width@1.6.0/node_modules/get-east-asian-width/index.js
6727
+ function validate(codePoint) {
6728
+ if (!Number.isSafeInteger(codePoint)) {
6729
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
6730
+ }
6731
+ }
6732
+ function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
6733
+ validate(codePoint);
6734
+ if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
6735
+ return 2;
6736
+ }
6737
+ return 1;
6738
+ }
6739
+
6740
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/utils.js
6741
+ var graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
6742
+ var wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });
6743
+ function getGraphemeSegmenter() {
6744
+ return graphemeSegmenter;
6745
+ }
6746
+ function getWordSegmenter() {
6747
+ return wordSegmenter;
6748
+ }
6749
+ function couldBeEmoji(segment) {
6750
+ const cp = segment.codePointAt(0);
6751
+ return cp >= 126976 && cp <= 130047 || cp >= 8960 && cp <= 9215 || cp >= 9728 && cp <= 10175 || cp >= 11088 && cp <= 11093 || segment.includes("️") || segment.length > 2;
6752
+ }
6753
+ var zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
6754
+ var leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
6755
+ var nonPrintingCharRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})$/v;
6756
+ var markCharRegex = /^\p{Mark}$/v;
6757
+ var terminalSpacingMarkRegex = /^(?:[\p{Spacing_Mark}--[\u1734\u302E\u302F]]|[\u065F\u0F7F\u102B\u102C\u1031\u1033-\u1035\u1038\u103A-\u103E])+$/v;
6758
+ var rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
6759
+ var WIDTH_CACHE_SIZE = 512;
6760
+ var widthCache = new Map;
6761
+ var cjkBreakRegex = /[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u;
6762
+ var cjkPunctuationRegex = new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[,.:;!?()[]{}“”‘’…—])`, "u");
6763
+ var autocompleteSeparatorRegex = new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`, "u");
6764
+ var autocompleteBoundaryRegex = new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`, "u");
6765
+ function isPrintableAscii(str) {
6766
+ for (let i = 0;i < str.length; i++) {
6767
+ const code = str.charCodeAt(i);
6768
+ if (code < 32 || code > 126) {
6769
+ return false;
6770
+ }
6771
+ }
6772
+ return true;
6773
+ }
6774
+ function truncateFragmentToWidth(text, maxWidth) {
6775
+ if (maxWidth <= 0 || text.length === 0) {
6776
+ return { text: "", width: 0 };
6777
+ }
6778
+ if (isPrintableAscii(text)) {
6779
+ const clipped = text.slice(0, maxWidth);
6780
+ return { text: clipped, width: clipped.length };
6781
+ }
6782
+ const hasAnsi = text.includes("\x1B");
6783
+ const hasTabs = text.includes("\t");
6784
+ if (!hasAnsi && !hasTabs) {
6785
+ let result = "";
6786
+ let width = 0;
6787
+ for (const { segment } of graphemeSegmenter.segment(text)) {
6788
+ const w = graphemeWidth(segment);
6789
+ if (width + w > maxWidth) {
6790
+ break;
6791
+ }
6792
+ result += segment;
6793
+ width += w;
6794
+ }
6795
+ return { text: result, width };
6796
+ }
6797
+ let result = "";
6798
+ let width = 0;
6799
+ let i = 0;
6800
+ let pendingAnsi = "";
6801
+ while (i < text.length) {
6802
+ const ansi = extractAnsiCode(text, i);
6803
+ if (ansi) {
6804
+ pendingAnsi += ansi.code;
6805
+ i += ansi.length;
6806
+ continue;
6807
+ }
6808
+ if (text[i] === "\t") {
6809
+ if (width + 3 > maxWidth) {
6810
+ break;
6811
+ }
6812
+ if (pendingAnsi) {
6813
+ result += pendingAnsi;
6814
+ pendingAnsi = "";
6815
+ }
6816
+ result += "\t";
6817
+ width += 3;
6818
+ i++;
6819
+ continue;
6820
+ }
6821
+ let end = i;
6822
+ while (end < text.length && text[end] !== "\t") {
6823
+ const nextAnsi = extractAnsiCode(text, end);
6824
+ if (nextAnsi) {
6825
+ break;
6826
+ }
6827
+ end++;
6828
+ }
6829
+ for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
6830
+ const w = graphemeWidth(segment);
6831
+ if (width + w > maxWidth) {
6832
+ return { text: result, width };
6833
+ }
6834
+ if (pendingAnsi) {
6835
+ result += pendingAnsi;
6836
+ pendingAnsi = "";
6837
+ }
6838
+ result += segment;
6839
+ width += w;
6840
+ }
6841
+ i = end;
6842
+ }
6843
+ return { text: result, width };
6844
+ }
6845
+ function finalizeTruncatedResult(prefix, prefixWidth, ellipsis, ellipsisWidth, maxWidth, pad) {
6846
+ const reset = "\x1B[0m";
6847
+ const hyperlinkClose = getActiveOsc8Close(prefix);
6848
+ const visibleWidth = prefixWidth + ellipsisWidth;
6849
+ let result;
6850
+ if (ellipsis.length > 0) {
6851
+ result = `${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`;
6852
+ } else {
6853
+ result = `${prefix}${hyperlinkClose}${reset}`;
6854
+ }
6855
+ return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;
6856
+ }
6857
+ function graphemeWidth(segment) {
6858
+ if (segment.length === 1) {
6859
+ const code = segment.charCodeAt(0);
6860
+ if (code >= 32 && code <= 126)
6861
+ return 1;
6862
+ if (code === 9)
6863
+ return 3;
6864
+ }
6865
+ if (terminalSpacingMarkRegex.test(segment)) {
6866
+ return [...segment].length;
6867
+ }
6868
+ if (zeroWidthRegex.test(segment)) {
6869
+ return 0;
6870
+ }
6871
+ if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {
6872
+ return 2;
6873
+ }
6874
+ const base = segment.replace(leadingNonPrintingRegex, "");
6875
+ const cp = base.codePointAt(0);
6876
+ if (cp === undefined) {
6877
+ return 0;
6878
+ }
6879
+ if (cp >= 127462 && cp <= 127487) {
6880
+ return 2;
6881
+ }
6882
+ let width = eastAsianWidth(cp);
6883
+ let followsMark = false;
6884
+ const chars = [...base];
6885
+ for (const char of chars.slice(1)) {
6886
+ if (terminalSpacingMarkRegex.test(char)) {
6887
+ width += 1;
6888
+ followsMark = false;
6889
+ } else if (markCharRegex.test(char)) {
6890
+ followsMark = true;
6891
+ } else if (!nonPrintingCharRegex.test(char)) {
6892
+ const c = char.codePointAt(0);
6893
+ if (followsMark || c >= 65280 && c <= 65519) {
6894
+ width += eastAsianWidth(c);
6895
+ } else if (c === 3635 || c === 3763) {
6896
+ width += 1;
6897
+ }
6898
+ followsMark = false;
6899
+ }
6900
+ }
6901
+ return width;
6902
+ }
6903
+ function visibleWidth(str) {
6904
+ if (str.length === 0) {
6905
+ return 0;
6906
+ }
6907
+ const asciiWidth = asciiVisibleWidth(str);
6908
+ if (asciiWidth !== -1) {
6909
+ return asciiWidth;
6910
+ }
6911
+ const cached = widthCache.get(str);
6912
+ if (cached !== undefined) {
6913
+ return cached;
6914
+ }
6915
+ let clean = str;
6916
+ if (str.includes("\t")) {
6917
+ clean = clean.replace(/\t/g, " ");
6918
+ }
6919
+ let escapeIndex = clean.indexOf("\x1B");
6920
+ if (escapeIndex !== -1) {
6921
+ let stripped = "";
6922
+ let copyFrom = 0;
6923
+ while (escapeIndex !== -1) {
6924
+ const length = ansiCodeLength(clean, escapeIndex);
6925
+ if (length > 0) {
6926
+ stripped += clean.slice(copyFrom, escapeIndex);
6927
+ escapeIndex += length;
6928
+ copyFrom = escapeIndex;
6929
+ } else {
6930
+ escapeIndex++;
6931
+ }
6932
+ escapeIndex = clean.indexOf("\x1B", escapeIndex);
6933
+ }
6934
+ clean = stripped + clean.slice(copyFrom);
6935
+ }
6936
+ let width = 0;
6937
+ for (const { segment } of graphemeSegmenter.segment(clean)) {
6938
+ width += graphemeWidth(segment);
6939
+ }
6940
+ if (widthCache.size >= WIDTH_CACHE_SIZE) {
6941
+ const firstKey = widthCache.keys().next().value;
6942
+ if (firstKey !== undefined) {
6943
+ widthCache.delete(firstKey);
6944
+ }
6945
+ }
6946
+ widthCache.set(str, width);
6947
+ return width;
6948
+ }
6949
+ function extractAnsiCode(str, pos) {
6950
+ const length = ansiCodeLength(str, pos);
6951
+ return length > 0 ? { code: str.substring(pos, pos + length), length } : null;
6952
+ }
6953
+ function asciiVisibleWidth(str) {
6954
+ let width = 0;
6955
+ let i = 0;
6956
+ while (i < str.length) {
6957
+ const code = str.charCodeAt(i);
6958
+ if (code >= 32 && code <= 126) {
6959
+ width++;
6960
+ i++;
6961
+ } else if (code === 9) {
6962
+ width += 3;
6963
+ i++;
6964
+ } else if (code === 27) {
6965
+ const length = ansiCodeLength(str, i);
6966
+ if (length === 0)
6967
+ return -1;
6968
+ i += length;
6969
+ } else {
6970
+ return -1;
6971
+ }
6972
+ }
6973
+ return width;
5182
6974
  }
5183
- function gravityHeader(deps) {
5184
- try {
5185
- const ctx = deps.getGravityContext?.();
5186
- return ctx ? { [GRAVITY_CONTEXT_HEADER]: ctx } : {};
5187
- } catch {
5188
- return {};
6975
+ function ansiCodeLength(str, pos) {
6976
+ if (pos >= str.length || str.charCodeAt(pos) !== 27)
6977
+ return 0;
6978
+ const next = str[pos + 1];
6979
+ if (next === "[") {
6980
+ for (let j = pos + 2;j < str.length; j++) {
6981
+ const c = str.charCodeAt(j);
6982
+ if (c === 109 || c === 71 || c === 75 || c === 72 || c === 74)
6983
+ return j + 1 - pos;
6984
+ }
6985
+ return 0;
6986
+ }
6987
+ if (next === "]" || next === "_") {
6988
+ for (let j = pos + 2;j < str.length; j++) {
6989
+ const c = str.charCodeAt(j);
6990
+ if (c === 7)
6991
+ return j + 1 - pos;
6992
+ if (c === 27 && str[j + 1] === "\\")
6993
+ return j + 2 - pos;
6994
+ }
6995
+ return 0;
5189
6996
  }
6997
+ return 0;
5190
6998
  }
5191
- var IMP_TIMEOUT_MS = 3000;
5192
- function isGravityImpUrl(raw) {
5193
- if (!raw)
5194
- return false;
5195
- try {
5196
- const u = new URL(raw);
5197
- return u.protocol === "https:" && /(^|\.)trygravity\.(ai|com)$/.test(u.hostname);
5198
- } catch {
5199
- return false;
6999
+ function parseOsc8Hyperlink(ansiCode) {
7000
+ if (!ansiCode.startsWith("\x1B]8;")) {
7001
+ return;
7002
+ }
7003
+ const terminator = ansiCode.endsWith("\x07") ? "\x07" : "\x1B\\";
7004
+ const body = ansiCode.slice(4, terminator === "\x07" ? -1 : -2);
7005
+ const separatorIndex = body.indexOf(";");
7006
+ if (separatorIndex === -1) {
7007
+ return;
7008
+ }
7009
+ const params = body.slice(0, separatorIndex);
7010
+ const url = body.slice(separatorIndex + 1);
7011
+ if (!url) {
7012
+ return null;
5200
7013
  }
7014
+ return { params, url, terminator };
5201
7015
  }
5202
- function fireGravityImpression(deps, ad) {
5203
- if (ad.source !== "gravity" || !isGravityImpUrl(ad.imp_url))
5204
- return false;
5205
- try {
5206
- Promise.resolve((deps.fetchImpl ?? fetch)(ad.imp_url, { method: "GET", signal: AbortSignal.timeout(IMP_TIMEOUT_MS) })).catch(() => {});
5207
- } catch {}
5208
- return true;
7016
+ function formatOsc8Hyperlink(hyperlink) {
7017
+ return `\x1B]8;${hyperlink.params};${hyperlink.url}${hyperlink.terminator}`;
5209
7018
  }
5210
- async function fetchAdNext(deps, slot) {
5211
- try {
5212
- const res = await authedFetch(deps, `/ads/next?slot=${slot}`);
5213
- if (res.status === 204 || !res.ok)
7019
+ function formatOsc8Close(terminator) {
7020
+ return `\x1B]8;;${terminator}`;
7021
+ }
7022
+ function getActiveOsc8Close(prefix) {
7023
+ if (!prefix.includes("\x1B]8;")) {
7024
+ return "";
7025
+ }
7026
+ let activeHyperlink = null;
7027
+ let i = 0;
7028
+ while (i < prefix.length) {
7029
+ const ansi = extractAnsiCode(prefix, i);
7030
+ if (ansi) {
7031
+ const hyperlink = parseOsc8Hyperlink(ansi.code);
7032
+ if (hyperlink !== undefined) {
7033
+ activeHyperlink = hyperlink;
7034
+ }
7035
+ i += ansi.length;
7036
+ } else {
7037
+ i++;
7038
+ }
7039
+ }
7040
+ return activeHyperlink ? formatOsc8Close(activeHyperlink.terminator) : "";
7041
+ }
7042
+
7043
+ class AnsiCodeTracker {
7044
+ bold = false;
7045
+ dim = false;
7046
+ italic = false;
7047
+ underline = false;
7048
+ blink = false;
7049
+ inverse = false;
7050
+ hidden = false;
7051
+ strikethrough = false;
7052
+ fgColor = null;
7053
+ bgColor = null;
7054
+ activeHyperlink = null;
7055
+ process(ansiCode) {
7056
+ const hyperlink = parseOsc8Hyperlink(ansiCode);
7057
+ if (hyperlink !== undefined) {
7058
+ this.activeHyperlink = hyperlink;
5214
7059
  return;
5215
- return await res.json();
5216
- } catch {
5217
- return;
7060
+ }
7061
+ if (!ansiCode.endsWith("m")) {
7062
+ return;
7063
+ }
7064
+ const match = ansiCode.match(/\x1b\[([\d;]*)m/);
7065
+ if (!match)
7066
+ return;
7067
+ const params = match[1];
7068
+ if (params === "" || params === "0") {
7069
+ this.reset();
7070
+ return;
7071
+ }
7072
+ const parts = params.split(";");
7073
+ let i = 0;
7074
+ while (i < parts.length) {
7075
+ const code = Number.parseInt(parts[i], 10);
7076
+ if (code === 38 || code === 48) {
7077
+ if (parts[i + 1] === "5" && parts[i + 2] !== undefined) {
7078
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;
7079
+ if (code === 38) {
7080
+ this.fgColor = colorCode;
7081
+ } else {
7082
+ this.bgColor = colorCode;
7083
+ }
7084
+ i += 3;
7085
+ continue;
7086
+ } else if (parts[i + 1] === "2" && parts[i + 4] !== undefined) {
7087
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;
7088
+ if (code === 38) {
7089
+ this.fgColor = colorCode;
7090
+ } else {
7091
+ this.bgColor = colorCode;
7092
+ }
7093
+ i += 5;
7094
+ continue;
7095
+ }
7096
+ }
7097
+ switch (code) {
7098
+ case 0:
7099
+ this.reset();
7100
+ break;
7101
+ case 1:
7102
+ this.bold = true;
7103
+ break;
7104
+ case 2:
7105
+ this.dim = true;
7106
+ break;
7107
+ case 3:
7108
+ this.italic = true;
7109
+ break;
7110
+ case 4:
7111
+ this.underline = true;
7112
+ break;
7113
+ case 5:
7114
+ this.blink = true;
7115
+ break;
7116
+ case 7:
7117
+ this.inverse = true;
7118
+ break;
7119
+ case 8:
7120
+ this.hidden = true;
7121
+ break;
7122
+ case 9:
7123
+ this.strikethrough = true;
7124
+ break;
7125
+ case 21:
7126
+ this.bold = false;
7127
+ break;
7128
+ case 22:
7129
+ this.bold = false;
7130
+ this.dim = false;
7131
+ break;
7132
+ case 23:
7133
+ this.italic = false;
7134
+ break;
7135
+ case 24:
7136
+ this.underline = false;
7137
+ break;
7138
+ case 25:
7139
+ this.blink = false;
7140
+ break;
7141
+ case 27:
7142
+ this.inverse = false;
7143
+ break;
7144
+ case 28:
7145
+ this.hidden = false;
7146
+ break;
7147
+ case 29:
7148
+ this.strikethrough = false;
7149
+ break;
7150
+ case 39:
7151
+ this.fgColor = null;
7152
+ break;
7153
+ case 49:
7154
+ this.bgColor = null;
7155
+ break;
7156
+ default:
7157
+ if (code >= 30 && code <= 37 || code >= 90 && code <= 97) {
7158
+ this.fgColor = String(code);
7159
+ } else if (code >= 40 && code <= 47 || code >= 100 && code <= 107) {
7160
+ this.bgColor = String(code);
7161
+ }
7162
+ break;
7163
+ }
7164
+ i++;
7165
+ }
7166
+ }
7167
+ reset() {
7168
+ this.bold = false;
7169
+ this.dim = false;
7170
+ this.italic = false;
7171
+ this.underline = false;
7172
+ this.blink = false;
7173
+ this.inverse = false;
7174
+ this.hidden = false;
7175
+ this.strikethrough = false;
7176
+ this.fgColor = null;
7177
+ this.bgColor = null;
7178
+ }
7179
+ clear() {
7180
+ this.reset();
7181
+ this.activeHyperlink = null;
7182
+ }
7183
+ getActiveCodes() {
7184
+ const codes = [];
7185
+ if (this.bold)
7186
+ codes.push("1");
7187
+ if (this.dim)
7188
+ codes.push("2");
7189
+ if (this.italic)
7190
+ codes.push("3");
7191
+ if (this.underline)
7192
+ codes.push("4");
7193
+ if (this.blink)
7194
+ codes.push("5");
7195
+ if (this.inverse)
7196
+ codes.push("7");
7197
+ if (this.hidden)
7198
+ codes.push("8");
7199
+ if (this.strikethrough)
7200
+ codes.push("9");
7201
+ if (this.fgColor)
7202
+ codes.push(this.fgColor);
7203
+ if (this.bgColor)
7204
+ codes.push(this.bgColor);
7205
+ let result = codes.length > 0 ? `\x1B[${codes.join(";")}m` : "";
7206
+ if (this.activeHyperlink) {
7207
+ result += formatOsc8Hyperlink(this.activeHyperlink);
7208
+ }
7209
+ return result;
7210
+ }
7211
+ getActiveBackgroundCode() {
7212
+ return this.bgColor ? `\x1B[${this.bgColor}m` : "";
7213
+ }
7214
+ hasActiveCodes() {
7215
+ return this.bold || this.dim || this.italic || this.underline || this.blink || this.inverse || this.hidden || this.strikethrough || this.fgColor !== null || this.bgColor !== null || this.activeHyperlink !== null;
7216
+ }
7217
+ getLineEndReset() {
7218
+ let result = "";
7219
+ if (this.underline) {
7220
+ result += "\x1B[24m";
7221
+ }
7222
+ if (this.activeHyperlink) {
7223
+ result += formatOsc8Close(this.activeHyperlink.terminator);
7224
+ }
7225
+ return result;
5218
7226
  }
5219
7227
  }
5220
- async function postImpression(deps, adId, clickToken, impFired = false) {
5221
- try {
5222
- await authedFetch(deps, "/ads/impression", {
5223
- method: "POST",
5224
- body: JSON.stringify({ ad_id: adId, click_token: clickToken, ...impFired ? { imp_fired: true } : {} })
5225
- });
5226
- } catch {}
7228
+ function truncateToWidth(text, maxWidth, ellipsis = "...", pad = false) {
7229
+ if (maxWidth <= 0) {
7230
+ return "";
7231
+ }
7232
+ if (text.length === 0) {
7233
+ return pad ? " ".repeat(maxWidth) : "";
7234
+ }
7235
+ const ellipsisWidth = visibleWidth(ellipsis);
7236
+ if (ellipsisWidth >= maxWidth) {
7237
+ const textWidth = visibleWidth(text);
7238
+ if (textWidth <= maxWidth) {
7239
+ return pad ? text + " ".repeat(maxWidth - textWidth) : text;
7240
+ }
7241
+ const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);
7242
+ if (clippedEllipsis.width === 0) {
7243
+ return pad ? " ".repeat(maxWidth) : "";
7244
+ }
7245
+ return finalizeTruncatedResult("", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);
7246
+ }
7247
+ if (isPrintableAscii(text)) {
7248
+ if (text.length <= maxWidth) {
7249
+ return pad ? text + " ".repeat(maxWidth - text.length) : text;
7250
+ }
7251
+ const targetWidth = maxWidth - ellipsisWidth;
7252
+ return finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);
7253
+ }
7254
+ const targetWidth = maxWidth - ellipsisWidth;
7255
+ let result = "";
7256
+ let pendingAnsi = "";
7257
+ let visibleSoFar = 0;
7258
+ let keptWidth = 0;
7259
+ let keepContiguousPrefix = true;
7260
+ let overflowed = false;
7261
+ let exhaustedInput = false;
7262
+ const hasAnsi = text.includes("\x1B");
7263
+ const hasTabs = text.includes("\t");
7264
+ if (!hasAnsi && !hasTabs) {
7265
+ for (const { segment } of graphemeSegmenter.segment(text)) {
7266
+ const width = graphemeWidth(segment);
7267
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
7268
+ result += segment;
7269
+ keptWidth += width;
7270
+ } else {
7271
+ keepContiguousPrefix = false;
7272
+ }
7273
+ visibleSoFar += width;
7274
+ if (visibleSoFar > maxWidth) {
7275
+ overflowed = true;
7276
+ break;
7277
+ }
7278
+ }
7279
+ exhaustedInput = !overflowed;
7280
+ } else {
7281
+ let i = 0;
7282
+ while (i < text.length) {
7283
+ const ansi = extractAnsiCode(text, i);
7284
+ if (ansi) {
7285
+ pendingAnsi += ansi.code;
7286
+ i += ansi.length;
7287
+ continue;
7288
+ }
7289
+ if (text[i] === "\t") {
7290
+ if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {
7291
+ if (pendingAnsi) {
7292
+ result += pendingAnsi;
7293
+ pendingAnsi = "";
7294
+ }
7295
+ result += "\t";
7296
+ keptWidth += 3;
7297
+ } else {
7298
+ keepContiguousPrefix = false;
7299
+ pendingAnsi = "";
7300
+ }
7301
+ visibleSoFar += 3;
7302
+ if (visibleSoFar > maxWidth) {
7303
+ overflowed = true;
7304
+ break;
7305
+ }
7306
+ i++;
7307
+ continue;
7308
+ }
7309
+ let end = i;
7310
+ while (end < text.length && text[end] !== "\t") {
7311
+ const nextAnsi = extractAnsiCode(text, end);
7312
+ if (nextAnsi) {
7313
+ break;
7314
+ }
7315
+ end++;
7316
+ }
7317
+ for (const { segment } of graphemeSegmenter.segment(text.slice(i, end))) {
7318
+ const width = graphemeWidth(segment);
7319
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
7320
+ if (pendingAnsi) {
7321
+ result += pendingAnsi;
7322
+ pendingAnsi = "";
7323
+ }
7324
+ result += segment;
7325
+ keptWidth += width;
7326
+ } else {
7327
+ keepContiguousPrefix = false;
7328
+ pendingAnsi = "";
7329
+ }
7330
+ visibleSoFar += width;
7331
+ if (visibleSoFar > maxWidth) {
7332
+ overflowed = true;
7333
+ break;
7334
+ }
7335
+ }
7336
+ if (overflowed) {
7337
+ break;
7338
+ }
7339
+ i = end;
7340
+ }
7341
+ exhaustedInput = i >= text.length;
7342
+ }
7343
+ if (!overflowed && exhaustedInput) {
7344
+ return pad ? text + " ".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;
7345
+ }
7346
+ return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);
5227
7347
  }
5228
- async function fetchMe(deps) {
5229
- try {
5230
- const res = await authedFetch(deps, "/me");
5231
- if (!res.ok)
7348
+ var pooledStyleTracker = new AnsiCodeTracker;
7349
+
7350
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/autocomplete.js
7351
+ var PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);
7352
+ var tokenStartRegex = new RegExp(`${autocompleteBoundaryRegex.source}$`, "u");
7353
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/oklab.js
7354
+ var K1 = 0.206;
7355
+ var K2 = 0.03;
7356
+ var K3 = (1 + K1) / (1 + K2);
7357
+
7358
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/colors.js
7359
+ var NUMBER_PATTERN = String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`;
7360
+ var OKLCH_PATTERN = new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)$`, "i");
7361
+ var OKHSL_PATTERN = new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`, "i");
7362
+ var GRAY_VALUES = Array.from({ length: 24 }, (_, index) => 8 + index * 10);
7363
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/keys.js
7364
+ var SYMBOL_KEYS = new Set([
7365
+ "`",
7366
+ "-",
7367
+ "=",
7368
+ "[",
7369
+ "]",
7370
+ "\\",
7371
+ ";",
7372
+ "'",
7373
+ ",",
7374
+ ".",
7375
+ "/",
7376
+ "!",
7377
+ "@",
7378
+ "#",
7379
+ "$",
7380
+ "%",
7381
+ "^",
7382
+ "&",
7383
+ "*",
7384
+ "(",
7385
+ ")",
7386
+ "_",
7387
+ "+",
7388
+ "|",
7389
+ "~",
7390
+ "{",
7391
+ "}",
7392
+ ":",
7393
+ "<",
7394
+ ">",
7395
+ "?"
7396
+ ]);
7397
+ var SHIFTED_SYMBOL_KEYS = new Set("~!@#$%^&*()_+|{}:<>?");
7398
+ var MODIFIERS = {
7399
+ shift: 1,
7400
+ alt: 2,
7401
+ ctrl: 4,
7402
+ super: 8
7403
+ };
7404
+ var LOCK_MASK = 64 + 128;
7405
+ var ARROW_CODEPOINTS = {
7406
+ up: -1,
7407
+ down: -2,
7408
+ right: -3,
7409
+ left: -4
7410
+ };
7411
+ var FUNCTIONAL_CODEPOINTS = {
7412
+ delete: -10,
7413
+ insert: -11,
7414
+ pageUp: -12,
7415
+ pageDown: -13,
7416
+ home: -14,
7417
+ end: -15
7418
+ };
7419
+ var KITTY_FUNCTIONAL_KEY_EQUIVALENTS = new Map([
7420
+ [57399, 48],
7421
+ [57400, 49],
7422
+ [57401, 50],
7423
+ [57402, 51],
7424
+ [57403, 52],
7425
+ [57404, 53],
7426
+ [57405, 54],
7427
+ [57406, 55],
7428
+ [57407, 56],
7429
+ [57408, 57],
7430
+ [57409, 46],
7431
+ [57410, 47],
7432
+ [57411, 42],
7433
+ [57412, 45],
7434
+ [57413, 43],
7435
+ [57415, 61],
7436
+ [57416, 44],
7437
+ [57417, ARROW_CODEPOINTS.left],
7438
+ [57418, ARROW_CODEPOINTS.right],
7439
+ [57419, ARROW_CODEPOINTS.up],
7440
+ [57420, ARROW_CODEPOINTS.down],
7441
+ [57421, FUNCTIONAL_CODEPOINTS.pageUp],
7442
+ [57422, FUNCTIONAL_CODEPOINTS.pageDown],
7443
+ [57423, FUNCTIONAL_CODEPOINTS.home],
7444
+ [57424, FUNCTIONAL_CODEPOINTS.end],
7445
+ [57425, FUNCTIONAL_CODEPOINTS.insert],
7446
+ [57426, FUNCTIONAL_CODEPOINTS.delete]
7447
+ ]);
7448
+ var KITTY_PRINTABLE_ALLOWED_MODIFIERS = MODIFIERS.shift | LOCK_MASK;
7449
+
7450
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/terminal-image.js
7451
+ var kittyImageMetadata = new Map;
7452
+ var KITTY_PLACEMENT_CONTROL_KEYS = new Set([
7453
+ "i",
7454
+ "p",
7455
+ "x",
7456
+ "y",
7457
+ "w",
7458
+ "h",
7459
+ "X",
7460
+ "Y",
7461
+ "c",
7462
+ "r",
7463
+ "C",
7464
+ "U",
7465
+ "z",
7466
+ "P",
7467
+ "Q",
7468
+ "H",
7469
+ "V"
7470
+ ]);
7471
+
7472
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/tui.js
7473
+ var TERMINAL_PALETTE_SIZE = 16;
7474
+ var TERMINAL_COLOR_REPLY_COUNT = 2 + TERMINAL_PALETTE_SIZE;
7475
+ var TERMINAL_COLOR_QUERY = `\x1B]10;?\x07\x1B]11;?\x07${Array.from({ length: TERMINAL_PALETTE_SIZE }, (_, index) => `\x1B]4;${index};?\x07`).join("")}\x1B[c`;
7476
+ var VIEWPORT_TUI = Symbol.for("@earendil-works/pi-tui/viewport");
7477
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/word-navigation.js
7478
+ var wordSegmenter2 = getWordSegmenter();
7479
+
7480
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/components/editor.js
7481
+ var graphemeSegmenter2 = getGraphemeSegmenter();
7482
+ var wordSegmenter3 = getWordSegmenter();
7483
+ var unquotedAutocompleteSuffixRegex = new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`, "u");
7484
+ var autocompleteTokenStartSource = `${autocompleteBoundaryRegex.source}[([{<\`]*`;
7485
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/layout-node.js
7486
+ var LAYOUT_NODE = Symbol.for("@earendil-works/pi-tui/layout-node");
7487
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/components/image.js
7488
+ var pngCache = new Map;
7489
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/components/input.js
7490
+ var segmenter = getGraphemeSegmenter();
7491
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/latex.js
7492
+ var NAMED_OPERATORS = new Set([
7493
+ "arccos",
7494
+ "arcsin",
7495
+ "arctan",
7496
+ "arg",
7497
+ "cos",
7498
+ "cosh",
7499
+ "cot",
7500
+ "coth",
7501
+ "csc",
7502
+ "deg",
7503
+ "det",
7504
+ "dim",
7505
+ "exp",
7506
+ "gcd",
7507
+ "hom",
7508
+ "inf",
7509
+ "ker",
7510
+ "lg",
7511
+ "lim",
7512
+ "liminf",
7513
+ "limsup",
7514
+ "ln",
7515
+ "log",
7516
+ "max",
7517
+ "min",
7518
+ "Pr",
7519
+ "sec",
7520
+ "sin",
7521
+ "sinh",
7522
+ "sup",
7523
+ "tan",
7524
+ "tanh"
7525
+ ]);
7526
+ var LIMIT_OPERATORS = new Set([
7527
+ "argmax",
7528
+ "argmin",
7529
+ "inf",
7530
+ "injlim",
7531
+ "lim",
7532
+ "liminf",
7533
+ "limsup",
7534
+ "max",
7535
+ "min",
7536
+ "projlim",
7537
+ "sup"
7538
+ ]);
7539
+ var DISPLAY_LIMIT_SYMBOLS = new Set([
7540
+ "bigcap",
7541
+ "bigcup",
7542
+ "bigodot",
7543
+ "bigoplus",
7544
+ "bigotimes",
7545
+ "bigsqcup",
7546
+ "biguplus",
7547
+ "bigvee",
7548
+ "bigwedge",
7549
+ "coprod",
7550
+ "int",
7551
+ "iint",
7552
+ "iiint",
7553
+ "oint",
7554
+ "prod",
7555
+ "sum"
7556
+ ]);
7557
+ var RELATION_COMMANDS = new Set([
7558
+ "Leftarrow",
7559
+ "Leftrightarrow",
7560
+ "Longleftarrow",
7561
+ "Longleftrightarrow",
7562
+ "Longrightarrow",
7563
+ "Rightarrow",
7564
+ "Join",
7565
+ "Vdash",
7566
+ "Vvdash",
7567
+ "approx",
7568
+ "asymp",
7569
+ "bowtie",
7570
+ "cong",
7571
+ "dashv",
7572
+ "fullouterjoin",
7573
+ "doteq",
7574
+ "downarrow",
7575
+ "equiv",
7576
+ "ge",
7577
+ "geq",
7578
+ "geqslant",
7579
+ "gets",
7580
+ "gg",
7581
+ "hookleftarrow",
7582
+ "hookrightarrow",
7583
+ "iff",
7584
+ "implies",
7585
+ "in",
7586
+ "leadsto",
7587
+ "le",
7588
+ "leftarrow",
7589
+ "leftharpoondown",
7590
+ "leftharpoonup",
7591
+ "leftrightarrow",
7592
+ "leftrightharpoons",
7593
+ "leftouterjoin",
7594
+ "leq",
7595
+ "leqslant",
7596
+ "ll",
7597
+ "longleftarrow",
7598
+ "longleftrightarrow",
7599
+ "longmapsto",
7600
+ "longrightarrow",
7601
+ "ltimes",
7602
+ "mapsto",
7603
+ "mid",
7604
+ "models",
7605
+ "ne",
7606
+ "nearrow",
7607
+ "neq",
7608
+ "ni",
7609
+ "notin",
7610
+ "nvdash",
7611
+ "nvDash",
7612
+ "nwarrow",
7613
+ "parallel",
7614
+ "perp",
7615
+ "prec",
7616
+ "preceq",
7617
+ "propto",
7618
+ "rightharpoondown",
7619
+ "rightharpoonup",
7620
+ "rightleftharpoons",
7621
+ "rightouterjoin",
7622
+ "rightarrow",
7623
+ "rightsquigarrow",
7624
+ "rtimes",
7625
+ "searrow",
7626
+ "sim",
7627
+ "simeq",
7628
+ "sqsubset",
7629
+ "sqsubseteq",
7630
+ "sqsupset",
7631
+ "sqsupseteq",
7632
+ "subset",
7633
+ "subseteq",
7634
+ "succ",
7635
+ "succeq",
7636
+ "supset",
7637
+ "supseteq",
7638
+ "swarrow",
7639
+ "to",
7640
+ "triangleleft",
7641
+ "triangleright",
7642
+ "twoheadleftarrow",
7643
+ "twoheadrightarrow",
7644
+ "uparrow",
7645
+ "vdash"
7646
+ ]);
7647
+ var SPACING_COMMANDS = new Set([
7648
+ ",",
7649
+ ":",
7650
+ ";",
7651
+ " ",
7652
+ ">",
7653
+ "enspace",
7654
+ "enskip",
7655
+ "medspace",
7656
+ "quad",
7657
+ "qquad",
7658
+ "thickspace",
7659
+ "thinspace"
7660
+ ]);
7661
+ var NEGATIVE_SPACING_COMMANDS = new Set(["!", "negmedspace", "negthickspace", "negthinspace"]);
7662
+ var FONT_SWITCH_COMMANDS = new Set(["bf", "cal", "it", "rm", "sf", "sl", "tt"]);
7663
+ var IGNORED_COMMANDS = new Set([
7664
+ "displaystyle",
7665
+ "limits",
7666
+ "nolimits",
7667
+ "scriptstyle",
7668
+ "scriptscriptstyle",
7669
+ "textstyle"
7670
+ ]);
7671
+ var SIZE_COMMANDS = new Set([
7672
+ "big",
7673
+ "Big",
7674
+ "bigg",
7675
+ "Bigg",
7676
+ "bigl",
7677
+ "Bigl",
7678
+ "biggl",
7679
+ "Biggl",
7680
+ "bigr",
7681
+ "Bigr",
7682
+ "biggr",
7683
+ "Biggr"
7684
+ ]);
7685
+ var PLAIN_WRAPPERS = new Set([
7686
+ "emph",
7687
+ "mathcal",
7688
+ "mathbf",
7689
+ "mathfrak",
7690
+ "mathit",
7691
+ "mathrm",
7692
+ "mathnormal",
7693
+ "mathscr",
7694
+ "mathsf",
7695
+ "mathtt",
7696
+ "mathup",
7697
+ "mbox",
7698
+ "overbrace",
7699
+ "pmb",
7700
+ "smash",
7701
+ "substack",
7702
+ "text",
7703
+ "textbf",
7704
+ "textit",
7705
+ "textmd",
7706
+ "textnormal",
7707
+ "textrm",
7708
+ "textsc",
7709
+ "textsf",
7710
+ "textsl",
7711
+ "texttt",
7712
+ "textup",
7713
+ "underbrace",
7714
+ "bm",
7715
+ "boldsymbol"
7716
+ ]);
7717
+
7718
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/components/markdown.js
7719
+ var STRICT_STRIKETHROUGH_REGEX = /^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;
7720
+
7721
+ class StrictStrikethroughTokenizer extends y {
7722
+ del(src) {
7723
+ const match = STRICT_STRIKETHROUGH_REGEX.exec(src);
7724
+ if (!match) {
5232
7725
  return;
5233
- return await res.json();
5234
- } catch {
7726
+ }
7727
+ const text = match[2];
7728
+ return {
7729
+ type: "del",
7730
+ raw: match[0],
7731
+ text,
7732
+ tokens: this.lexer.inlineTokens(text)
7733
+ };
7734
+ }
7735
+ }
7736
+ function isEscaped(source, index) {
7737
+ let backslashes = 0;
7738
+ for (let position = index - 1;position >= 0 && source[position] === "\\"; position--) {
7739
+ backslashes++;
7740
+ }
7741
+ return backslashes % 2 === 1;
7742
+ }
7743
+ function findClosingDelimiter(source, closing, start) {
7744
+ let index = source.indexOf(closing, start);
7745
+ while (index >= 0 && isEscaped(source, index)) {
7746
+ index = source.indexOf(closing, index + closing.length);
7747
+ }
7748
+ return index;
7749
+ }
7750
+ function looksLikePendingDollarMath(source) {
7751
+ return /\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source);
7752
+ }
7753
+ function tokenizeInlineLatex(source) {
7754
+ let opening = "";
7755
+ let closing = "";
7756
+ if (source.startsWith("$$")) {
7757
+ opening = "$$";
7758
+ closing = "$$";
7759
+ } else if (source.startsWith("\\(")) {
7760
+ opening = "\\(";
7761
+ closing = "\\)";
7762
+ } else if (source.startsWith("\\[")) {
7763
+ opening = "\\[";
7764
+ closing = "\\]";
7765
+ } else if (source.startsWith("$") && !/^\$\s/.test(source)) {
7766
+ opening = "$";
7767
+ closing = "$";
7768
+ } else {
7769
+ return;
7770
+ }
7771
+ const closingIndex = findClosingDelimiter(source, closing, opening.length);
7772
+ if (closingIndex >= 0 && opening === "$" && (/\s$/.test(source.slice(opening.length, closingIndex)) || /^\d/.test(source.slice(closingIndex + 1)) || /^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length, closingIndex)) && /^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex + 1)) || source.slice(opening.length, closingIndex).includes("`"))) {
7773
+ return;
7774
+ }
7775
+ if (closingIndex < 0) {
7776
+ const pendingSource = source.slice(opening.length);
7777
+ if (opening.startsWith("\\") || looksLikePendingDollarMath(pendingSource)) {
7778
+ return { type: "latex", raw: source, text: pendingSource, pending: true };
7779
+ }
7780
+ return;
7781
+ }
7782
+ const text = source.slice(opening.length, closingIndex);
7783
+ if (!text || text.includes(`
7784
+ `)) {
5235
7785
  return;
5236
7786
  }
7787
+ const raw = source.slice(0, closingIndex + closing.length);
7788
+ return { type: "latex", raw, text };
7789
+ }
7790
+ function tokenizeBlockLatex(source) {
7791
+ const dollarMatch = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);
7792
+ if (dollarMatch?.[1]) {
7793
+ return { type: "latexBlock", raw: dollarMatch[0], text: dollarMatch[1].trim() };
7794
+ }
7795
+ const bracketMatch = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);
7796
+ if (bracketMatch?.[1]) {
7797
+ return { type: "latexBlock", raw: bracketMatch[0], text: bracketMatch[1].trim() };
7798
+ }
7799
+ const pendingBracket = /^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
7800
+ if (pendingBracket) {
7801
+ return { type: "latexBlock", raw: pendingBracket[0], text: pendingBracket[1], pending: true };
7802
+ }
7803
+ const pendingDollar = /^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);
7804
+ if (pendingDollar?.[1] && looksLikePendingDollarMath(pendingDollar[1])) {
7805
+ return { type: "latexBlock", raw: pendingDollar[0], text: pendingDollar[1], pending: true };
7806
+ }
7807
+ return;
5237
7808
  }
7809
+ var LATEX_MARKDOWN_EXTENSIONS = [
7810
+ {
7811
+ name: "latexBlock",
7812
+ level: "block",
7813
+ start(source) {
7814
+ const match = /(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);
7815
+ return match ? match.index + (match[0].startsWith(`
7816
+ `) ? 1 : 0) : undefined;
7817
+ },
7818
+ tokenizer: tokenizeBlockLatex
7819
+ },
7820
+ {
7821
+ name: "latex",
7822
+ level: "inline",
7823
+ start(source) {
7824
+ const indices = [source.indexOf("$"), source.indexOf("\\("), source.indexOf("\\[")].filter((index) => index >= 0);
7825
+ return indices.length > 0 ? Math.min(...indices) : undefined;
7826
+ },
7827
+ tokenizer: tokenizeInlineLatex
7828
+ }
7829
+ ];
7830
+ var markdownParser = new Z;
7831
+ markdownParser.setOptions({
7832
+ tokenizer: new StrictStrikethroughTokenizer
7833
+ });
7834
+ markdownParser.use({ extensions: [...LATEX_MARKDOWN_EXTENSIONS] });
7835
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/native-platform.js
7836
+ import { createRequire as createRequire2 } from "node:module";
7837
+
7838
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/native-module-path.js
7839
+ import { createRequire } from "node:module";
7840
+ var moduleRequire = createRequire(import.meta.url);
5238
7841
 
7842
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/native-platform.js
7843
+ var cjsRequire = createRequire2(import.meta.url);
7844
+ var helpers = new Map;
7845
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/terminal.js
7846
+ var DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS = 7;
7847
+ var KITTY_KEYBOARD_PROTOCOL_QUERY = `\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`;
7848
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/alt-screen-search.js
7849
+ var segmenter2 = getGraphemeSegmenter();
7850
+
7851
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js
7852
+ var MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES = 32 * 1024 * 1024;
7853
+ var MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES = 64 * 1024 * 1024;
7854
+ var TERMINAL_WORD_SELECTION_JOINERS = new Set(["/", "-"]);
7855
+ var wordSegmenter4 = getWordSegmenter();
7856
+ // ../../node_modules/.bun/@earendil-works+pi-tui@1.2.0/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js
7857
+ var MAX_RENDER_WRITE_CHARS = 1024 * 1024;
5239
7858
  // ../pi-ads/src/style.ts
5240
- import { createHash as createHash2 } from "node:crypto";
5241
7859
  var OSC_RE = /\x1b\][\s\S]*?(?:\x07|\x1b\\)/g;
5242
7860
  var CSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
5243
7861
  var C1_RE = /[\x80-\x9f]/g;
@@ -5245,17 +7863,8 @@ var C0_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g;
5245
7863
  function sanitizeText(input) {
5246
7864
  return input.replace(OSC_RE, "").replace(CSI_RE, "").replace(/\x1b/g, "").replace(C1_RE, "").replace(/[\t\r\n]+/g, " ").replace(C0_RE, "").trim();
5247
7865
  }
5248
- function truncate(text, maxWidth) {
5249
- if (maxWidth <= 0)
5250
- return "";
5251
- if (text.length <= maxWidth)
5252
- return text;
5253
- if (maxWidth <= 1)
5254
- return text.slice(0, maxWidth);
5255
- return `${text.slice(0, maxWidth - 1)}…`;
5256
- }
5257
- function pad(text, width) {
5258
- return text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
7866
+ function fit(text, width) {
7867
+ return truncateToWidth(text, Math.max(0, width), "…", true);
5259
7868
  }
5260
7869
  function osc8(text, url, id) {
5261
7870
  const params = id ? `id=${id}` : "";
@@ -5272,7 +7881,7 @@ function renderAdCard(creative, clickUrl, theme, columns) {
5272
7881
  const bottom = `└${"─".repeat(innerWidth + 2)}┘`;
5273
7882
  const linkId = createHash2("sha256").update(url).digest("hex").slice(0, 12);
5274
7883
  const row = (text, opts) => {
5275
- const plain = pad(truncate(text, innerWidth), innerWidth);
7884
+ const plain = fit(text, innerWidth);
5276
7885
  let styled = theme.fg("accent", plain);
5277
7886
  if (opts?.bold)
5278
7887
  styled = theme.bold(styled);
@@ -5290,9 +7899,16 @@ function renderPlainAdLine(creative, clickUrl, theme, columns) {
5290
7899
  const headline = sanitizeText(creative.headline);
5291
7900
  const cta = sanitizeText(creative.cta);
5292
7901
  const url = sanitizeText(clickUrl);
5293
- const plain = truncate(`AD ▚ ${headline} — ${cta}`, Math.max(10, columns - 2));
7902
+ const plain = truncateToWidth(`AD ▚ ${headline} — ${cta}`, Math.max(0, columns - 2), "…");
5294
7903
  return theme.fg("dim", osc8(plain, url));
5295
7904
  }
7905
+ var CARD_MIN_COLUMNS = 25;
7906
+ function adWidget(creative, clickUrl, adMinColumns) {
7907
+ return (_tui, theme) => ({
7908
+ render: (width) => width < 1 ? [] : (width >= Math.max(adMinColumns, CARD_MIN_COLUMNS) ? renderAdCard(creative, clickUrl, theme, width) : [renderPlainAdLine(creative, clickUrl, theme, width)]).map((line) => ` ${line}`),
7909
+ invalidate() {}
7910
+ });
7911
+ }
5296
7912
  function renderErrorLine(message, theme) {
5297
7913
  return theme.fg("error", message);
5298
7914
  }
@@ -5306,7 +7922,7 @@ function createBannerRenderer(opts = {}) {
5306
7922
  let lastPostedToken;
5307
7923
  const screen = opts.screen ?? {};
5308
7924
  return {
5309
- async render(deps, ctx, config, columnsOverride) {
7925
+ async render(deps, ctx, config) {
5310
7926
  const ad = await fetchAdNext(deps, "banner");
5311
7927
  if (opts.isActive && !opts.isActive())
5312
7928
  return;
@@ -5331,10 +7947,7 @@ function createBannerRenderer(opts = {}) {
5331
7947
  ctx.ui.setWidget(BANNER_WIDGET_ID, undefined);
5332
7948
  opts.onBannerAd?.(undefined);
5333
7949
  };
5334
- const theme = ctx.ui.theme;
5335
- const columns = columnsOverride ?? process.stdout.columns ?? 80;
5336
- const lines = columns >= config.adMinColumns ? renderAdCard(ad.creative, ad.click_url, theme, columns) : [renderPlainAdLine(ad.creative, ad.click_url, theme, columns)];
5337
- ctx.ui.setWidget(BANNER_WIDGET_ID, lines);
7950
+ ctx.ui.setWidget(BANNER_WIDGET_ID, adWidget(ad.creative, ad.click_url, config.adMinColumns));
5338
7951
  opts.onBannerAd?.(ad.click_url);
5339
7952
  if (lastPostedToken !== ad.click_token) {
5340
7953
  lastPostedToken = ad.click_token;
@@ -5358,7 +7971,7 @@ function createInlineRenderer(screen = {}) {
5358
7971
  screen.inline = undefined;
5359
7972
  };
5360
7973
  return {
5361
- async onTurnEnd(deps, ctx, config, columnsOverride) {
7974
+ async onTurnEnd(deps, ctx, config) {
5362
7975
  turnCount += 1;
5363
7976
  clearInline(ctx);
5364
7977
  if (turnCount % config.adInlineTurnFrequency !== 0)
@@ -5373,10 +7986,7 @@ function createInlineRenderer(screen = {}) {
5373
7986
  return;
5374
7987
  if (isGravity && screen.banner)
5375
7988
  screen.clearBanner?.();
5376
- const theme = ctx.ui.theme;
5377
- const columns = columnsOverride ?? process.stdout.columns ?? 80;
5378
- const lines = columns >= config.adMinColumns ? renderAdCard(ad.creative, ad.click_url, theme, columns) : [renderPlainAdLine(ad.creative, ad.click_url, theme, columns)];
5379
- ctx.ui.setWidget(INLINE_WIDGET_ID, lines, { placement: "belowEditor" });
7989
+ ctx.ui.setWidget(INLINE_WIDGET_ID, adWidget(ad.creative, ad.click_url, config.adMinColumns), { placement: "belowEditor" });
5380
7990
  inlineVisible = true;
5381
7991
  screen.inline = isGravity ? "gravity" : "own";
5382
7992
  screen.clearInline = () => clearInline(ctx);
@@ -5557,7 +8167,7 @@ function createAdsExtension(opts) {
5557
8167
  }
5558
8168
 
5559
8169
  // src/pi-launch.ts
5560
- import { dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
8170
+ import { dirname as dirname3, join as join5, resolve as resolve2 } from "node:path";
5561
8171
  import { fileURLToPath as fileURLToPath3 } from "node:url";
5562
8172
 
5563
8173
  // src/provider.ts
@@ -5973,6 +8583,104 @@ function createUsageToolExtension(opts) {
5973
8583
  };
5974
8584
  }
5975
8585
 
8586
+ // src/image-tool.ts
8587
+ import { randomBytes } from "node:crypto";
8588
+ import { mkdir as mkdir2, open } from "node:fs/promises";
8589
+ import { join as join3 } from "node:path";
8590
+ var IMAGE_TOOL_NAME = "generate_image";
8591
+ var MAX_BYTES = 8 * 1024 * 1024;
8592
+ var TIMEOUT_MS = 120000;
8593
+ var EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" };
8594
+ var IMAGE_GUIDELINES = [
8595
+ "Use generate_image only when the user asks for an image, mockup, icon, illustration or other visual asset. Do not call it for diagrams you can write as code, SVG or ASCII.",
8596
+ "Make one call per asset. Put the style, any exact text to render, and the composition in the prompt, and pick aspect_ratio to suit the use (16:9 for banners, 1:1 for icons).",
8597
+ "You cannot see the generated image. The tool saves it to a file and returns the relative path; refer to that path in code, docs or your answer, and tell the user you could not check how it looks.",
8598
+ "Each image uses part of the user's daily allowance, so do not regenerate unless the user asks."
8599
+ ];
8600
+ var ERROR_TEXT = {
8601
+ daily_cap: "The user's free allowance for today is used up. Do not retry. Tell the user they can get credits at freepi.ai/extra-credits, and continue without this tool.",
8602
+ rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
8603
+ rate_limited: "Too many image requests right now. Do not call generate_image again in this turn unless the user asks.",
8604
+ not_configured: "Image generation is not available on this server. Do not call generate_image again in this session.",
8605
+ upstream_error: "The image provider failed. You may retry once.",
8606
+ account_review: "This account is under review, so image generation is disabled. Do not retry; tell the user and continue without it.",
8607
+ content_rejected: "The image provider rejected this prompt. Do not retry the same prompt; tell the user and offer to reword it."
8608
+ };
8609
+ async function post(opts, body, signal) {
8610
+ try {
8611
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
8612
+ const res = await (opts.fetchImpl ?? fetch)(`${opts.baseUrl}/tools/image`, {
8613
+ method: "POST",
8614
+ headers: { Authorization: `Bearer ${await opts.getToken()}`, "Content-Type": "application/json" },
8615
+ body: JSON.stringify(body),
8616
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout
8617
+ });
8618
+ if (res.ok)
8619
+ return { ok: true, data: await res.json() };
8620
+ const j = await res.json().catch(() => ({}));
8621
+ const code = j.error?.code ?? j.code ?? "";
8622
+ const mapped = ERROR_TEXT[code];
8623
+ if (mapped)
8624
+ return { ok: false, text: mapped };
8625
+ return { ok: false, text: `Request failed (HTTP ${res.status}): ${j.error?.message ?? j.message ?? "no message"}` };
8626
+ } catch (e) {
8627
+ if (e instanceof Error && e.name === "TimeoutError")
8628
+ return { ok: false, text: "Image generation timed out after 120 seconds." };
8629
+ return { ok: false, text: `Request failed: ${String(e)}` };
8630
+ }
8631
+ }
8632
+ function slug(s) {
8633
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 40).replace(/-+$/, "") || "image";
8634
+ }
8635
+ var done = (text, details) => ({ content: [{ type: "text", text }], details });
8636
+ var fail = (text) => done(text, { ok: false });
8637
+ function createImageToolExtension(opts) {
8638
+ return {
8639
+ name: "free-pi-image-tool",
8640
+ factory(pi) {
8641
+ pi.registerTool({
8642
+ name: IMAGE_TOOL_NAME,
8643
+ label: "Generate Image",
8644
+ description: "Generate one image from a text prompt and save it as a file under images/ in the project. Returns the file path; you cannot see the image. Use it only when the user asks for an image, mockup, icon or illustration. Each call uses part of the user's daily allowance.",
8645
+ promptSnippet: "Generate an image file from a prompt when the user asks for one (counts against the user's daily allowance)",
8646
+ promptGuidelines: IMAGE_GUIDELINES,
8647
+ parameters: _Object_({
8648
+ prompt: String2({ minLength: 1, maxLength: 1000, description: "What to draw: subject, style, any exact text to render, and composition" }),
8649
+ aspect_ratio: Optional(Union([Literal("1:1"), Literal("16:9"), Literal("9:16"), Literal("4:3"), Literal("3:2")], { description: "Default 1:1" })),
8650
+ name: Optional(String2({ maxLength: 60, description: "Short file name hint, e.g. hero-banner; used only for the saved file's name" }))
8651
+ }),
8652
+ async execute(_id, params, signal) {
8653
+ const r = await post(opts, { prompt: params.prompt, ...params.aspect_ratio ? { aspect_ratio: params.aspect_ratio } : {} }, signal);
8654
+ if (!r.ok)
8655
+ return fail(r.text);
8656
+ const d = r.data;
8657
+ const ext = EXT[d.media_type];
8658
+ if (!ext)
8659
+ return fail(`The server returned an unsupported image type (${d.media_type}). Nothing was saved.`);
8660
+ const buf = Buffer.from(d.image_b64 ?? "", "base64");
8661
+ if (buf.length === 0)
8662
+ return fail("The server returned an empty image. Nothing was saved.");
8663
+ if (buf.length > MAX_BYTES)
8664
+ return fail("The generated image was too large to save (over 8 MB). Nothing was saved.");
8665
+ const rel = `images/${slug(params.name ?? params.prompt)}-${randomBytes(3).toString("hex")}.${ext}`;
8666
+ try {
8667
+ await mkdir2(join3(opts.cwd ?? process.cwd(), "images"), { recursive: true });
8668
+ const fh = await open(join3(opts.cwd ?? process.cwd(), rel), "wx");
8669
+ try {
8670
+ await fh.writeFile(buf);
8671
+ } finally {
8672
+ await fh.close();
8673
+ }
8674
+ } catch (e) {
8675
+ return fail(`Could not save the image: ${String(e)}`);
8676
+ }
8677
+ return done(`Saved image to ${rel} (${ext}, ${buf.length} bytes). You cannot see the image; reference this path in your answer or code, and tell the user you could not check how it looks.`, { ok: true, path: rel, cost_usd: d.cost_usd, model: d.model });
8678
+ }
8679
+ });
8680
+ }
8681
+ };
8682
+ }
8683
+
5976
8684
  // src/web-tools.ts
5977
8685
  var WEB_SEARCH_TOOL_NAME = "web_search";
5978
8686
  var DOCS_LOOKUP_TOOL_NAME = "docs_lookup";
@@ -5987,7 +8695,7 @@ var WEB_SEARCH_GUIDELINES = [
5987
8695
  "Write a specific query the way you would type it into a search engine (include the product name, the version and the exact error text). Read the returned page text before searching again, and do not repeat a query that already returned results. Cite the URLs you relied on in your answer.",
5988
8696
  COST_GUIDELINE
5989
8697
  ];
5990
- var ERROR_TEXT = {
8698
+ var ERROR_TEXT2 = {
5991
8699
  daily_cap: "The user's daily free usage is used up. Do not retry; tell the user and continue without this tool.",
5992
8700
  rolling_cap: "The user's short-term usage limit is reached. Do not retry; continue without this tool.",
5993
8701
  rate_limited: "Too many calls right now. Wait for the current call to finish, and do not call again in this turn unless needed.",
@@ -5995,7 +8703,7 @@ var ERROR_TEXT = {
5995
8703
  not_configured: "This tool is not available on this server. Do not call it again in this session.",
5996
8704
  upstream_error: "The search provider failed. You may retry once."
5997
8705
  };
5998
- async function post(opts, path, body, label, signal) {
8706
+ async function post2(opts, path, body, label, signal) {
5999
8707
  try {
6000
8708
  const timeout = AbortSignal.timeout(30000);
6001
8709
  const res = await (opts.fetchImpl ?? fetch)(`${opts.baseUrl}${path}`, {
@@ -6007,7 +8715,7 @@ async function post(opts, path, body, label, signal) {
6007
8715
  if (res.ok)
6008
8716
  return { ok: true, data: await res.json() };
6009
8717
  const err = await res.json().catch(() => ({}));
6010
- const mapped = ERROR_TEXT[err.code ?? ""];
8718
+ const mapped = ERROR_TEXT2[err.code ?? ""];
6011
8719
  if (mapped)
6012
8720
  return { ok: false, text: typeof mapped === "function" ? mapped(label) : mapped };
6013
8721
  return { ok: false, text: `Request failed (HTTP ${res.status}): ${err.message ?? "no message"}` };
@@ -6017,7 +8725,7 @@ async function post(opts, path, body, label, signal) {
6017
8725
  return { ok: false, text: `Request failed: ${String(e)}` };
6018
8726
  }
6019
8727
  }
6020
- var done = (o) => ({ content: [{ type: "text", text: o.text }], details: o.details });
8728
+ var done2 = (o) => ({ content: [{ type: "text", text: o.text }], details: o.details });
6021
8729
  function createWebToolsExtension(opts) {
6022
8730
  return {
6023
8731
  name: "free-pi-web-tools",
@@ -6033,9 +8741,9 @@ function createWebToolsExtension(opts) {
6033
8741
  num_results: Optional(Integer({ minimum: 1, maximum: 10, description: "1-10, default 5; use 3 for a quick fact, 8-10 for a survey" }))
6034
8742
  }),
6035
8743
  async execute(_id, params, signal) {
6036
- const r = await post(opts, "/tools/web-search", params, "", signal);
8744
+ const r = await post2(opts, "/tools/web-search", params, "", signal);
6037
8745
  if (!r.ok)
6038
- return done({ text: r.text, details: { ok: false } });
8746
+ return done2({ text: r.text, details: { ok: false } });
6039
8747
  const results = r.data.results ?? [];
6040
8748
  const text = results.length ? `Web results for "${params.query}":
6041
8749
 
@@ -6045,7 +8753,7 @@ Published: ${x.published_date}` : ""}
6045
8753
  ${x.text}`).join(`
6046
8754
 
6047
8755
  `) : `No results for "${params.query}". Try a broader or differently worded query.`;
6048
- return done({ text, details: { ok: true, cost_usd: r.data.cost_usd } });
8756
+ return done2({ text, details: { ok: true, cost_usd: r.data.cost_usd } });
6049
8757
  }
6050
8758
  });
6051
8759
  pi.registerTool({
@@ -6060,11 +8768,11 @@ ${x.text}`).join(`
6060
8768
  library_id: Optional(String2({ description: "The library_id printed by an earlier docs_lookup, e.g. /vercel/next.js; skips the name search" }))
6061
8769
  }),
6062
8770
  async execute(_id, params, signal) {
6063
- const r = await post(opts, "/tools/docs", params, params.library, signal);
8771
+ const r = await post2(opts, "/tools/docs", params, params.library, signal);
6064
8772
  if (!r.ok)
6065
- return done({ text: r.text, details: { ok: false } });
8773
+ return done2({ text: r.text, details: { ok: false } });
6066
8774
  const d = r.data;
6067
- return done({ text: `${d.title} (library_id: ${d.library_id})
8775
+ return done2({ text: `${d.title} (library_id: ${d.library_id})
6068
8776
 
6069
8777
  ${d.docs}`, details: { ok: true, cost_usd: d.cost_usd } });
6070
8778
  }
@@ -6229,7 +8937,7 @@ function createDocsToolExtension() {
6229
8937
  // src/todo-view.ts
6230
8938
  var PLAIN_STYLE = { bold: (s) => s, dim: (s) => s, accent: (s) => s, error: (s) => s };
6231
8939
  var GAP = " ";
6232
- function truncate2(text, max) {
8940
+ function truncate(text, max) {
6233
8941
  if (max <= 0)
6234
8942
  return "";
6235
8943
  if ([...text].length <= max)
@@ -6255,19 +8963,19 @@ function widgetLines(todos, width, st = PLAIN_STYLE) {
6255
8963
  ].join(GAP)
6256
8964
  ];
6257
8965
  }
6258
- const lines = [st.bold(truncate2(header, width))];
8966
+ const lines = [st.bold(truncate(header, width))];
6259
8967
  const open = todos.filter((t) => !t.done);
6260
8968
  if (open.length === 0) {
6261
- lines.push(st.dim(truncate2("✓ All done", width)));
8969
+ lines.push(st.dim(truncate("✓ All done", width)));
6262
8970
  return lines;
6263
8971
  }
6264
8972
  open.slice(0, 3).forEach((t, i) => {
6265
- const line = truncate2(`${i === 0 ? "▸" : "○"} ${t.text}`, width);
8973
+ const line = truncate(`${i === 0 ? "▸" : "○"} ${t.text}`, width);
6266
8974
  lines.push(i === 0 ? st.accent(st.bold(line)) : st.dim(line));
6267
8975
  });
6268
8976
  const more = open.length - 3;
6269
8977
  if (more > 0)
6270
- lines.push(st.dim(truncate2(`+${more} more · /todos for all`, width)));
8978
+ lines.push(st.dim(truncate(`+${more} more · /todos for all`, width)));
6271
8979
  return lines;
6272
8980
  }
6273
8981
  function resultLines(d, st = PLAIN_STYLE) {
@@ -6479,7 +9187,7 @@ function createTodoToolExtension(options = {}) {
6479
9187
 
6480
9188
  // src/tool-aliases.ts
6481
9189
  import { homedir as homedir2 } from "node:os";
6482
- import { join as join3 } from "node:path";
9190
+ import { join as join4 } from "node:path";
6483
9191
  import { fileURLToPath as fileURLToPath2 } from "node:url";
6484
9192
  import {
6485
9193
  createBashToolDefinition,
@@ -6505,7 +9213,7 @@ function normalizeShellPath(input, platform = process.platform, home = homedir2(
6505
9213
  if (p === "~")
6506
9214
  return home;
6507
9215
  if (p.startsWith("~/") || platform === "win32" && p.startsWith("~\\"))
6508
- return join3(home, p.slice(2));
9216
+ return join4(home, p.slice(2));
6509
9217
  if (/^file:\/\//.test(p))
6510
9218
  return fileURLToPath2(p);
6511
9219
  return p;
@@ -6537,6 +9245,12 @@ function createToolAliasesExtension() {
6537
9245
 
6538
9246
  // src/error-notice.ts
6539
9247
  var NOTICE_DEDUPE_MS = 15000;
9248
+ function optionalNumber(value) {
9249
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
9250
+ }
9251
+ function optionalString(value) {
9252
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
9253
+ }
6540
9254
  function parseErrorEnvelope(errorMessage) {
6541
9255
  if (typeof errorMessage !== "string")
6542
9256
  return;
@@ -6549,14 +9263,53 @@ function parseErrorEnvelope(errorMessage) {
6549
9263
  const code = body.code ?? body.error?.code;
6550
9264
  if (typeof message !== "string" || message.trim() === "")
6551
9265
  return;
6552
- return { status: Number(m[1]), code: typeof code === "string" ? code : "unknown", message };
9266
+ const parsed = {
9267
+ status: Number(m[1]),
9268
+ code: typeof code === "string" ? code : "unknown",
9269
+ message
9270
+ };
9271
+ const limit = optionalString(body.limit);
9272
+ const retryAfter = optionalNumber(body.retry_after_seconds);
9273
+ const clearsAt = optionalString(body.clears_at);
9274
+ const remaining = optionalNumber(body.remaining_credits_today);
9275
+ const allowance = optionalNumber(body.allowance_credits);
9276
+ if (limit)
9277
+ parsed.limit = limit;
9278
+ if (retryAfter !== undefined)
9279
+ parsed.retry_after_seconds = retryAfter;
9280
+ if (clearsAt)
9281
+ parsed.clears_at = clearsAt;
9282
+ if (remaining !== undefined)
9283
+ parsed.remaining_credits_today = remaining;
9284
+ if (allowance !== undefined)
9285
+ parsed.allowance_credits = allowance;
9286
+ const ceiling = optionalNumber(body.hourly_ceiling);
9287
+ if (body.lane === "slow")
9288
+ parsed.lane = "slow";
9289
+ if (ceiling !== undefined)
9290
+ parsed.hourly_ceiling = ceiling;
9291
+ return parsed;
6553
9292
  } catch {
6554
9293
  return;
6555
9294
  }
6556
9295
  }
9296
+ function formatLimitEnvelope(env, opts) {
9297
+ if (env.code === "concurrent_session" || typeof env.remaining_credits_today !== "number")
9298
+ return env.message;
9299
+ return formatLimitNotice({
9300
+ limit: env.limit ?? env.code,
9301
+ retry_after_seconds: env.retry_after_seconds,
9302
+ clears_at: env.clears_at,
9303
+ remaining_credits_today: env.remaining_credits_today,
9304
+ allowance_credits: env.allowance_credits,
9305
+ lane: env.lane,
9306
+ hourly_ceiling: env.hourly_ceiling
9307
+ }, { localTime: true, timeZone: opts?.timeZone });
9308
+ }
6557
9309
  function createErrorNoticeExtension(opts = {}) {
6558
9310
  const lastAt = new Map;
6559
9311
  const now = opts.now ?? Date.now;
9312
+ const timeZone = opts.timeZone;
6560
9313
  return {
6561
9314
  name: "free-pi-error-notice",
6562
9315
  factory(pi) {
@@ -6571,7 +9324,7 @@ function createErrorNoticeExtension(opts = {}) {
6571
9324
  if (t - (lastAt.get(env.code) ?? -Infinity) < NOTICE_DEDUPE_MS)
6572
9325
  return;
6573
9326
  lastAt.set(env.code, t);
6574
- ctx.ui.notify(env.message, env.status >= 500 ? "error" : "warning");
9327
+ ctx.ui.notify(formatLimitEnvelope(env, { timeZone }), env.status >= 500 ? "error" : "warning");
6575
9328
  });
6576
9329
  }
6577
9330
  };
@@ -6705,6 +9458,20 @@ function installFooterRightAlign(mode) {
6705
9458
 
6706
9459
  // src/changelog.ts
6707
9460
  var CHANGELOG_HIGHLIGHTS = [
9461
+ {
9462
+ version: "0.4.8",
9463
+ highlights: [
9464
+ "The agent can now make images: ask for a mockup, icon or illustration and generate_image saves it into your project's images/ folder. Each image counts toward your daily allowance.",
9465
+ "Clearer limit messages: you now see when a limit clears and how many credits you have left today."
9466
+ ]
9467
+ },
9468
+ {
9469
+ version: "0.4.7",
9470
+ highlights: [
9471
+ "free-pi now updates itself when a new version is required: no more running npx free-pi-cli@latest.",
9472
+ "The ad box redraws at your terminal's width after a resize, and never overflows with wide characters."
9473
+ ]
9474
+ },
6708
9475
  {
6709
9476
  version: "0.4.6",
6710
9477
  highlights: [
@@ -7062,12 +9829,12 @@ function updateBannerLines(theme, latest, width) {
7062
9829
  return [
7063
9830
  "",
7064
9831
  border,
7065
- theme.bold(theme.fg("warning", truncate3(headline, inner))),
7066
- theme.fg("dim", truncate3(detail, inner)),
9832
+ theme.bold(theme.fg("warning", truncate2(headline, inner))),
9833
+ theme.fg("dim", truncate2(detail, inner)),
7067
9834
  border
7068
9835
  ];
7069
9836
  }
7070
- function truncate3(text, maxWidth) {
9837
+ function truncate2(text, maxWidth) {
7071
9838
  if (maxWidth <= 0)
7072
9839
  return "";
7073
9840
  if (text.length <= maxWidth)
@@ -7078,7 +9845,7 @@ function truncate3(text, maxWidth) {
7078
9845
  }
7079
9846
  function headerLines(theme, modelName, expanded, width = Number.POSITIVE_INFINITY, updateLatest) {
7080
9847
  const inner = width - 1;
7081
- const fit = (plain, styled) => plain.length <= inner ? styled() : theme.fg("dim", truncate3(plain, inner));
9848
+ const fit = (plain, styled) => plain.length <= inner ? styled() : theme.fg("dim", truncate2(plain, inner));
7082
9849
  const titleRest = ` · ${modelName} · ctrl+o for help`;
7083
9850
  const title = fit(`free-pi${titleRest}`, () => `${theme.bold(theme.fg("accent", "free-pi"))}${theme.fg("dim", titleRest)}`);
7084
9851
  const commandLines = COMMANDS.map(({ name, description }) => {
@@ -7293,6 +10060,7 @@ var ALLOWED_TOOL_NAMES = [
7293
10060
  DOCS_TOOL_NAME,
7294
10061
  WEB_SEARCH_TOOL_NAME,
7295
10062
  DOCS_LOOKUP_TOOL_NAME,
10063
+ IMAGE_TOOL_NAME,
7296
10064
  TODO_TOOL_NAME,
7297
10065
  "codemode",
7298
10066
  "tool_search"
@@ -7355,6 +10123,10 @@ function buildRuntimeOptions(opts, sessionId) {
7355
10123
  baseUrl: opts.baseUrl,
7356
10124
  getToken: () => opts.jwt
7357
10125
  });
10126
+ const imageToolExtension = createImageToolExtension({
10127
+ baseUrl: opts.baseUrl,
10128
+ getToken: () => opts.jwt
10129
+ });
7358
10130
  const errorNoticeExtension = createErrorNoticeExtension();
7359
10131
  const toolGuardExtension = createToolGuardExtension({
7360
10132
  baseUrl: opts.baseUrl,
@@ -7383,6 +10155,7 @@ function buildRuntimeOptions(opts, sessionId) {
7383
10155
  buyToolExtension,
7384
10156
  docsToolExtension,
7385
10157
  webToolsExtension,
10158
+ imageToolExtension,
7386
10159
  errorNoticeExtension,
7387
10160
  toolGuardExtension,
7388
10161
  commandsExtension,
@@ -7408,7 +10181,7 @@ function buildRuntimeOptions(opts, sessionId) {
7408
10181
  function getSessionDir(cwd, agentDir) {
7409
10182
  const resolvedCwd = resolve2(cwd);
7410
10183
  const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
7411
- return join4(resolve2(agentDir), "sessions", safePath);
10184
+ return join5(resolve2(agentDir), "sessions", safePath);
7412
10185
  }
7413
10186
  async function createSessionManager(cwd, sessionDir, sessionId, api = SessionManager) {
7414
10187
  if (sessionId) {
@@ -7550,6 +10323,62 @@ function createRealSpawn(io = { platform: process.platform, spawnSyncImpl: spawn
7550
10323
  };
7551
10324
  }
7552
10325
 
10326
+ // src/relaunch.ts
10327
+ import { mkdtempSync, existsSync as existsSync2, rmSync } from "node:fs";
10328
+ import { constants as osConstants, tmpdir } from "node:os";
10329
+ import { join as join6 } from "node:path";
10330
+ var SEMVER = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
10331
+ var WIN_SAFE_ARG = /^[A-Za-z0-9._:=\/@+,-]+$/;
10332
+ async function relaunchViaNpx(latest, deps) {
10333
+ const { env } = deps;
10334
+ if ("FREEPI_NO_AUTO_UPDATE" in env || !deps.autoUpdateEnabled())
10335
+ return;
10336
+ if (env.FREEPI_AUTO_UPDATED)
10337
+ return;
10338
+ const win = deps.platform === "win32";
10339
+ if (win && !deps.argv.every((a) => WIN_SAFE_ARG.test(a)))
10340
+ return;
10341
+ const target = latest && SEMVER.test(latest) ? latest : "latest";
10342
+ const readyDir = mkdtempSync(join6(tmpdir(), "free-pi-relaunch-"));
10343
+ const readyFile = join6(readyDir, "started");
10344
+ try {
10345
+ deps.log(`Updating free-pi to ${target}…`);
10346
+ return await new Promise((resolve) => {
10347
+ let child;
10348
+ try {
10349
+ child = deps.spawn(win ? "npx.cmd" : "npx", ["--yes", `free-pi-cli@${target}`, ...deps.argv], {
10350
+ stdio: "inherit",
10351
+ env: { ...env, FREEPI_AUTO_UPDATED: target, FREEPI_RELAUNCH_READY: readyFile },
10352
+ shell: win
10353
+ });
10354
+ } catch {
10355
+ resolve(undefined);
10356
+ return;
10357
+ }
10358
+ const handlers = win ? [] : [
10359
+ ["SIGINT", () => {}],
10360
+ ["SIGTERM", () => void child.kill("SIGTERM")],
10361
+ ["SIGHUP", () => void child.kill("SIGHUP")]
10362
+ ];
10363
+ for (const [sig, cb] of handlers)
10364
+ deps.proc.on(sig, cb);
10365
+ const done = (code) => {
10366
+ for (const [sig, cb] of handlers)
10367
+ deps.proc.off(sig, cb);
10368
+ resolve(code);
10369
+ };
10370
+ child.on("error", () => done(undefined));
10371
+ child.on("exit", (code, signal) => {
10372
+ const exitCode = code ?? 128 + (signal ? osConstants.signals[signal] ?? 0 : 0);
10373
+ const cancelled = signal === "SIGINT" || signal === "SIGTERM" || signal === "SIGHUP" || exitCode === 130 || exitCode === 143 || exitCode === 129;
10374
+ done(exitCode !== 0 && !cancelled && !existsSync2(readyFile) ? undefined : exitCode);
10375
+ });
10376
+ });
10377
+ } finally {
10378
+ rmSync(readyDir, { recursive: true, force: true });
10379
+ }
10380
+ }
10381
+
7553
10382
  // src/auth-flow.ts
7554
10383
  class UnauthorizedError extends Error {
7555
10384
  constructor() {
@@ -7680,12 +10509,12 @@ ${INTRO_TEXT}
7680
10509
  }
7681
10510
 
7682
10511
  // src/whats-new.ts
7683
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
10512
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
7684
10513
  import { dirname as dirname4 } from "node:path";
7685
10514
  function maybeWhatsNew(cliVersion, agentDir) {
7686
10515
  try {
7687
10516
  const path = getLastSeenVersionPath(agentDir);
7688
- const lastSeen = existsSync2(path) ? readFileSync2(path, "utf-8").trim() : undefined;
10517
+ const lastSeen = existsSync3(path) ? readFileSync2(path, "utf-8").trim() : undefined;
7689
10518
  writeLastSeen(path, cliVersion);
7690
10519
  if (lastSeen === undefined)
7691
10520
  return;
@@ -7781,6 +10610,9 @@ async function run(deps, argv = process.argv) {
7781
10610
  if (outcome === "updated-exit")
7782
10611
  return 0;
7783
10612
  if (outcome === "blocked") {
10613
+ const relaunched = await deps.relaunchLatest?.(versionCheck.latest);
10614
+ if (relaunched !== undefined)
10615
+ return relaunched;
7784
10616
  deps.log("free-pi-cli is below the required minimum version; update with: npx free-pi-cli@latest");
7785
10617
  return 1;
7786
10618
  }
@@ -7889,6 +10721,11 @@ function resolveCliRealpath() {
7889
10721
  }
7890
10722
  }
7891
10723
  async function main() {
10724
+ if (process.env.FREEPI_RELAUNCH_READY) {
10725
+ try {
10726
+ writeFileSync2(process.env.FREEPI_RELAUNCH_READY, "");
10727
+ } catch {}
10728
+ }
7892
10729
  const command = parseCliArgs(process.argv.slice(2));
7893
10730
  if (command.kind === "version") {
7894
10731
  console.log(versionLine());
@@ -7933,7 +10770,16 @@ ${HELP_TEXT}`);
7933
10770
  launchPi,
7934
10771
  log: (message) => console.log(message),
7935
10772
  checkClientVersion,
7936
- startGravityPixel: (jwt) => startGravityPixel(jwt, join5(dirname5(agentDir), "gravity")),
10773
+ startGravityPixel: (jwt) => startGravityPixel(jwt, join7(dirname5(agentDir), "gravity")),
10774
+ relaunchLatest: (latest) => relaunchViaNpx(latest, {
10775
+ env: process.env,
10776
+ argv: process.argv.slice(2),
10777
+ platform: process.platform,
10778
+ autoUpdateEnabled: () => readAutoUpdate(getConfigPath()),
10779
+ spawn: (cmd, args, opts) => spawn2(cmd, args, opts),
10780
+ proc: process,
10781
+ log: (message) => console.log(message)
10782
+ }),
7937
10783
  maybeSelfUpdate: (action, latest) => maybeSelfUpdate(action, latest, {
7938
10784
  env: process.env,
7939
10785
  autoUpdateEnabled: () => readAutoUpdate(getConfigPath()),