diff --git a/.agents/skills/add-model/SKILL.md b/.agents/skills/add-model/SKILL.md index f97c966e1f3..e46f22c43e5 100644 --- a/.agents/skills/add-model/SKILL.md +++ b/.agents/skills/add-model/SKILL.md @@ -143,12 +143,12 @@ If anything matches, run the affected provider tests and update assertions as ne ### New API behavior is NOT data-driven -The Consumption Matrix (Step 2) tells you which capability *flags* are honored by existing provider code. But if the new model needs **net-new** request handling that the provider doesn't implement yet — a new beta header (e.g. Anthropic's `anthropic-beta` structured-outputs header in `anthropic/index.ts`), a new thinking/reasoning encoding, a Responses-API quirk — you must edit `apps/sim/providers//core.ts` / `index.ts`. Setting a flag whose behavior isn't implemented is a silent no-op. +The Consumption Matrix (Step 2) tells you which capability *flags* are honored by existing provider code. But if the new model needs **net-new** request handling that the provider doesn't implement yet — a new beta header (e.g. Anthropic's `anthropic-beta` structured-outputs header in `anthropic/index.ts`), a new thinking/reasoning encoding, a Responses-API quirk — you must edit `apps/sim/providers//core.ts` / `index.ts`. Setting a flag whose behavior isn't implemented is a silent no-op. When you do edit provider code, reuse the shared helpers rather than hand-rolling: streaming responses are assembled via `createStreamingExecution` (`@/providers/streaming-execution`) and tool schemas via `adaptOpenAIChatToolSchema` / `adaptAnthropicToolSchema` (`@/providers/tool-schema-adapter`). ### Wrong family entirely? - **Embedding or rerank model** → it does NOT go in the `models[]` array. Use `EMBEDDING_MODEL_PRICING` / `RERANK_MODEL_PRICING` in `models.ts` instead. -- **Brand-new provider** (not just a new model under an existing one) → much larger surface: add the id to `ProviderId` in `providers/types.ts`, a registry entry in `providers/registry.ts`, a provider implementation under `providers//`, an icon in `components/icons.tsx`, and the `PROVIDER_DEFINITIONS` block. That is beyond this skill — tell the user. +- **Brand-new provider** (not just a new model under an existing one) → much larger surface: add the id to `ProviderId` in `providers/types.ts`, a registry entry in `providers/registry.ts`, a provider implementation under `providers//` (assemble streaming responses with `createStreamingExecution` and wrap tool schemas with the `@/providers/tool-schema-adapter` helpers), an icon in `components/icons.tsx`, and the `PROVIDER_DEFINITIONS` block. That is beyond this skill — tell the user. ## Step 5: Write, lint diff --git a/apps/docs/components/icons.tsx b/apps/docs/components/icons.tsx index 8ea1529b1e8..2d6b6eb2c03 100644 --- a/apps/docs/components/icons.tsx +++ b/apps/docs/components/icons.tsx @@ -1958,6 +1958,17 @@ export function WhatsAppIcon(props: SVGProps) { ) } +export function SquareIcon(props: SVGProps) { + return ( + + + + ) +} + export function StripeIcon(props: SVGProps) { return ( ) { ) } +export function ContextDevIcon(props: SVGProps) { + return ( + + + + ) +} + export function ConvexIcon(props: SVGProps) { return ( = { codepipeline: CodePipelineIcon, confluence: ConfluenceIcon, confluence_v2: ConfluenceIcon, + context_dev: ContextDevIcon, convex: ConvexIcon, crowdstrike: CrowdStrikeIcon, cursor: CursorIcon, @@ -437,6 +440,7 @@ export const blockTypeToIconMap: Record = { slack: SlackIcon, smtp: SmtpIcon, sqs: SQSIcon, + square: SquareIcon, ssh: SshIcon, stagehand: StagehandIcon, stripe: StripeIcon, diff --git a/apps/docs/content/docs/en/integrations/context_dev.mdx b/apps/docs/content/docs/en/integrations/context_dev.mdx new file mode 100644 index 00000000000..1da78894369 --- /dev/null +++ b/apps/docs/content/docs/en/integrations/context_dev.mdx @@ -0,0 +1,678 @@ +--- +title: Context.dev +description: Scrape, crawl, search, extract, and enrich web and brand data +--- + +import { BlockInfoCard } from "@/components/ui/block-info-card" + + + +## Usage Instructions + +Integrate Context.dev into the workflow. Scrape pages to markdown or HTML, capture screenshots, list images, crawl entire sites, map sitemaps, search the web, extract structured data and products, pull design systems, classify industries, and retrieve brand assets by domain, name, email, ticker, or transaction — all from one API. + + + +## Actions + +### `context_dev_scrape_markdown` + +Scrape any URL and return clean, LLM-ready markdown content. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The full URL to scrape \(must include http:// or https://\) | +| `useMainContentOnly` | boolean | No | Return only main content, excluding headers, footers, and navigation | +| `includeLinks` | boolean | No | Preserve hyperlinks in the markdown output \(default: true\) | +| `includeImages` | boolean | No | Include image references in the markdown output \(default: false\) | +| `includeFrames` | boolean | No | Render iframe contents inline \(default: false\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 86400000\) | +| `waitForMs` | number | No | Browser wait time after page load in milliseconds \(0-30000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `markdown` | string | Page content as clean markdown | +| `url` | string | The scraped URL | + +### `context_dev_scrape_html` + +Scrape any URL and return the raw HTML content of the page. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The full URL to scrape \(must include http:// or https://\) | +| `useMainContentOnly` | boolean | No | Return only main content, excluding headers, footers, and navigation | +| `includeFrames` | boolean | No | Render iframe contents inline into the returned HTML \(default: false\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 86400000\) | +| `waitForMs` | number | No | Browser wait time after page load in milliseconds \(0-30000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `html` | string | Raw HTML content of the page | +| `url` | string | The scraped URL | +| `type` | string | Detected content type \(html, xml, json, text, csv, markdown, svg, pdf\) | + +### `context_dev_scrape_images` + +Discover every image asset on a page, with optional dimension and type enrichment. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The full URL to scrape images from \(must include http:// or https://\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 86400000\) | +| `waitForMs` | number | No | Browser wait time after page load in milliseconds \(0-30000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `enrichResolution` | boolean | No | Measure image dimensions \(enables 5-credit enrichment\) | +| `enrichHostedUrl` | boolean | No | Host images on a CDN and return their URL and MIME type \(enables enrichment\) | +| `enrichClassification` | boolean | No | Classify each image by visual asset type \(enables enrichment\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `success` | boolean | Whether the scrape succeeded | +| `images` | array | Discovered image assets with source, element, type, and optional enrichment | +| ↳ `src` | string | Image source URL or data | +| ↳ `element` | string | Source element \(img, svg, link, source, video, css, object, meta, background\) | +| ↳ `type` | string | Image representation \(url, html, base64\) | +| ↳ `alt` | string | Alt text | +| ↳ `enrichment` | json | Optional enrichment \(width, height, mimetype, url, type\) when requested | +| `url` | string | The scraped URL | + +### `context_dev_screenshot` + +Capture a screenshot of any web page and store it as a downloadable image file. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The full URL to capture \(must include http:// or https://\) | +| `fullScreenshot` | boolean | No | Capture the full scrollable page instead of just the viewport \(default: false\) | +| `handleCookiePopup` | boolean | No | Attempt to dismiss cookie banners before capturing \(default: false\) | +| `viewportWidth` | number | No | Viewport width in pixels \(240-7680, default: 1920\) | +| `viewportHeight` | number | No | Viewport height in pixels \(240-4320, default: 1080\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 86400000\) | +| `waitForMs` | number | No | Post-load delay before capturing in milliseconds \(0-30000, default: 3000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `file` | file | Stored screenshot image file | +| `screenshotUrl` | string | Public URL of the captured screenshot | +| `screenshotType` | string | Screenshot type \(viewport or fullPage\) | +| `domain` | string | Domain that was captured | +| `width` | number | Screenshot width in pixels | +| `height` | number | Screenshot height in pixels | + +### `context_dev_crawl` + +Crawl an entire website and return each discovered page as clean markdown. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The starting URL to crawl \(must include http:// or https://\) | +| `maxPages` | number | No | Maximum number of pages to crawl \(1-500, default: 100\) | +| `maxDepth` | number | No | Maximum link depth from the starting URL \(0 = start page only\) | +| `urlRegex` | string | No | Regex pattern to filter which URLs are crawled | +| `includeLinks` | boolean | No | Preserve hyperlinks in the markdown output \(default: true\) | +| `includeImages` | boolean | No | Include image references in the markdown output \(default: false\) | +| `useMainContentOnly` | boolean | No | Strip headers, footers, and sidebars from each page \(default: false\) | +| `followSubdomains` | boolean | No | Follow links to subdomains of the starting domain \(default: false\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 86400000\) | +| `waitForMs` | number | No | Browser wait time after page load in milliseconds \(0-30000\) | +| `stopAfterMs` | number | No | Soft crawl time budget in milliseconds \(10000-110000, default: 80000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `results` | array | Crawled pages with markdown content and per-page metadata | +| ↳ `markdown` | string | Page content as markdown | +| ↳ `metadata` | json | Page metadata \(url, title, crawlDepth, statusCode\) | +| `metadata` | object | Crawl summary \(numUrls, maxCrawlDepth, numSucceeded, numFailed, numSkipped\) | + +### `context_dev_map` + +Build a sitemap of a domain and return every discovered page URL. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to build a sitemap for \(e.g., "example.com"\) | +| `maxLinks` | number | No | Maximum number of URLs to return \(1-100000, default: 10000\) | +| `urlRegex` | string | No | RE2-compatible regex to filter URLs \(max 256 chars\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `domain` | string | The domain that was mapped | +| `urls` | array | All page URLs discovered from the sitemap | +| `meta` | object | Sitemap discovery stats \(sitemapsDiscovered, sitemapsFetched, errors\) | + +### `context_dev_search` + +Search the web with natural language and optionally scrape results to markdown. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `query` | string | Yes | The natural language search query \(1-500 characters\) | +| `includeDomains` | array | No | Only return results from these domains | +| `excludeDomains` | array | No | Exclude results from these domains | +| `freshness` | string | No | Recency filter \(last_24_hours, last_week, last_month, last_year\) | +| `queryFanout` | boolean | No | Expand the query into parallel variants for broader coverage | +| `markdownEnabled` | boolean | No | Scrape each result page to markdown \(default: false\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `results` | array | Search results with url, title, description, relevance, and optional markdown | +| ↳ `url` | string | Result page URL | +| ↳ `title` | string | Result page title | +| ↳ `description` | string | Result snippet/description | +| ↳ `relevance` | string | Relevance rating \(high, medium, low\) | +| ↳ `markdown` | json | Scraped markdown for the result \(when markdown scraping is enabled\) | +| `query` | string | The query that was searched | + +### `context_dev_extract` + +Crawl a website and extract structured data matching a provided JSON schema. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The starting website URL \(must include http:// or https://\) | +| `schema` | json | Yes | JSON Schema describing the structure of the data to extract | +| `instructions` | string | No | Optional extraction guidance for link prioritization \(max 2000 chars\) | +| `factCheck` | boolean | No | Require extracted values to be grounded in page facts \(default: false\) | +| `followSubdomains` | boolean | No | Follow links on subdomains of the starting domain \(default: false\) | +| `maxPages` | number | No | Maximum number of pages to analyze \(1-50, default: 5\) | +| `maxDepth` | number | No | Maximum link depth from the starting URL | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 604800000\) | +| `stopAfterMs` | number | No | Soft crawl time budget in milliseconds \(10000-110000, default: 80000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Extraction status | +| `url` | string | The starting URL that was crawled | +| `urlsAnalyzed` | array | URLs that were analyzed during extraction | +| `data` | json | Structured data matching the requested schema | +| `metadata` | object | Crawl summary \(numUrls, maxCrawlDepth, numSucceeded, numFailed, numSkipped\) | + +### `context_dev_extract_product` + +Detect and extract structured product details from a single product page URL. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `url` | string | Yes | The product page URL \(must include http:// or https://\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 604800000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `isProductPage` | boolean | Whether the URL is a product page | +| `platform` | string | Detected platform \(amazon, tiktok_shop, etsy, generic\) | +| `product` | object | Extracted product details | +| ↳ `name` | string | Product name | +| ↳ `description` | string | Product description | +| ↳ `price` | number | Product price | +| ↳ `currency` | string | Price currency | +| ↳ `billing_frequency` | string | Billing frequency \(monthly, yearly, one_time, usage_based\) | +| ↳ `pricing_model` | string | Pricing model \(per_seat, flat, tiered, freemium, custom\) | +| ↳ `url` | string | Product URL | +| ↳ `category` | string | Product category | +| ↳ `features` | json | Product features | +| ↳ `target_audience` | json | Target audience | +| ↳ `tags` | json | Product tags | +| ↳ `image_url` | string | Primary product image URL | +| ↳ `images` | json | Product image URLs | +| ↳ `sku` | string | Product SKU | + +### `context_dev_extract_products` + +Extract the product catalog from a brand + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to extract products from \(e.g., "example.com"\) | +| `maxProducts` | number | No | Maximum number of products to extract \(1-12\) | +| `maxAgeMs` | number | No | Cache duration in milliseconds \(0-2592000000, default: 604800000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `products` | array | Extracted products with pricing, features, and metadata | +| ↳ `name` | string | Product name | +| ↳ `description` | string | Product description | +| ↳ `price` | number | Product price | +| ↳ `currency` | string | Price currency | +| ↳ `billing_frequency` | string | Billing frequency \(monthly, yearly, one_time, usage_based\) | +| ↳ `pricing_model` | string | Pricing model \(per_seat, flat, tiered, freemium, custom\) | +| ↳ `url` | string | Product URL | +| ↳ `category` | string | Product category | +| ↳ `features` | json | Product features | +| ↳ `target_audience` | json | Target audience | +| ↳ `tags` | json | Product tags | +| ↳ `image_url` | string | Primary product image URL | +| ↳ `images` | json | Product image URLs | +| ↳ `sku` | string | Product SKU | + +### `context_dev_scrape_fonts` + +Extract the font families, usage stats, and font files used by a domain. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to extract fonts from \(e.g., "example.com"\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Extraction status | +| `domain` | string | The domain that was analyzed | +| `fonts` | array | Fonts with usage statistics and fallbacks | +| ↳ `font` | string | Font family name | +| ↳ `uses` | json | Where the font is used | +| ↳ `fallbacks` | json | Fallback font families | +| ↳ `num_elements` | number | Number of elements using the font | +| ↳ `num_words` | number | Number of words rendered in the font | +| ↳ `percent_words` | number | Percent of words using the font | +| ↳ `percent_elements` | number | Percent of elements using the font | +| `fontLinks` | json | Font family download links keyed by font name \(type, files, category\) | + +### `context_dev_scrape_styleguide` + +Extract a domain + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to extract the styleguide from \(e.g., "example.com"\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Extraction status | +| `domain` | string | The domain that was analyzed | +| `styleguide` | json | Design system: mode, colors, typography, elementSpacing, shadows, fontLinks, components | + +### `context_dev_classify_naics` + +Classify a brand into NAICS industry codes from its domain or company name. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `input` | string | Yes | Brand domain or company name to classify \(e.g., "stripe.com" or "Stripe"\) | +| `minResults` | number | No | Minimum number of codes to return \(1-10, default: 1\) | +| `maxResults` | number | No | Maximum number of codes to return \(1-10, default: 5\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Classification status | +| `domain` | string | Resolved domain | +| `type` | string | Input type that was resolved | +| `codes` | array | Matched NAICS codes with name and confidence | +| ↳ `code` | string | Industry code | +| ↳ `name` | string | Industry name | +| ↳ `confidence` | string | Match confidence \(high, medium, low\) | + +### `context_dev_classify_sic` + +Classify a brand into SIC industry codes from its domain or company name. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `input` | string | Yes | Brand domain or company name to classify \(e.g., "stripe.com" or "Stripe"\) | +| `type` | string | No | SIC taxonomy version: "original_sic" \(default\) or "latest_sec" | +| `minResults` | number | No | Minimum number of codes to return \(1-10, default: 1\) | +| `maxResults` | number | No | Maximum number of codes to return \(1-10, default: 5\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Classification status | +| `domain` | string | Resolved domain | +| `type` | string | Input type that was resolved | +| `classification` | string | SIC taxonomy version used \(original_sic or latest_sec\) | +| `codes` | array | Matched SIC codes with name, confidence, and group metadata | +| ↳ `code` | string | Industry code | +| ↳ `name` | string | Industry name | +| ↳ `confidence` | string | Match confidence \(high, medium, low\) | +| ↳ `majorGroup` | string | Major group code \(original_sic only\) | +| ↳ `majorGroupName` | string | Major group name \(original_sic only\) | +| ↳ `office` | string | SEC office \(latest_sec only\) | + +### `context_dev_get_brand` + +Retrieve brand data for a domain: logos, colors, backdrops, socials, address, and industry. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to retrieve brand data for \(e.g., "airbnb.com"\) | +| `forceLanguage` | string | No | Override the detected language with a supported language code | +| `maxSpeed` | boolean | No | Skip time-consuming operations for a faster response \(default: false\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Retrieval status | +| `brand` | object | Brand data object | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `description` | string | Brand description | +| ↳ `slogan` | string | Brand slogan | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | +| ↳ `socials` | json | Social media profiles \(type and url\) | +| ↳ `address` | json | Brand address | +| ↳ `stock` | json | Stock info \(ticker and exchange\) | +| ↳ `is_nsfw` | boolean | Whether the brand contains adult content | +| ↳ `email` | string | Brand contact email | +| ↳ `phone` | string | Brand contact phone | +| ↳ `industries` | json | Industry taxonomy \(eic industry/subindustry pairs\) | +| ↳ `links` | json | Key brand links \(careers, privacy, terms, blog, pricing\) | +| ↳ `primary_language` | string | Primary language of the brand site | + +### `context_dev_get_brand_by_name` + +Retrieve brand data by company name: logos, colors, socials, address, and industry. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `name` | string | Yes | Company name to retrieve brand data for \(3-30 chars, e.g., "Apple Inc"\) | +| `countryGl` | string | No | ISO 2-letter country code to prioritize \(e.g., "us"\) | +| `forceLanguage` | string | No | Override the detected language with a supported language code | +| `maxSpeed` | boolean | No | Skip time-consuming operations for a faster response \(default: false\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Retrieval status | +| `brand` | object | Brand data object | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `description` | string | Brand description | +| ↳ `slogan` | string | Brand slogan | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | +| ↳ `socials` | json | Social media profiles \(type and url\) | +| ↳ `address` | json | Brand address | +| ↳ `stock` | json | Stock info \(ticker and exchange\) | +| ↳ `is_nsfw` | boolean | Whether the brand contains adult content | +| ↳ `email` | string | Brand contact email | +| ↳ `phone` | string | Brand contact phone | +| ↳ `industries` | json | Industry taxonomy \(eic industry/subindustry pairs\) | +| ↳ `links` | json | Key brand links \(careers, privacy, terms, blog, pricing\) | +| ↳ `primary_language` | string | Primary language of the brand site | + +### `context_dev_get_brand_by_email` + +Retrieve brand data from a work email address. Free/disposable emails are rejected (422). + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `email` | string | Yes | Work email address; the domain is extracted \(free providers are rejected\) | +| `forceLanguage` | string | No | Override the detected language with a supported language code | +| `maxSpeed` | boolean | No | Skip time-consuming operations for a faster response \(default: false\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Retrieval status | +| `brand` | object | Brand data object | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `description` | string | Brand description | +| ↳ `slogan` | string | Brand slogan | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | +| ↳ `socials` | json | Social media profiles \(type and url\) | +| ↳ `address` | json | Brand address | +| ↳ `stock` | json | Stock info \(ticker and exchange\) | +| ↳ `is_nsfw` | boolean | Whether the brand contains adult content | +| ↳ `email` | string | Brand contact email | +| ↳ `phone` | string | Brand contact phone | +| ↳ `industries` | json | Industry taxonomy \(eic industry/subindustry pairs\) | +| ↳ `links` | json | Key brand links \(careers, privacy, terms, blog, pricing\) | +| ↳ `primary_language` | string | Primary language of the brand site | + +### `context_dev_get_brand_by_ticker` + +Retrieve brand data for a public company by its stock ticker symbol. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `ticker` | string | Yes | Stock ticker symbol \(e.g., "AAPL", "GOOGL", "BRK.A"\) | +| `tickerExchange` | string | No | Exchange code for the ticker \(e.g., "NASDAQ", "NYSE", "LSE"\). Default: NASDAQ | +| `forceLanguage` | string | No | Override the detected language with a supported language code | +| `maxSpeed` | boolean | No | Skip time-consuming operations for a faster response \(default: false\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Retrieval status | +| `brand` | object | Brand data object | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `description` | string | Brand description | +| ↳ `slogan` | string | Brand slogan | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | +| ↳ `socials` | json | Social media profiles \(type and url\) | +| ↳ `address` | json | Brand address | +| ↳ `stock` | json | Stock info \(ticker and exchange\) | +| ↳ `is_nsfw` | boolean | Whether the brand contains adult content | +| ↳ `email` | string | Brand contact email | +| ↳ `phone` | string | Brand contact phone | +| ↳ `industries` | json | Industry taxonomy \(eic industry/subindustry pairs\) | +| ↳ `links` | json | Key brand links \(careers, privacy, terms, blog, pricing\) | +| ↳ `primary_language` | string | Primary language of the brand site | + +### `context_dev_get_brand_simplified` + +Retrieve essential brand data for a domain: title, colors, logos, and backdrops. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to retrieve simplified brand data for \(e.g., "airbnb.com"\) | +| `maxAgeMs` | number | No | Cache max age in milliseconds \(86400000-31536000000, default: 7776000000\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Retrieval status | +| `brand` | object | Simplified brand data \(domain, title, colors, logos, backdrops\) | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | + +### `context_dev_identify_transaction` + +Identify the brand behind a raw bank/card transaction descriptor and return its brand data. + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `transactionInfo` | string | Yes | The raw transaction descriptor or identifier to resolve to a brand | +| `countryGl` | string | No | ISO 2-letter country code from the transaction \(e.g., "us", "gb"\) | +| `city` | string | No | City name to prioritize in the search | +| `mcc` | string | No | Merchant Category Code for the business category | +| `phone` | number | No | Phone number from the transaction for verification | +| `highConfidenceOnly` | boolean | No | Enforce additional verification steps for higher confidence \(default: false\) | +| `forceLanguage` | string | No | Override the detected language with a supported language code | +| `maxSpeed` | boolean | No | Skip time-consuming operations for a faster response \(default: false\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Identification status | +| `brand` | object | Brand data for the identified merchant | +| ↳ `domain` | string | Brand domain | +| ↳ `title` | string | Brand title | +| ↳ `description` | string | Brand description | +| ↳ `slogan` | string | Brand slogan | +| ↳ `colors` | json | Brand colors \(hex and name\) | +| ↳ `logos` | json | Brand logos with mode, colors, resolution, and type | +| ↳ `backdrops` | json | Brand backdrop images | +| ↳ `socials` | json | Social media profiles \(type and url\) | +| ↳ `address` | json | Brand address | +| ↳ `stock` | json | Stock info \(ticker and exchange\) | +| ↳ `is_nsfw` | boolean | Whether the brand contains adult content | +| ↳ `email` | string | Brand contact email | +| ↳ `phone` | string | Brand contact phone | +| ↳ `industries` | json | Industry taxonomy \(eic industry/subindustry pairs\) | +| ↳ `links` | json | Key brand links \(careers, privacy, terms, blog, pricing\) | +| ↳ `primary_language` | string | Primary language of the brand site | + +### `context_dev_prefetch_domain` + +Queue a domain for brand-data prefetching to reduce latency on later requests (subscribers; 0 credits). + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `domain` | string | Yes | The domain to prefetch brand data for \(e.g., "example.com"\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Prefetch status | +| `message` | string | Human-readable prefetch result message | +| `domain` | string | The domain queued for prefetching | + +### `context_dev_prefetch_by_email` + +Queue an email + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `email` | string | Yes | Work email address whose domain should be prefetched \(free providers rejected\) | +| `timeoutMS` | number | No | Request timeout in milliseconds \(1000-300000\) | +| `apiKey` | string | Yes | Context.dev API key | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `status` | string | Prefetch status | +| `message` | string | Human-readable prefetch result message | +| `domain` | string | The domain queued for prefetching | + + diff --git a/apps/docs/content/docs/en/integrations/meta.json b/apps/docs/content/docs/en/integrations/meta.json index e67c39642b8..ab898490da8 100644 --- a/apps/docs/content/docs/en/integrations/meta.json +++ b/apps/docs/content/docs/en/integrations/meta.json @@ -35,6 +35,7 @@ "cloudwatch", "codepipeline", "confluence", + "context_dev", "convex", "crowdstrike", "cursor", @@ -191,6 +192,7 @@ "slack", "smtp", "sqs", + "square", "ssh", "stagehand", "stripe", diff --git a/apps/docs/content/docs/en/integrations/square.mdx b/apps/docs/content/docs/en/integrations/square.mdx new file mode 100644 index 00000000000..d741dbdb24d --- /dev/null +++ b/apps/docs/content/docs/en/integrations/square.mdx @@ -0,0 +1,1479 @@ +--- +title: Square +description: Process payments and manage Square commerce data +--- + +import { BlockInfoCard } from "@/components/ui/block-info-card" + + + +## Usage Instructions + +Integrate Square into the workflow. Take and refund payments, manage customers, build catalog items and images, create and search orders, and issue invoices. Authenticate with a Square access token (personal access token). + + + +## Actions + +### `square_create_payment` + +Take a payment using a payment source such as a card nonce or a card on file + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `sourceId` | string | Yes | ID of the payment source \(card nonce, card-on-file ID, or wallet token\) | +| `amount` | number | Yes | Amount in the smallest currency denomination \(e.g. 1000 = $10.00\) | +| `currency` | string | Yes | Three-letter ISO 4217 currency code \(e.g. USD\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | +| `customerId` | string | No | ID of the customer associated with the payment | +| `locationId` | string | No | ID of the location where the payment is taken \(defaults to the main location\) | +| `orderId` | string | No | ID of the order associated with the payment | +| `referenceId` | string | No | Optional external reference for the payment | +| `note` | string | No | Optional note attached to the payment | +| `autocomplete` | boolean | No | Whether to immediately capture the payment \(defaults to true\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `payment` | object | The created payment object | +| ↳ `id` | string | Unique ID for the payment | +| ↳ `status` | string | Payment status \(APPROVED, PENDING, COMPLETED, CANCELED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `approved_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `app_fee_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `refunded_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `source_type` | string | Source of the payment \(CARD, BANK_ACCOUNT, WALLET, etc.\) | +| ↳ `card_details` | json | Details about a card payment | +| ↳ `location_id` | string | ID of the location where the payment was taken | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `reference_id` | string | Optional external reference for the payment | +| ↳ `receipt_number` | string | Receipt number for the payment | +| ↳ `receipt_url` | string | URL of the payment receipt | +| ↳ `note` | string | Optional note attached to the payment | +| ↳ `refund_ids` | array | IDs of refunds associated with the payment | +| ↳ `processing_fee` | array | Processing fees applied to the payment | +| ↳ `created_at` | string | Timestamp when the payment was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the payment was last updated \(RFC 3339\) | +| ↳ `version_token` | string | Optimistic concurrency token for the payment | +| `metadata` | json | Payment summary metadata | +| ↳ `id` | string | Square payment ID | +| ↳ `status` | string | Current payment status | +| ↳ `order_id` | string | Associated order ID | + +### `square_get_payment` + +Retrieve details for a single payment by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `paymentId` | string | Yes | ID of the payment to retrieve | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `payment` | object | The retrieved payment object | +| ↳ `id` | string | Unique ID for the payment | +| ↳ `status` | string | Payment status \(APPROVED, PENDING, COMPLETED, CANCELED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `approved_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `app_fee_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `refunded_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `source_type` | string | Source of the payment \(CARD, BANK_ACCOUNT, WALLET, etc.\) | +| ↳ `card_details` | json | Details about a card payment | +| ↳ `location_id` | string | ID of the location where the payment was taken | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `reference_id` | string | Optional external reference for the payment | +| ↳ `receipt_number` | string | Receipt number for the payment | +| ↳ `receipt_url` | string | URL of the payment receipt | +| ↳ `note` | string | Optional note attached to the payment | +| ↳ `refund_ids` | array | IDs of refunds associated with the payment | +| ↳ `processing_fee` | array | Processing fees applied to the payment | +| ↳ `created_at` | string | Timestamp when the payment was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the payment was last updated \(RFC 3339\) | +| ↳ `version_token` | string | Optimistic concurrency token for the payment | +| `metadata` | json | Payment summary metadata | +| ↳ `id` | string | Square payment ID | +| ↳ `status` | string | Current payment status | +| ↳ `order_id` | string | Associated order ID | + +### `square_list_payments` + +List payments taken by the account, optionally filtered by location and time range + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationId` | string | No | Filter payments by location ID | +| `beginTime` | string | No | RFC 3339 timestamp for the beginning of the reporting period | +| `endTime` | string | No | RFC 3339 timestamp for the end of the reporting period | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `payments` | array | Array of payment objects | +| ↳ `id` | string | Unique ID for the payment | +| ↳ `status` | string | Payment status \(APPROVED, PENDING, COMPLETED, CANCELED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `approved_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `app_fee_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `refunded_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `source_type` | string | Source of the payment \(CARD, BANK_ACCOUNT, WALLET, etc.\) | +| ↳ `card_details` | json | Details about a card payment | +| ↳ `location_id` | string | ID of the location where the payment was taken | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `reference_id` | string | Optional external reference for the payment | +| ↳ `receipt_number` | string | Receipt number for the payment | +| ↳ `receipt_url` | string | URL of the payment receipt | +| ↳ `note` | string | Optional note attached to the payment | +| ↳ `refund_ids` | array | IDs of refunds associated with the payment | +| ↳ `processing_fee` | array | Processing fees applied to the payment | +| ↳ `created_at` | string | Timestamp when the payment was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the payment was last updated \(RFC 3339\) | +| ↳ `version_token` | string | Optimistic concurrency token for the payment | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_cancel_payment` + +Cancel (void) an authorized payment that has not been captured + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `paymentId` | string | Yes | ID of the payment to cancel | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `payment` | object | The canceled payment object | +| ↳ `id` | string | Unique ID for the payment | +| ↳ `status` | string | Payment status \(APPROVED, PENDING, COMPLETED, CANCELED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `approved_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `app_fee_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `refunded_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `source_type` | string | Source of the payment \(CARD, BANK_ACCOUNT, WALLET, etc.\) | +| ↳ `card_details` | json | Details about a card payment | +| ↳ `location_id` | string | ID of the location where the payment was taken | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `reference_id` | string | Optional external reference for the payment | +| ↳ `receipt_number` | string | Receipt number for the payment | +| ↳ `receipt_url` | string | URL of the payment receipt | +| ↳ `note` | string | Optional note attached to the payment | +| ↳ `refund_ids` | array | IDs of refunds associated with the payment | +| ↳ `processing_fee` | array | Processing fees applied to the payment | +| ↳ `created_at` | string | Timestamp when the payment was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the payment was last updated \(RFC 3339\) | +| ↳ `version_token` | string | Optimistic concurrency token for the payment | +| `metadata` | json | Payment summary metadata | +| ↳ `id` | string | Square payment ID | +| ↳ `status` | string | Current payment status | +| ↳ `order_id` | string | Associated order ID | + +### `square_complete_payment` + +Capture (complete) a payment that was authorized with delayed capture + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `paymentId` | string | Yes | ID of the payment to complete | +| `versionToken` | string | No | Optional version token for optimistic concurrency control | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `payment` | object | The completed payment object | +| ↳ `id` | string | Unique ID for the payment | +| ↳ `status` | string | Payment status \(APPROVED, PENDING, COMPLETED, CANCELED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `approved_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `app_fee_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `refunded_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `source_type` | string | Source of the payment \(CARD, BANK_ACCOUNT, WALLET, etc.\) | +| ↳ `card_details` | json | Details about a card payment | +| ↳ `location_id` | string | ID of the location where the payment was taken | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `reference_id` | string | Optional external reference for the payment | +| ↳ `receipt_number` | string | Receipt number for the payment | +| ↳ `receipt_url` | string | URL of the payment receipt | +| ↳ `note` | string | Optional note attached to the payment | +| ↳ `refund_ids` | array | IDs of refunds associated with the payment | +| ↳ `processing_fee` | array | Processing fees applied to the payment | +| ↳ `created_at` | string | Timestamp when the payment was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the payment was last updated \(RFC 3339\) | +| ↳ `version_token` | string | Optimistic concurrency token for the payment | +| `metadata` | json | Payment summary metadata | +| ↳ `id` | string | Square payment ID | +| ↳ `status` | string | Current payment status | +| ↳ `order_id` | string | Associated order ID | + +### `square_refund_payment` + +Refund all or part of a completed payment + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `paymentId` | string | Yes | ID of the payment to refund | +| `amount` | number | Yes | Amount to refund in the smallest currency denomination \(e.g. 100 = $1.00\) | +| `currency` | string | Yes | Three-letter ISO 4217 currency code \(e.g. USD\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | +| `reason` | string | No | Reason for the refund | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `refund` | object | The created refund object | +| ↳ `id` | string | Unique ID for the refund | +| ↳ `status` | string | Refund status \(PENDING, COMPLETED, REJECTED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `processing_fee` | array | Processing fees refunded | +| ↳ `payment_id` | string | ID of the payment being refunded | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `location_id` | string | ID of the associated location | +| ↳ `reason` | string | Reason for the refund | +| ↳ `created_at` | string | Timestamp when the refund was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the refund was last updated \(RFC 3339\) | +| `metadata` | json | Refund summary metadata | +| ↳ `id` | string | Square refund ID | +| ↳ `status` | string | Current refund status | +| ↳ `payment_id` | string | Refunded payment ID | + +### `square_get_refund` + +Retrieve a single payment refund by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `refundId` | string | Yes | ID of the refund to retrieve | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `refund` | object | The retrieved refund object | +| ↳ `id` | string | Unique ID for the refund | +| ↳ `status` | string | Refund status \(PENDING, COMPLETED, REJECTED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `processing_fee` | array | Processing fees refunded | +| ↳ `payment_id` | string | ID of the payment being refunded | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `location_id` | string | ID of the associated location | +| ↳ `reason` | string | Reason for the refund | +| ↳ `created_at` | string | Timestamp when the refund was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the refund was last updated \(RFC 3339\) | +| `metadata` | json | Refund summary metadata | +| ↳ `id` | string | Square refund ID | +| ↳ `status` | string | Current refund status | +| ↳ `payment_id` | string | Refunded payment ID | + +### `square_list_refunds` + +List payment refunds, optionally filtered by location, status, and time range + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationId` | string | No | Filter refunds by location ID | +| `status` | string | No | Filter by refund status \(PENDING, COMPLETED, REJECTED, or FAILED\) | +| `beginTime` | string | No | RFC 3339 timestamp for the beginning of the reporting period | +| `endTime` | string | No | RFC 3339 timestamp for the end of the reporting period | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `refunds` | array | Array of refund objects | +| ↳ `id` | string | Unique ID for the refund | +| ↳ `status` | string | Refund status \(PENDING, COMPLETED, REJECTED, or FAILED\) | +| ↳ `amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `processing_fee` | array | Processing fees refunded | +| ↳ `payment_id` | string | ID of the payment being refunded | +| ↳ `order_id` | string | ID of the associated order | +| ↳ `location_id` | string | ID of the associated location | +| ↳ `reason` | string | Reason for the refund | +| ↳ `created_at` | string | Timestamp when the refund was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the refund was last updated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_create_customer` + +Create a new customer profile in the Square customer directory + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `givenName` | string | No | First name of the customer | +| `familyName` | string | No | Last name of the customer | +| `companyName` | string | No | Business name of the customer | +| `nickname` | string | No | Nickname of the customer | +| `emailAddress` | string | No | Email address of the customer | +| `phoneNumber` | string | No | Phone number of the customer | +| `birthday` | string | No | Birthday in YYYY-MM-DD or MM-DD format | +| `note` | string | No | Note about the customer | +| `referenceId` | string | No | Optional external reference for the customer | +| `address` | json | No | Square address object for the customer | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customer` | object | The created customer object | +| ↳ `id` | string | Unique ID for the customer | +| ↳ `given_name` | string | First name of the customer | +| ↳ `family_name` | string | Last name of the customer | +| ↳ `nickname` | string | Nickname of the customer | +| ↳ `company_name` | string | Business name of the customer | +| ↳ `email_address` | string | Email address of the customer | +| ↳ `phone_number` | string | Phone number of the customer | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `birthday` | string | Birthday in YYYY-MM-DD or MM-DD format | +| ↳ `reference_id` | string | Optional external reference for the customer | +| ↳ `note` | string | Note about the customer | +| ↳ `creation_source` | string | How the customer profile was created | +| ↳ `preferences` | json | Customer communication preferences | +| ↳ `group_ids` | array | IDs of customer groups the customer belongs to | +| ↳ `segment_ids` | array | IDs of customer segments the customer belongs to | +| ↳ `version` | number | Optimistic concurrency version of the customer | +| ↳ `created_at` | string | Timestamp when the customer was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the customer was last updated \(RFC 3339\) | +| `metadata` | json | Customer summary metadata | +| ↳ `id` | string | Square customer ID | +| ↳ `email_address` | string | Customer email address | +| ↳ `given_name` | string | Customer first name | +| ↳ `family_name` | string | Customer last name | + +### `square_get_customer` + +Retrieve a single customer profile by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `customerId` | string | Yes | ID of the customer to retrieve | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customer` | object | The retrieved customer object | +| ↳ `id` | string | Unique ID for the customer | +| ↳ `given_name` | string | First name of the customer | +| ↳ `family_name` | string | Last name of the customer | +| ↳ `nickname` | string | Nickname of the customer | +| ↳ `company_name` | string | Business name of the customer | +| ↳ `email_address` | string | Email address of the customer | +| ↳ `phone_number` | string | Phone number of the customer | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `birthday` | string | Birthday in YYYY-MM-DD or MM-DD format | +| ↳ `reference_id` | string | Optional external reference for the customer | +| ↳ `note` | string | Note about the customer | +| ↳ `creation_source` | string | How the customer profile was created | +| ↳ `preferences` | json | Customer communication preferences | +| ↳ `group_ids` | array | IDs of customer groups the customer belongs to | +| ↳ `segment_ids` | array | IDs of customer segments the customer belongs to | +| ↳ `version` | number | Optimistic concurrency version of the customer | +| ↳ `created_at` | string | Timestamp when the customer was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the customer was last updated \(RFC 3339\) | +| `metadata` | json | Customer summary metadata | +| ↳ `id` | string | Square customer ID | +| ↳ `email_address` | string | Customer email address | +| ↳ `given_name` | string | Customer first name | +| ↳ `family_name` | string | Customer last name | + +### `square_list_customers` + +List customer profiles in the Square customer directory + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `limit` | number | No | Maximum number of results to return per page \(max 100\) | +| `cursor` | string | No | Pagination cursor from a previous response | +| `sortField` | string | No | Field to sort by \(DEFAULT or CREATED_AT\) | +| `sortOrder` | string | No | Sort order \(ASC or DESC\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customers` | array | Array of customer objects | +| ↳ `id` | string | Unique ID for the customer | +| ↳ `given_name` | string | First name of the customer | +| ↳ `family_name` | string | Last name of the customer | +| ↳ `nickname` | string | Nickname of the customer | +| ↳ `company_name` | string | Business name of the customer | +| ↳ `email_address` | string | Email address of the customer | +| ↳ `phone_number` | string | Phone number of the customer | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `birthday` | string | Birthday in YYYY-MM-DD or MM-DD format | +| ↳ `reference_id` | string | Optional external reference for the customer | +| ↳ `note` | string | Note about the customer | +| ↳ `creation_source` | string | How the customer profile was created | +| ↳ `preferences` | json | Customer communication preferences | +| ↳ `group_ids` | array | IDs of customer groups the customer belongs to | +| ↳ `segment_ids` | array | IDs of customer segments the customer belongs to | +| ↳ `version` | number | Optimistic concurrency version of the customer | +| ↳ `created_at` | string | Timestamp when the customer was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the customer was last updated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_search_customers` + +Search customer profiles using filters such as email, phone, or creation date + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `query` | json | No | Square customer query object with optional filter and sort \(e.g. \{"filter":\{"email_address":\{"exact":"a@b.com"\}\}\}\) | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customers` | array | Array of matching customer objects | +| ↳ `id` | string | Unique ID for the customer | +| ↳ `given_name` | string | First name of the customer | +| ↳ `family_name` | string | Last name of the customer | +| ↳ `nickname` | string | Nickname of the customer | +| ↳ `company_name` | string | Business name of the customer | +| ↳ `email_address` | string | Email address of the customer | +| ↳ `phone_number` | string | Phone number of the customer | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `birthday` | string | Birthday in YYYY-MM-DD or MM-DD format | +| ↳ `reference_id` | string | Optional external reference for the customer | +| ↳ `note` | string | Note about the customer | +| ↳ `creation_source` | string | How the customer profile was created | +| ↳ `preferences` | json | Customer communication preferences | +| ↳ `group_ids` | array | IDs of customer groups the customer belongs to | +| ↳ `segment_ids` | array | IDs of customer segments the customer belongs to | +| ↳ `version` | number | Optimistic concurrency version of the customer | +| ↳ `created_at` | string | Timestamp when the customer was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the customer was last updated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_update_customer` + +Update fields on an existing customer profile + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `customerId` | string | Yes | ID of the customer to update | +| `givenName` | string | No | First name of the customer | +| `familyName` | string | No | Last name of the customer | +| `companyName` | string | No | Business name of the customer | +| `nickname` | string | No | Nickname of the customer | +| `emailAddress` | string | No | Email address of the customer | +| `phoneNumber` | string | No | Phone number of the customer | +| `birthday` | string | No | Birthday in YYYY-MM-DD or MM-DD format | +| `note` | string | No | Note about the customer | +| `referenceId` | string | No | Optional external reference for the customer | +| `address` | json | No | Square address object for the customer | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `customer` | object | The updated customer object | +| ↳ `id` | string | Unique ID for the customer | +| ↳ `given_name` | string | First name of the customer | +| ↳ `family_name` | string | Last name of the customer | +| ↳ `nickname` | string | Nickname of the customer | +| ↳ `company_name` | string | Business name of the customer | +| ↳ `email_address` | string | Email address of the customer | +| ↳ `phone_number` | string | Phone number of the customer | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `birthday` | string | Birthday in YYYY-MM-DD or MM-DD format | +| ↳ `reference_id` | string | Optional external reference for the customer | +| ↳ `note` | string | Note about the customer | +| ↳ `creation_source` | string | How the customer profile was created | +| ↳ `preferences` | json | Customer communication preferences | +| ↳ `group_ids` | array | IDs of customer groups the customer belongs to | +| ↳ `segment_ids` | array | IDs of customer segments the customer belongs to | +| ↳ `version` | number | Optimistic concurrency version of the customer | +| ↳ `created_at` | string | Timestamp when the customer was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the customer was last updated \(RFC 3339\) | +| `metadata` | json | Customer summary metadata | +| ↳ `id` | string | Square customer ID | +| ↳ `email_address` | string | Customer email address | +| ↳ `given_name` | string | Customer first name | +| ↳ `family_name` | string | Customer last name | + +### `square_delete_customer` + +Delete a customer profile from the Square customer directory + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `customerId` | string | Yes | ID of the customer to delete | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `deleted` | boolean | Whether the customer was deleted | +| `id` | string | ID of the deleted customer | + +### `square_list_locations` + +List all locations associated with the Square account + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `locations` | array | Array of location objects | +| ↳ `id` | string | Unique ID for the location | +| ↳ `name` | string | Name of the location | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `timezone` | string | IANA timezone of the location | +| ↳ `status` | string | Location status \(ACTIVE or INACTIVE\) | +| ↳ `type` | string | Location type \(PHYSICAL or MOBILE\) | +| ↳ `merchant_id` | string | ID of the merchant that owns the location | +| ↳ `country` | string | Country code of the location | +| ↳ `language_code` | string | Language code of the location | +| ↳ `currency` | string | Currency used by the location | +| ↳ `phone_number` | string | Phone number of the location | +| ↳ `business_name` | string | Business name shown to customers | +| ↳ `business_email` | string | Email of the business | +| ↳ `description` | string | Description of the location | +| ↳ `capabilities` | array | Capabilities of the location \(e.g. CREDIT_CARD_PROCESSING\) | +| ↳ `created_at` | string | Timestamp when the location was created \(RFC 3339\) | +| `metadata` | json | List metadata | +| ↳ `count` | number | Number of locations returned | + +### `square_get_location` + +Retrieve a single location by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationId` | string | Yes | ID of the location to retrieve \(use "main" for the main location\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `location` | object | The retrieved location object | +| ↳ `id` | string | Unique ID for the location | +| ↳ `name` | string | Name of the location | +| ↳ `address` | object | Physical address | +| ↳ `address_line_1` | string | First line of the address | +| ↳ `address_line_2` | string | Second line of the address | +| ↳ `address_line_3` | string | Third line of the address | +| ↳ `locality` | string | City or town | +| ↳ `sublocality` | string | Neighborhood or district | +| ↳ `administrative_district_level_1` | string | State, province, or region | +| ↳ `postal_code` | string | Postal or ZIP code | +| ↳ `country` | string | Two-letter ISO 3166-1 alpha-2 country code | +| ↳ `first_name` | string | First name of the addressee | +| ↳ `last_name` | string | Last name of the addressee | +| ↳ `timezone` | string | IANA timezone of the location | +| ↳ `status` | string | Location status \(ACTIVE or INACTIVE\) | +| ↳ `type` | string | Location type \(PHYSICAL or MOBILE\) | +| ↳ `merchant_id` | string | ID of the merchant that owns the location | +| ↳ `country` | string | Country code of the location | +| ↳ `language_code` | string | Language code of the location | +| ↳ `currency` | string | Currency used by the location | +| ↳ `phone_number` | string | Phone number of the location | +| ↳ `business_name` | string | Business name shown to customers | +| ↳ `business_email` | string | Email of the business | +| ↳ `description` | string | Description of the location | +| ↳ `capabilities` | array | Capabilities of the location \(e.g. CREDIT_CARD_PROCESSING\) | +| ↳ `created_at` | string | Timestamp when the location was created \(RFC 3339\) | +| `metadata` | json | Location summary metadata | +| ↳ `id` | string | Square location ID | +| ↳ `name` | string | Location name | + +### `square_create_order` + +Create an order with line items, taxes, discounts, and fulfillments + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `order` | json | Yes | Square order object including location_id and line_items \(e.g. \{"location_id":"L1","line_items":\[\{"name":"Coffee","quantity":"1","base_price_money":\{"amount":250,"currency":"USD"\}\}\]\}\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `order` | object | The created order object | +| ↳ `id` | string | Unique ID for the order | +| ↳ `location_id` | string | ID of the location for the order | +| ↳ `reference_id` | string | Optional external reference for the order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `state` | string | Order state \(OPEN, COMPLETED, or CANCELED\) | +| ↳ `version` | number | Optimistic concurrency version of the order | +| ↳ `line_items` | array | Line items in the order | +| ↳ `taxes` | array | Taxes applied to the order | +| ↳ `discounts` | array | Discounts applied to the order | +| ↳ `fulfillments` | array | Fulfillments for the order | +| ↳ `net_amounts` | json | Net money amounts for the order | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tax_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_discount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_service_charge_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `created_at` | string | Timestamp when the order was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the order was last updated \(RFC 3339\) | +| ↳ `closed_at` | string | Timestamp when the order was closed \(RFC 3339\) | +| `metadata` | json | Order summary metadata | +| ↳ `id` | string | Square order ID | +| ↳ `state` | string | Current order state | +| ↳ `location_id` | string | Order location ID | + +### `square_get_order` + +Retrieve a single order by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `orderId` | string | Yes | ID of the order to retrieve | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `order` | object | The retrieved order object | +| ↳ `id` | string | Unique ID for the order | +| ↳ `location_id` | string | ID of the location for the order | +| ↳ `reference_id` | string | Optional external reference for the order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `state` | string | Order state \(OPEN, COMPLETED, or CANCELED\) | +| ↳ `version` | number | Optimistic concurrency version of the order | +| ↳ `line_items` | array | Line items in the order | +| ↳ `taxes` | array | Taxes applied to the order | +| ↳ `discounts` | array | Discounts applied to the order | +| ↳ `fulfillments` | array | Fulfillments for the order | +| ↳ `net_amounts` | json | Net money amounts for the order | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tax_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_discount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_service_charge_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `created_at` | string | Timestamp when the order was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the order was last updated \(RFC 3339\) | +| ↳ `closed_at` | string | Timestamp when the order was closed \(RFC 3339\) | +| `metadata` | json | Order summary metadata | +| ↳ `id` | string | Square order ID | +| ↳ `state` | string | Current order state | +| ↳ `location_id` | string | Order location ID | + +### `square_search_orders` + +Search orders across one or more locations using filters and sorting + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationIds` | array | Yes | Array of location IDs to search within | +| `query` | json | No | Square order query object with optional filter and sort \(e.g. \{"filter":\{"state_filter":\{"states":\["OPEN"\]\}\}\}\) | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `orders` | array | Array of matching order objects | +| ↳ `id` | string | Unique ID for the order | +| ↳ `location_id` | string | ID of the location for the order | +| ↳ `reference_id` | string | Optional external reference for the order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `state` | string | Order state \(OPEN, COMPLETED, or CANCELED\) | +| ↳ `version` | number | Optimistic concurrency version of the order | +| ↳ `line_items` | array | Line items in the order | +| ↳ `taxes` | array | Taxes applied to the order | +| ↳ `discounts` | array | Discounts applied to the order | +| ↳ `fulfillments` | array | Fulfillments for the order | +| ↳ `net_amounts` | json | Net money amounts for the order | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tax_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_discount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_service_charge_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `created_at` | string | Timestamp when the order was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the order was last updated \(RFC 3339\) | +| ↳ `closed_at` | string | Timestamp when the order was closed \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_pay_order` + +Pay for an order using one or more already-approved payments + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `orderId` | string | Yes | ID of the order to pay for | +| `paymentIds` | array | No | IDs of approved payments to apply to the order | +| `orderVersion` | number | No | Version of the order being paid \(for optimistic concurrency\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `order` | object | The paid order object | +| ↳ `id` | string | Unique ID for the order | +| ↳ `location_id` | string | ID of the location for the order | +| ↳ `reference_id` | string | Optional external reference for the order | +| ↳ `customer_id` | string | ID of the associated customer | +| ↳ `state` | string | Order state \(OPEN, COMPLETED, or CANCELED\) | +| ↳ `version` | number | Optimistic concurrency version of the order | +| ↳ `line_items` | array | Line items in the order | +| ↳ `taxes` | array | Taxes applied to the order | +| ↳ `discounts` | array | Discounts applied to the order | +| ↳ `fulfillments` | array | Fulfillments for the order | +| ↳ `net_amounts` | json | Net money amounts for the order | +| ↳ `total_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tax_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_discount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_service_charge_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `total_tip_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `created_at` | string | Timestamp when the order was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the order was last updated \(RFC 3339\) | +| ↳ `closed_at` | string | Timestamp when the order was closed \(RFC 3339\) | +| `metadata` | json | Order summary metadata | +| ↳ `id` | string | Square order ID | +| ↳ `state` | string | Current order state | +| ↳ `location_id` | string | Order location ID | + +### `square_create_invoice` + +Create a draft invoice for an existing order and customer + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `invoice` | json | Yes | Square invoice object including location_id, order_id, primary_recipient, and payment_requests \(e.g. \{"location_id":"L1","order_id":"O1","primary_recipient":\{"customer_id":"C1"\},"payment_requests":\[\{"request_type":"BALANCE","due_date":"2026-07-01"\}\]\}\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoice` | object | The created invoice object | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | Invoice summary metadata | +| ↳ `id` | string | Square invoice ID | +| ↳ `status` | string | Current invoice status | +| ↳ `version` | number | Invoice version | + +### `square_get_invoice` + +Retrieve a single invoice by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `invoiceId` | string | Yes | ID of the invoice to retrieve | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoice` | object | The retrieved invoice object | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | Invoice summary metadata | +| ↳ `id` | string | Square invoice ID | +| ↳ `status` | string | Current invoice status | +| ↳ `version` | number | Invoice version | + +### `square_list_invoices` + +List invoices for a specific location + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationId` | string | Yes | ID of the location to list invoices for | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoices` | array | Array of invoice objects | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_search_invoices` + +Search invoices across one or more locations + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `locationId` | string | Yes | ID of the location to search within \(Square allows one location per search\) | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoices` | array | Array of matching invoice objects | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_publish_invoice` + +Publish a draft invoice so it is sent to the customer and becomes payable + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `invoiceId` | string | Yes | ID of the invoice to publish | +| `version` | number | Yes | Current version of the invoice \(use the version returned by Create Invoice\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoice` | object | The published invoice object | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | Invoice summary metadata | +| ↳ `id` | string | Square invoice ID | +| ↳ `status` | string | Current invoice status | +| ↳ `version` | number | Invoice version | + +### `square_cancel_invoice` + +Cancel a published invoice that is unpaid or partially paid + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `invoiceId` | string | Yes | ID of the invoice to cancel | +| `version` | number | Yes | Current version of the invoice | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `invoice` | object | The canceled invoice object | +| ↳ `id` | string | Unique ID for the invoice | +| ↳ `version` | number | Optimistic concurrency version of the invoice | +| ↳ `location_id` | string | ID of the location for the invoice | +| ↳ `order_id` | string | ID of the order the invoice bills for | +| ↳ `status` | string | Invoice status \(DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.\) | +| ↳ `invoice_number` | string | Human-readable invoice number | +| ↳ `title` | string | Title of the invoice | +| ↳ `description` | string | Description of the invoice | +| ↳ `public_url` | string | URL where the customer can view and pay the invoice | +| ↳ `primary_recipient` | json | Primary recipient of the invoice | +| ↳ `payment_requests` | array | Payment requests for the invoice | +| ↳ `next_payment_amount_money` | object | Monetary amount with a currency | +| ↳ `amount` | number | Amount in the smallest denomination of the currency \(e.g. cents for USD\) | +| ↳ `currency` | string | Three-letter ISO 4217 currency code \(e.g. USD\) | +| ↳ `scheduled_at` | string | Timestamp when the invoice is scheduled to be sent \(RFC 3339\) | +| ↳ `timezone` | string | Timezone used for invoice dates | +| ↳ `delivery_method` | string | How the invoice is delivered \(EMAIL, SHARE_MANUALLY, SMS\) | +| ↳ `created_at` | string | Timestamp when the invoice was created \(RFC 3339\) | +| ↳ `updated_at` | string | Timestamp when the invoice was last updated \(RFC 3339\) | +| `metadata` | json | Invoice summary metadata | +| ↳ `id` | string | Square invoice ID | +| ↳ `status` | string | Current invoice status | +| ↳ `version` | number | Invoice version | + +### `square_delete_invoice` + +Delete a draft invoice + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `invoiceId` | string | Yes | ID of the draft invoice to delete | +| `version` | number | No | Current version of the invoice \(required if the invoice has been updated\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `deleted` | boolean | Whether the invoice was deleted | +| `id` | string | ID of the deleted invoice | + +### `square_upsert_catalog_object` + +Create or update a catalog object such as an item, variation, or category + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `object` | json | Yes | Square catalog object to create or update. Use ID "#name" for new objects \(e.g. \{"type":"ITEM","id":"#Coffee","item_data":\{"name":"Coffee"\}\}\) | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `object` | object | The created or updated catalog object | +| ↳ `type` | string | Type of catalog object \(ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.\) | +| ↳ `id` | string | Unique ID for the catalog object | +| ↳ `version` | number | Optimistic concurrency version of the object | +| ↳ `updated_at` | string | Timestamp when the object was last updated \(RFC 3339\) | +| ↳ `is_deleted` | boolean | Whether the object is deleted | +| ↳ `present_at_all_locations` | boolean | Whether the object is present at all locations | +| ↳ `item_data` | json | Item-specific data \(when type is ITEM\) | +| ↳ `item_variation_data` | json | Variation-specific data \(when type is ITEM_VARIATION\) | +| ↳ `category_data` | json | Category-specific data \(when type is CATEGORY\) | +| ↳ `image_data` | json | Image-specific data \(when type is IMAGE\) | +| `metadata` | json | Catalog object summary metadata | +| ↳ `id` | string | Square catalog object ID | +| ↳ `type` | string | Catalog object type | +| ↳ `version` | number | Catalog object version | + +### `square_get_catalog_object` + +Retrieve a single catalog object by its ID + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `objectId` | string | Yes | ID of the catalog object to retrieve | +| `includeRelatedObjects` | boolean | No | Whether to include related objects such as an item variations | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `object` | object | The retrieved catalog object | +| ↳ `type` | string | Type of catalog object \(ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.\) | +| ↳ `id` | string | Unique ID for the catalog object | +| ↳ `version` | number | Optimistic concurrency version of the object | +| ↳ `updated_at` | string | Timestamp when the object was last updated \(RFC 3339\) | +| ↳ `is_deleted` | boolean | Whether the object is deleted | +| ↳ `present_at_all_locations` | boolean | Whether the object is present at all locations | +| ↳ `item_data` | json | Item-specific data \(when type is ITEM\) | +| ↳ `item_variation_data` | json | Variation-specific data \(when type is ITEM_VARIATION\) | +| ↳ `category_data` | json | Category-specific data \(when type is CATEGORY\) | +| ↳ `image_data` | json | Image-specific data \(when type is IMAGE\) | +| `metadata` | json | Catalog object summary metadata | +| ↳ `id` | string | Square catalog object ID | +| ↳ `type` | string | Catalog object type | +| ↳ `version` | number | Catalog object version | + +### `square_list_catalog` + +List catalog objects, optionally filtered by type + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `types` | string | No | Comma-separated catalog object types to return \(e.g. ITEM,CATEGORY\). Defaults to all top-level types | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `objects` | array | Array of catalog objects | +| ↳ `type` | string | Type of catalog object \(ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.\) | +| ↳ `id` | string | Unique ID for the catalog object | +| ↳ `version` | number | Optimistic concurrency version of the object | +| ↳ `updated_at` | string | Timestamp when the object was last updated \(RFC 3339\) | +| ↳ `is_deleted` | boolean | Whether the object is deleted | +| ↳ `present_at_all_locations` | boolean | Whether the object is present at all locations | +| ↳ `item_data` | json | Item-specific data \(when type is ITEM\) | +| ↳ `item_variation_data` | json | Variation-specific data \(when type is ITEM_VARIATION\) | +| ↳ `category_data` | json | Category-specific data \(when type is CATEGORY\) | +| ↳ `image_data` | json | Image-specific data \(when type is IMAGE\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_search_catalog_objects` + +Search catalog objects by type and query filters + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `objectTypes` | array | No | Array of catalog object types to search \(e.g. \["ITEM","CATEGORY"\]\) | +| `query` | json | No | Square catalog query object \(e.g. \{"text_query":\{"keywords":\["coffee"\]\}\} or \{"prefix_query":\{...\}\}\) | +| `limit` | number | No | Maximum number of results to return per page | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `objects` | array | Array of matching catalog objects | +| ↳ `type` | string | Type of catalog object \(ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.\) | +| ↳ `id` | string | Unique ID for the catalog object | +| ↳ `version` | number | Optimistic concurrency version of the object | +| ↳ `updated_at` | string | Timestamp when the object was last updated \(RFC 3339\) | +| ↳ `is_deleted` | boolean | Whether the object is deleted | +| ↳ `present_at_all_locations` | boolean | Whether the object is present at all locations | +| ↳ `item_data` | json | Item-specific data \(when type is ITEM\) | +| ↳ `item_variation_data` | json | Variation-specific data \(when type is ITEM_VARIATION\) | +| ↳ `category_data` | json | Category-specific data \(when type is CATEGORY\) | +| ↳ `image_data` | json | Image-specific data \(when type is IMAGE\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + +### `square_create_catalog_image` + +Upload an image and attach it to the catalog, optionally to a specific item + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `file` | file | Yes | The image file to upload \(UserFile object\) | +| `fileName` | string | No | Optional filename override for the image | +| `objectId` | string | No | ID of the catalog object \(e.g. an item\) to attach the image to | +| `caption` | string | No | Caption \(alt text\) for the image | +| `idempotencyKey` | string | No | Unique key to make the request idempotent \(auto-generated if omitted\) | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `object` | object | The created catalog image object | +| ↳ `type` | string | Type of catalog object \(ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.\) | +| ↳ `id` | string | Unique ID for the catalog object | +| ↳ `version` | number | Optimistic concurrency version of the object | +| ↳ `updated_at` | string | Timestamp when the object was last updated \(RFC 3339\) | +| ↳ `is_deleted` | boolean | Whether the object is deleted | +| ↳ `present_at_all_locations` | boolean | Whether the object is present at all locations | +| ↳ `item_data` | json | Item-specific data \(when type is ITEM\) | +| ↳ `item_variation_data` | json | Variation-specific data \(when type is ITEM_VARIATION\) | +| ↳ `category_data` | json | Category-specific data \(when type is CATEGORY\) | +| ↳ `image_data` | json | Image-specific data \(when type is IMAGE\) | +| `metadata` | json | Catalog object summary metadata | +| ↳ `id` | string | Square catalog object ID | +| ↳ `type` | string | Catalog object type | +| ↳ `version` | number | Catalog object version | + +### `square_delete_catalog_object` + +Delete a catalog object and its children (e.g. an item and its variations) + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `objectId` | string | Yes | ID of the catalog object to delete | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `deleted` | boolean | Whether the catalog object was deleted | +| `deleted_object_ids` | array | IDs of all catalog objects deleted \(including children\) | +| `deleted_at` | string | Timestamp when the deletion occurred \(RFC 3339\) | + +### `square_batch_retrieve_inventory_counts` + +Retrieve current inventory counts for catalog items across locations + +#### Input + +| Parameter | Type | Required | Description | +| --------- | ---- | -------- | ----------- | +| `apiKey` | string | Yes | Square access token \(personal access token\) | +| `catalogObjectIds` | array | No | IDs of the catalog item variations to retrieve counts for | +| `locationIds` | array | No | IDs of the locations to retrieve counts for \(defaults to all locations\) | +| `states` | array | No | Inventory states to filter by \(e.g. IN_STOCK, SOLD, IN_TRANSIT\) | +| `updatedAfter` | string | No | Only return counts updated after this RFC 3339 timestamp | +| `limit` | number | No | Maximum number of results to return per page \(1-1000\) | +| `cursor` | string | No | Pagination cursor from a previous response | + +#### Output + +| Parameter | Type | Description | +| --------- | ---- | ----------- | +| `counts` | array | Array of inventory count objects | +| ↳ `catalog_object_id` | string | ID of the catalog object \(item variation\) being counted | +| ↳ `catalog_object_type` | string | Type of the counted catalog object \(usually ITEM_VARIATION\) | +| ↳ `state` | string | Inventory state \(e.g. IN_STOCK, SOLD, WASTE\) | +| ↳ `location_id` | string | ID of the location for this count | +| ↳ `quantity` | string | Number of units in the given state at the location | +| ↳ `calculated_at` | string | Timestamp when the count was calculated \(RFC 3339\) | +| `metadata` | json | List pagination metadata | +| ↳ `count` | number | Number of items returned in this page | +| ↳ `cursor` | string | Pagination cursor to fetch the next page, if more results exist | + + diff --git a/apps/sim/app/(auth)/verify/use-verification.ts b/apps/sim/app/(auth)/verify/use-verification.ts index ec95836c98a..7e809685aeb 100644 --- a/apps/sim/app/(auth)/verify/use-verification.ts +++ b/apps/sim/app/(auth)/verify/use-verification.ts @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { createLogger } from '@sim/logger' +import { normalizeEmail } from '@sim/utils/string' import { useRouter, useSearchParams } from 'next/navigation' import { client, useSession } from '@/lib/auth/auth-client' import { validateCallbackUrl } from '@/lib/core/security/input-validation' @@ -100,7 +101,7 @@ export function useVerification({ setErrorMessage('') try { - const normalizedEmail = email.trim().toLowerCase() + const normalizedEmail = normalizeEmail(email) const response = await client.emailOtp.verifyEmail({ email: normalizedEmail, otp, @@ -173,7 +174,7 @@ export function useVerification({ setIsLoading(true) setErrorMessage('') - const normalizedEmail = email.trim().toLowerCase() + const normalizedEmail = normalizeEmail(email) client.emailOtp .sendVerificationOtp({ email: normalizedEmail, diff --git a/apps/sim/app/api/credential-sets/invite/[token]/route.ts b/apps/sim/app/api/credential-sets/invite/[token]/route.ts index efaff3de3af..160a5054739 100644 --- a/apps/sim/app/api/credential-sets/invite/[token]/route.ts +++ b/apps/sim/app/api/credential-sets/invite/[token]/route.ts @@ -8,6 +8,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' +import { normalizeEmail } from '@sim/utils/string' import { and, eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { @@ -17,7 +18,6 @@ import { import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { normalizeEmail } from '@/lib/invitations/core' import { syncAllWebhooksForCredentialSet } from '@/lib/webhooks/utils.server' const logger = createLogger('CredentialSetInviteToken') diff --git a/apps/sim/app/api/invitations/[id]/route.ts b/apps/sim/app/api/invitations/[id]/route.ts index 4bcdca5a1f6..f17d2e10a59 100644 --- a/apps/sim/app/api/invitations/[id]/route.ts +++ b/apps/sim/app/api/invitations/[id]/route.ts @@ -2,6 +2,7 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' import { db } from '@sim/db' import { invitation, invitationWorkspaceGrant } from '@sim/db/schema' import { createLogger } from '@sim/logger' +import { normalizeEmail } from '@sim/utils/string' import { and, eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { @@ -13,7 +14,7 @@ import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { cancelInvitation, getInvitationById, normalizeEmail } from '@/lib/invitations/core' +import { cancelInvitation, getInvitationById } from '@/lib/invitations/core' import { hasWorkspaceAdminAccess } from '@/lib/workspaces/permissions/utils' const logger = createLogger('InvitationsAPI') diff --git a/apps/sim/app/api/tools/crowdstrike/query/route.ts b/apps/sim/app/api/tools/crowdstrike/query/route.ts index 92335d15c5e..218695f8601 100644 --- a/apps/sim/app/api/tools/crowdstrike/query/route.ts +++ b/apps/sim/app/api/tools/crowdstrike/query/route.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { type NextRequest, NextResponse } from 'next/server' import { crowdstrikeQueryContract } from '@/lib/api/contracts/tools/crowdstrike' import { getValidationErrorMessage, parseRequest } from '@/lib/api/server' @@ -31,10 +32,6 @@ function getCloudBaseUrl(cloud: CrowdStrikeCloud): string { return cloudMap[cloud] } -function isJsonRecord(value: unknown): value is JsonRecord { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function getString(value: unknown): string | null { return typeof value === 'string' ? value : null } @@ -56,12 +53,12 @@ function getRecordArray(value: unknown): JsonRecord[] { return [] } - return value.filter(isJsonRecord) + return value.filter(isRecordLike) } function getResourcesArray(data: unknown): unknown[] { const root = getResponseRoot(data) - if (!isJsonRecord(root) || !Array.isArray(root.resources)) { + if (!isRecordLike(root) || !Array.isArray(root.resources)) { return [] } @@ -69,7 +66,7 @@ function getResourcesArray(data: unknown): unknown[] { } function getRecordResources(data: unknown): JsonRecord[] { - return getResourcesArray(data).filter(isJsonRecord) + return getResourcesArray(data).filter(isRecordLike) } function getStringResources(data: unknown): string[] { @@ -77,11 +74,11 @@ function getStringResources(data: unknown): string[] { } function getResponseRoot(data: unknown): unknown { - if (!isJsonRecord(data)) { + if (!isRecordLike(data)) { return null } - if (isJsonRecord(data.body)) { + if (isRecordLike(data.body)) { return data.body } @@ -90,7 +87,7 @@ function getResponseRoot(data: unknown): unknown { function getPagination(data: unknown) { const root = getResponseRoot(data) - if (!isJsonRecord(root) || !isJsonRecord(root.meta) || !isJsonRecord(root.meta.pagination)) { + if (!isRecordLike(root) || !isRecordLike(root.meta) || !isRecordLike(root.meta.pagination)) { return null } @@ -102,13 +99,13 @@ function getPagination(data: unknown) { } function getErrorMessage(data: unknown, fallback: string): string { - if (!isJsonRecord(data)) { + if (!isRecordLike(data)) { return fallback } const errors = Array.isArray(data.errors) ? data.errors : [] const firstError = errors[0] - if (isJsonRecord(firstError)) { + if (isRecordLike(firstError)) { const firstMessage = getString(firstError.message) ?? getString(firstError.code) if (firstMessage) { return firstMessage @@ -179,7 +176,7 @@ async function getAccessToken(params: CrowdStrikeBaseParams): Promise { throw new Error(getErrorMessage(data, 'Failed to authenticate with CrowdStrike')) } - if (!isJsonRecord(data) || typeof data.access_token !== 'string') { + if (!isRecordLike(data) || typeof data.access_token !== 'string') { throw new Error('CrowdStrike authentication did not return an access token') } @@ -234,7 +231,7 @@ function normalizeAggregationBucket(resource: JsonRecord): CrowdStrikeSensorAggr count: getNumber(resource.count), from: getNumber(resource.from), keyAsString: getString(resource.key_as_string), - label: isJsonRecord(resource.label) ? resource.label : null, + label: isRecordLike(resource.label) ? resource.label : null, stringFrom: getString(resource.string_from), stringTo: getString(resource.string_to), subAggregates: getRecordArray(resource.sub_aggregates).map(normalizeAggregationResult), diff --git a/apps/sim/app/api/tools/image/route.ts b/apps/sim/app/api/tools/image/route.ts index e6560c71f64..d4f7492c4ae 100644 --- a/apps/sim/app/api/tools/image/route.ts +++ b/apps/sim/app/api/tools/image/route.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage, toError } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' +import { isRecordLike } from '@sim/utils/object' import { type NextRequest, NextResponse } from 'next/server' import { type ImageToolBody, @@ -431,10 +432,6 @@ const FALAI_IMAGE_MODEL_CONFIGS: Record = { }, } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function getStringProperty( record: Record | undefined, key: string @@ -452,7 +449,7 @@ function getNumberProperty( } function firstRecord(value: unknown): Record | undefined { - return Array.isArray(value) ? value.find(isRecord) : undefined + return Array.isArray(value) ? value.find(isRecordLike) : undefined } function pickAllowed( @@ -575,7 +572,7 @@ async function generateWithOpenAI( maxBytes: MAX_IMAGE_JSON_BYTES, label: 'OpenAI image response', }) - if (!isRecord(data)) { + if (!isRecordLike(data)) { throw new Error('Invalid OpenAI image response') } @@ -669,27 +666,27 @@ async function generateWithGemini( maxBytes: MAX_IMAGE_JSON_BYTES, label: 'Gemini image response', }) - if (!isRecord(data)) { + if (!isRecordLike(data)) { throw new Error('Invalid Gemini image response') } const candidate = firstRecord(data.candidates) - const content = isRecord(candidate?.content) ? candidate.content : undefined + const content = isRecordLike(candidate?.content) ? candidate.content : undefined const parts = Array.isArray(content?.parts) ? content.parts : [] - const textPart = parts.find((part) => isRecord(part) && typeof part.text === 'string') + const textPart = parts.find((part) => isRecordLike(part) && typeof part.text === 'string') const imagePart = parts.find((part) => { - if (!isRecord(part)) return false - return isRecord(part.inlineData) || isRecord(part.inline_data) + if (!isRecordLike(part)) return false + return isRecordLike(part.inlineData) || isRecordLike(part.inline_data) }) - if (!isRecord(imagePart)) { + if (!isRecordLike(imagePart)) { logger.error(`[${requestId}] Gemini response missing image part`) throw new Error('No image data found in Gemini response') } - const inlineData = isRecord(imagePart.inlineData) + const inlineData = isRecordLike(imagePart.inlineData) ? imagePart.inlineData - : isRecord(imagePart.inline_data) + : isRecordLike(imagePart.inline_data) ? imagePart.inline_data : undefined const base64Image = getStringProperty(inlineData, 'data') @@ -712,7 +709,7 @@ async function generateWithGemini( fileName: `gemini-${model}.${extensionFromContentType(contentType)}`, provider: 'gemini', model, - description: isRecord(textPart) ? getStringProperty(textPart, 'text') : undefined, + description: isRecordLike(textPart) ? getStringProperty(textPart, 'text') : undefined, } } @@ -722,7 +719,7 @@ function buildFalAIQueueUrl(endpoint: string, requestId: string, path: 'status' function getFalAIErrorMessage(error: unknown): string { if (typeof error === 'string') return error - if (isRecord(error)) { + if (isRecordLike(error)) { return ( getStringProperty(error, 'message') || getStringProperty(error, 'detail') || @@ -835,7 +832,7 @@ async function generateWithFalAI( maxBytes: MAX_IMAGE_JSON_BYTES, label: 'Fal.ai create response', }) - if (!isRecord(createData)) { + if (!isRecordLike(createData)) { throw new Error('Invalid Fal.ai queue response') } @@ -878,7 +875,7 @@ async function generateWithFalAI( maxBytes: MAX_IMAGE_JSON_BYTES, label: 'Fal.ai status response', }) - if (!isRecord(statusData)) { + if (!isRecordLike(statusData)) { throw new Error('Invalid Fal.ai status response') } @@ -910,7 +907,7 @@ async function generateWithFalAI( maxBytes: MAX_IMAGE_JSON_BYTES, label: 'Fal.ai result response', }) - if (!isRecord(resultData)) { + if (!isRecordLike(resultData)) { throw new Error('Invalid Fal.ai result response') } diff --git a/apps/sim/app/api/tools/square/catalog-image/route.ts b/apps/sim/app/api/tools/square/catalog-image/route.ts new file mode 100644 index 00000000000..622c5c1c7a2 --- /dev/null +++ b/apps/sim/app/api/tools/square/catalog-image/route.ts @@ -0,0 +1,121 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { type NextRequest, NextResponse } from 'next/server' +import { squareCatalogImageContract } from '@/lib/api/contracts/tools/square' +import { parseRequest } from '@/lib/api/server' +import { checkInternalAuth } from '@/lib/auth/hybrid' +import { generateRequestId } from '@/lib/core/utils/request' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils' +import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' +import { assertToolFileAccess } from '@/app/api/files/authorization' +import { SQUARE_API_VERSION, SQUARE_BASE_URL } from '@/tools/square/types' + +export const dynamic = 'force-dynamic' + +const logger = createLogger('SquareCatalogImageAPI') + +export const POST = withRouteHandler(async (request: NextRequest) => { + const requestId = generateRequestId() + + try { + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) + + if (!authResult.success || !authResult.userId) { + logger.warn(`[${requestId}] Unauthorized Square catalog image upload: ${authResult.error}`) + return NextResponse.json( + { success: false, error: authResult.error || 'Authentication required' }, + { status: 401 } + ) + } + + const parsed = await parseRequest(squareCatalogImageContract, request, {}) + if (!parsed.success) return parsed.response + const validatedData = parsed.data.body + + if (!validatedData.file) { + return NextResponse.json({ success: false, error: 'File is required' }, { status: 400 }) + } + + const userFiles = processFilesToUserFiles( + [validatedData.file as RawFileInput], + requestId, + logger + ) + + if (userFiles.length === 0) { + return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 }) + } + + const userFile = userFiles[0] + const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger) + if (denied) return denied + + const fileBuffer = await downloadFileFromStorage(userFile, requestId, logger) + const fileName = validatedData.fileName || userFile.name + const mimeType = userFile.type || 'application/octet-stream' + + const imageRequest: Record = { + idempotency_key: validatedData.idempotencyKey || generateId(), + image: { + type: 'IMAGE', + id: '#square_catalog_image', + image_data: validatedData.caption ? { caption: validatedData.caption } : {}, + }, + } + if (validatedData.objectId) imageRequest.object_id = validatedData.objectId + + const formData = new FormData() + formData.append('request', JSON.stringify(imageRequest)) + formData.append('file', new Blob([new Uint8Array(fileBuffer)], { type: mimeType }), fileName) + + const response = await fetch(`${SQUARE_BASE_URL}/v2/catalog/images`, { + method: 'POST', + headers: { + Authorization: `Bearer ${validatedData.accessToken}`, + 'Square-Version': SQUARE_API_VERSION, + }, + body: formData, + }) + + if (!response.ok) { + const errorText = await response.text() + let detail: string | undefined + try { + detail = JSON.parse(errorText)?.errors?.[0]?.detail + } catch { + detail = undefined + } + logger.error(`[${requestId}] Square API error:`, { status: response.status, body: errorText }) + return NextResponse.json( + { + success: false, + error: detail || `Failed to upload catalog image (HTTP ${response.status})`, + }, + { status: response.status } + ) + } + + const data = await response.json() + const object = data.image ?? {} + + return NextResponse.json({ + success: true, + output: { + object, + metadata: { + id: object.id ?? '', + type: object.type ?? null, + version: object.version ?? null, + }, + }, + }) + } catch (error) { + logger.error(`[${requestId}] Unexpected error:`, error) + return NextResponse.json( + { success: false, error: getErrorMessage(error, 'Unknown error') }, + { status: 500 } + ) + } +}) diff --git a/apps/sim/app/api/tools/video/route.ts b/apps/sim/app/api/tools/video/route.ts index 9980121ed4c..b98d4fed2c5 100644 --- a/apps/sim/app/api/tools/video/route.ts +++ b/apps/sim/app/api/tools/video/route.ts @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { type NextRequest, NextResponse } from 'next/server' import { videoProviders, videoToolContract } from '@/lib/api/contracts/tools/media/video' import { getValidationErrorMessage, parseRequest, validationErrorResponse } from '@/lib/api/server' @@ -1081,10 +1082,6 @@ function formatFalAIDuration( return String(duration) } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function getStringProperty( record: Record | undefined, key: string @@ -1159,7 +1156,7 @@ function getFalAIValidationError( function getFalAIErrorMessage(error: unknown): string { if (typeof error === 'string') return error - if (isRecord(error)) return getStringProperty(error, 'message') || JSON.stringify(error) + if (isRecordLike(error)) return getStringProperty(error, 'message') || JSON.stringify(error) return 'Unknown error' } @@ -1236,7 +1233,7 @@ async function generateWithFalAI( } const createData = await readVideoJson(createResponse, 'Fal.ai queue response') - if (!isRecord(createData)) { + if (!isRecordLike(createData)) { throw new Error('Invalid Fal.ai queue response') } @@ -1273,7 +1270,7 @@ async function generateWithFalAI( } const statusData = await readVideoJson(statusResponse, 'Fal.ai status response') - if (!isRecord(statusData)) { + if (!isRecordLike(statusData)) { throw new Error('Invalid Fal.ai status response') } @@ -1300,12 +1297,12 @@ async function generateWithFalAI( } const resultData = await readVideoJson(resultResponse, 'Fal.ai result response') - if (!isRecord(resultData)) { + if (!isRecordLike(resultData)) { throw new Error('Invalid Fal.ai result response') } - const videoOutput = isRecord(resultData.video) ? resultData.video : undefined - const fallbackOutput = isRecord(resultData.output) ? resultData.output : undefined + const videoOutput = isRecordLike(resultData.video) ? resultData.video : undefined + const fallbackOutput = isRecordLike(resultData.output) ? resultData.output : undefined const videoUrl = getStringProperty(videoOutput, 'url') || getStringProperty(fallbackOutput, 'url') if (!videoUrl) { diff --git a/apps/sim/app/api/workspaces/[id]/owner-billing/route.test.ts b/apps/sim/app/api/workspaces/[id]/owner-billing/route.test.ts new file mode 100644 index 00000000000..2ae727ae92b --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/owner-billing/route.test.ts @@ -0,0 +1,80 @@ +/** + * @vitest-environment node + */ +import { createMockRequest } from '@sim/testing' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockGetSession, mockGetUserEntityPermissions, mockGetWorkspaceOwnerSubscriptionAccess } = + vi.hoisted(() => ({ + mockGetSession: vi.fn(), + mockGetUserEntityPermissions: vi.fn(), + mockGetWorkspaceOwnerSubscriptionAccess: vi.fn(), + })) + +vi.mock('@/lib/auth', () => ({ + auth: { api: { getSession: vi.fn() } }, + getSession: mockGetSession, +})) + +vi.mock('@/lib/workspaces/permissions/utils', () => ({ + getUserEntityPermissions: mockGetUserEntityPermissions, +})) + +vi.mock('@/lib/billing/core/workspace-access', () => ({ + getWorkspaceOwnerSubscriptionAccess: mockGetWorkspaceOwnerSubscriptionAccess, +})) + +import { GET } from '@/app/api/workspaces/[id]/owner-billing/route' + +const WORKSPACE_ID = 'ws-1' + +const PAID_ACCESS = { + plan: 'team_25000', + status: 'active', + isPaid: true, + isPro: false, + isTeam: true, + isEnterprise: false, + isOrgScoped: true, + organizationId: 'org-1', +} + +function buildParams() { + return { params: Promise.resolve({ id: WORKSPACE_ID }) } +} + +async function callGet() { + const request = createMockRequest('GET') + const response = await GET(request, buildParams()) + return { status: response.status, body: await response.json() } +} + +describe('GET /api/workspaces/[id]/owner-billing', () => { + beforeEach(() => { + vi.clearAllMocks() + mockGetSession.mockResolvedValue({ user: { id: 'u-1' } }) + mockGetUserEntityPermissions.mockResolvedValue('read') + mockGetWorkspaceOwnerSubscriptionAccess.mockResolvedValue(PAID_ACCESS) + }) + + it('returns 401 when unauthenticated', async () => { + mockGetSession.mockResolvedValue(null) + const { status } = await callGet() + expect(status).toBe(401) + expect(mockGetWorkspaceOwnerSubscriptionAccess).not.toHaveBeenCalled() + }) + + it('returns 404 when the caller has no workspace access', async () => { + mockGetUserEntityPermissions.mockResolvedValue(null) + const { status } = await callGet() + expect(status).toBe(404) + expect(mockGetWorkspaceOwnerSubscriptionAccess).not.toHaveBeenCalled() + }) + + it('returns the workspace owner subscription access for a member', async () => { + const { status, body } = await callGet() + expect(status).toBe(200) + expect(body).toEqual(PAID_ACCESS) + expect(mockGetWorkspaceOwnerSubscriptionAccess).toHaveBeenCalledWith(WORKSPACE_ID) + }) +}) diff --git a/apps/sim/app/api/workspaces/[id]/owner-billing/route.ts b/apps/sim/app/api/workspaces/[id]/owner-billing/route.ts new file mode 100644 index 00000000000..6766c3351a4 --- /dev/null +++ b/apps/sim/app/api/workspaces/[id]/owner-billing/route.ts @@ -0,0 +1,35 @@ +import type { NextRequest } from 'next/server' +import { NextResponse } from 'next/server' +import { getWorkspaceOwnerBillingContract } from '@/lib/api/contracts/workspaces' +import { parseRequest } from '@/lib/api/server' +import { getSession } from '@/lib/auth' +import { getWorkspaceOwnerSubscriptionAccess } from '@/lib/billing/core/workspace-access' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' + +/** + * Subscription access state of the workspace's billed account — the workspace- + * scoped counterpart to the viewer `/api/billing`. Lets the UI gate workspace + * features (e.g. the deploy modal) on the owner's plan rather than the viewer's, + * so a free member of a paid workspace isn't shown an upgrade wall. + */ +export const GET = withRouteHandler( + async (req: NextRequest, context: { params: Promise<{ id: string }> }) => { + const session = await getSession() + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const parsed = await parseRequest(getWorkspaceOwnerBillingContract, req, context) + if (!parsed.success) return parsed.response + const { id: workspaceId } = parsed.data.params + + const permission = await getUserEntityPermissions(session.user.id, 'workspace', workspaceId) + if (!permission) { + return NextResponse.json({ error: 'Not found' }, { status: 404 }) + } + + const ownerAccess = await getWorkspaceOwnerSubscriptionAccess(workspaceId) + return NextResponse.json(ownerAccess) + } +) diff --git a/apps/sim/app/api/workspaces/invitations/batch/route.ts b/apps/sim/app/api/workspaces/invitations/batch/route.ts index b43a45bade0..02dc504458a 100644 --- a/apps/sim/app/api/workspaces/invitations/batch/route.ts +++ b/apps/sim/app/api/workspaces/invitations/batch/route.ts @@ -1,10 +1,10 @@ import { createLogger } from '@sim/logger' +import { normalizeEmail } from '@sim/utils/string' import { type NextRequest, NextResponse } from 'next/server' import { batchWorkspaceInvitationsContract } from '@/lib/api/contracts/invitations' import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { normalizeEmail } from '@/lib/invitations/core' import { createWorkspaceInvitation, prepareWorkspaceInvitationContext, diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/user-input/components/constants.ts b/apps/sim/app/workspace/[workspaceId]/home/components/user-input/components/constants.ts index 9fb5b05d04a..a1065032200 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/user-input/components/constants.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/components/user-input/components/constants.ts @@ -47,27 +47,25 @@ export interface PlusMenuHandle { /** * Box and typography shared by the textarea and its mirror overlay — both must * produce identical line wrapping so the overlay text sits exactly over the - * (transparent) textarea text. The scale is the canonical chip text-field - * scale ({@link ChipTextarea}: `text-sm`, default tracking), so the editor - * reads identically in the chat input and inside chip modals — one size, - * everywhere. + * (transparent) textarea text. The scale is the chat input's native prompt + * scale (`text-[15px]`, `-0.015em` tracking); the task modal's body inherits it + * so the editor reads the same whether it's the chat input or inside the modal. */ const FIELD_MIRROR_CLASSES = cn( - 'm-0 box-border min-h-[20px] w-full break-words [overflow-wrap:anywhere] border-0 bg-transparent', - 'px-1 py-1 font-body text-sm leading-[20px]' + 'm-0 box-border min-h-[24px] w-full break-words [overflow-wrap:anywhere] border-0 bg-transparent', + 'px-1 py-1 font-body text-[15px] leading-[24px] tracking-[-0.015em]' ) /** * The textarea grows to its full content height (`h-auto`, no internal scroll); * the shared scroller clips and scrolls it. Its text is transparent so the - * mirror overlay shows through; only the caret paints. The placeholder uses - * the canonical `--text-muted`, matching every other chip text field. + * mirror overlay shows through; only the caret paints. */ export const TEXTAREA_BASE_CLASSES = cn( FIELD_MIRROR_CLASSES, 'block h-auto resize-none overflow-hidden', 'text-transparent caret-[var(--text-primary)] outline-none', - 'placeholder:text-[var(--text-muted)]', + 'placeholder:font-[380] placeholder:text-[var(--text-subtle)]', 'focus-visible:ring-0 focus-visible:ring-offset-0' ) diff --git a/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/index.ts b/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/index.ts index 5be3244a128..e0b9c3ff895 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/index.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/index.ts @@ -8,4 +8,4 @@ export { type StreamLoopOptions, type StreamLoopState, } from './stream-context' -export { finalizeResidualToolCalls, isRecord } from './stream-helpers' +export { finalizeResidualToolCalls } from './stream-helpers' diff --git a/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/stream-helpers.ts b/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/stream-helpers.ts index 437d7c73a0e..2c438e0c858 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/stream-helpers.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/hooks/stream/stream-helpers.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' import { resolveStreamToolOutcome } from '@/lib/copilot/chat/stream-tool-outcome' import type { MothershipStreamV1ToolUI } from '@/lib/copilot/generated/mothership-stream-v1' import { @@ -81,12 +82,8 @@ export type ToolResultPhasePayload = { success?: boolean } -export function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - export function asPayloadRecord(value: unknown): StreamPayload | undefined { - return isRecord(value) ? value : undefined + return isRecordLike(value) ? value : undefined } export function getToolUI(ui?: MothershipStreamV1ToolUI): StreamToolUI | undefined { diff --git a/apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts b/apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts index 53b75ebe0f6..5374c77b416 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts +++ b/apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts @@ -3,6 +3,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage, toError } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { generateId, generateShortId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { useQueryClient } from '@tanstack/react-query' import { usePathname, useRouter } from 'next/navigation' import { requestJson } from '@/lib/api/client/request' @@ -60,7 +61,6 @@ import { createStreamLoopContext, dispatchStreamEvent, finalizeResidualToolCalls, - isRecord, } from '@/app/workspace/[workspaceId]/home/hooks/stream' import { fetchMothershipChatHistory, @@ -255,7 +255,7 @@ async function sleepWithAbort(ms: number, signal?: AbortSignal) { } function isFileAttachmentForApi(value: unknown): value is FileAttachmentForApi { - if (!isRecord(value)) return false + if (!isRecordLike(value)) return false return ( typeof value.id === 'string' && typeof value.key === 'string' && @@ -268,7 +268,7 @@ function isFileAttachmentForApi(value: unknown): value is FileAttachmentForApi { } function isChatContext(value: unknown): value is ChatContext { - if (!isRecord(value) || typeof value.kind !== 'string' || typeof value.label !== 'string') { + if (!isRecordLike(value) || typeof value.kind !== 'string' || typeof value.label !== 'string') { return false } @@ -486,14 +486,14 @@ function isStreamSchemaValidationError(error: unknown): error is StreamSchemaVal } function parseStreamBatchResponse(value: unknown): StreamBatchResponse { - if (!isRecord(value)) { + if (!isRecordLike(value)) { throw new Error('Invalid stream batch response') } const rawEvents = Array.isArray(value.events) ? value.events : [] const events: StreamBatchEvent[] = [] for (const [index, entry] of rawEvents.entries()) { - if (!isRecord(entry)) { + if (!isRecordLike(entry)) { throw createBatchSchemaValidationError(`Reconnect batch event ${index + 1} is not an object.`) } if ( @@ -3761,21 +3761,21 @@ export function useChat( }), }) const payload: unknown = await res.json().catch(() => null) - if (isRecord(payload) && payload.aborted === true) { + if (isRecordLike(payload) && payload.aborted === true) { abortSucceeded = true } if (!res.ok) { - if (isRecord(payload) && payload.settled === false) { + if (isRecordLike(payload) && payload.settled === false) { return false } throw new Error( - isRecord(payload) && typeof payload.error === 'string' + isRecordLike(payload) && typeof payload.error === 'string' ? payload.error : 'Failed to abort previous response' ) } abortSucceeded = true - return isRecord(payload) && payload.settled === true + return isRecordLike(payload) && payload.settled === true } const abortPromise = sid ? postAbortRequest(resolvedChatId).then((settled) => { diff --git a/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-control.tsx b/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-control.tsx deleted file mode 100644 index 54cc65d5720..00000000000 --- a/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-control.tsx +++ /dev/null @@ -1,131 +0,0 @@ -'use client' - -import { format } from 'date-fns' -import { ChipDatePicker, ChipDropdown, ChipInput, RefreshCw } from '@/components/emcn' -import type { Recurrence } from '@/app/workspace/[workspaceId]/scheduled-tasks/utils/recurrence' - -const WEEKDAY_PRESET = [1, 2, 3, 4, 5] -/** Seed count when the user first chooses "ends after N runs". */ -const DEFAULT_END_AFTER_COUNT = 10 - -/** The frequency presets the dropdown authors, keyed by a synthetic option value. */ -type FrequencyOption = 'once' | 'daily' | 'weekly' | 'weekdays' | 'monthly' | 'custom' - -function isWeekdayPreset(weekdays: number[]): boolean { - return ( - weekdays.length === WEEKDAY_PRESET.length && WEEKDAY_PRESET.every((d) => weekdays.includes(d)) - ) -} - -/** Collapses a recurrence into the single dropdown value that represents it. */ -function frequencyOptionFor(recurrence: Recurrence): FrequencyOption { - if (recurrence.frequency === 'weekly') - return isWeekdayPreset(recurrence.weekdays) ? 'weekdays' : 'weekly' - return recurrence.frequency -} - -interface RecurrenceControlProps { - recurrence: Recurrence - onChange: (recurrence: Recurrence) => void - /** The launch day, so weekly/monthly labels name the weekday and day-of-month. */ - launchDate: string -} - -/** - * The repeat + end controls for a scheduled task, modeled on a calendar app's - * recurrence row: a frequency preset and — when the task repeats — how it ends - * (never, on a date, or after N runs). - */ -export function RecurrenceControl({ recurrence, onChange, launchDate }: RecurrenceControlProps) { - const launch = new Date(`${launchDate}T00:00`) - - const frequencyOptions = [ - { value: 'once', label: 'Once' }, - { value: 'daily', label: 'Daily' }, - { value: 'weekly', label: `Weekly on ${format(launch, 'EEE')}` }, - { value: 'weekdays', label: 'Weekdays' }, - { value: 'monthly', label: `Monthly on the ${format(launch, 'do')}` }, - ...(recurrence.frequency === 'custom' ? [{ value: 'custom', label: 'Custom' }] : []), - ] - - const handleFrequencyChange = (value: string) => { - const option = value as FrequencyOption - switch (option) { - case 'once': - onChange({ frequency: 'once', weekdays: [], end: { type: 'never' } }) - return - case 'daily': - onChange({ ...recurrence, frequency: 'daily', weekdays: [] }) - return - case 'weekly': - onChange({ ...recurrence, frequency: 'weekly', weekdays: [launch.getDay()] }) - return - case 'weekdays': - onChange({ ...recurrence, frequency: 'weekly', weekdays: [...WEEKDAY_PRESET] }) - return - case 'monthly': - onChange({ ...recurrence, frequency: 'monthly', weekdays: [] }) - return - case 'custom': - onChange({ ...recurrence, frequency: 'custom' }) - } - } - - const handleEndChange = (value: string) => { - if (value === 'never') onChange({ ...recurrence, end: { type: 'never' } }) - else if (value === 'on') - onChange({ ...recurrence, end: { type: 'on', date: format(launch, 'yyyy-MM-dd') } }) - else { - const count = recurrence.end.type === 'after' ? recurrence.end.count : DEFAULT_END_AFTER_COUNT - onChange({ ...recurrence, end: { type: 'after', count } }) - } - } - - return ( -
- - - {recurrence.frequency !== 'once' && ( - - )} - - {recurrence.frequency !== 'once' && recurrence.end.type === 'on' && ( - onChange({ ...recurrence, end: { type: 'on', date } })} - flush - /> - )} - - {recurrence.frequency !== 'once' && recurrence.end.type === 'after' && ( - { - const count = Math.max(1, Math.floor(Number(event.target.value) || 1)) - onChange({ ...recurrence, end: { type: 'after', count } }) - }} - endAdornment={runs} - /> - )} -
- ) -} diff --git a/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-section.tsx b/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-section.tsx new file mode 100644 index 00000000000..d74ca387fb0 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-section.tsx @@ -0,0 +1,185 @@ +'use client' + +import { useRef } from 'react' +import { format } from 'date-fns' +import { ChipDatePicker, ChipModalField, ChipModalSeparator, Switch } from '@/components/emcn' +import type { + Recurrence, + RecurrenceFrequency, +} from '@/app/workspace/[workspaceId]/scheduled-tasks/utils/recurrence' + +const WEEKDAY_PRESET = [1, 2, 3, 4, 5] +/** Seed count when the user first chooses "ends after N runs". */ +const DEFAULT_END_AFTER_COUNT = 10 +/** Cadence a task falls back to when the user first flips on recurrence. */ +const DEFAULT_RECURRING_FREQUENCY = 'daily' + +/** The frequency presets the dropdown authors, keyed by a synthetic option value. */ +type FrequencyOption = 'daily' | 'weekly' | 'weekdays' | 'monthly' | 'custom' + +function isWeekdayPreset(weekdays: number[]): boolean { + return ( + weekdays.length === WEEKDAY_PRESET.length && WEEKDAY_PRESET.every((d) => weekdays.includes(d)) + ) +} + +/** Collapses a recurring recurrence into the single dropdown value that represents it. */ +function frequencyOptionFor(recurrence: Recurrence): FrequencyOption { + if (recurrence.frequency === 'weekly') + return isWeekdayPreset(recurrence.weekdays) ? 'weekdays' : 'weekly' + // Exhaustiveness fallback: callers gate on `isRecurring`, so `once` never + // reaches here at runtime, but the dropdown can't represent it — mapping it to + // a recurring default keeps the return type `FrequencyOption` without a cast. + if (recurrence.frequency === 'once') return DEFAULT_RECURRING_FREQUENCY + return recurrence.frequency +} + +interface RecurrenceSectionProps { + recurrence: Recurrence + onChange: (recurrence: Recurrence) => void + /** The launch day, so weekly/monthly labels name the weekday and day-of-month. */ + launchDate: string +} + +/** + * The repeat + end controls for a scheduled task, rendered as a body section + * below the prompt: a "Recurring" {@link Switch} that toggles a one-time launch + * into a repeat, and — once on — the frequency preset and how it ends (never, on + * a date, or after N runs). + * + * Composed as a sibling between the prompt body and footer; it owns its own + * leading separator and mirrors {@link ChipModalBody}'s spacing + * (`gap-4 px-2 pt-4 pb-4.5`) so every {@link ChipModalField} lands at the same + * effective `px-4` as the modal header/footer — no changes to the `ChipModal` + * primitives. + */ +export function RecurrenceSection({ recurrence, onChange, launchDate }: RecurrenceSectionProps) { + /** + * The cadence to reinstate when recurrence is toggled back on. Toggling off + * collapses `frequency` to `once`, dropping which preset was active, so the + * last recurring cadence is cached here and restored — a paused "Weekly on + * Mon" returns as weekly, not silently reset to daily. Written during render + * (an idempotent cache), so it is current before the toggle handler reads it. + */ + const lastRecurringFrequency = useRef(DEFAULT_RECURRING_FREQUENCY) + if (recurrence.frequency !== 'once') lastRecurringFrequency.current = recurrence.frequency + + const launch = new Date(`${launchDate}T00:00`) + const isRecurring = recurrence.frequency !== 'once' + + const frequencyOptions = [ + { value: 'daily', label: 'Daily' }, + { value: 'weekly', label: `Weekly on ${format(launch, 'EEE')}` }, + { value: 'weekdays', label: 'Weekdays' }, + { value: 'monthly', label: `Monthly on the ${format(launch, 'do')}` }, + ...(recurrence.frequency === 'custom' ? [{ value: 'custom', label: 'Custom' }] : []), + ] + + /** + * Flips the one-time launch into a repeat and back. Toggling off keeps the + * recurrence shape (weekdays, end, and a passed-through `custom` cron) on the + * object and only collapses `frequency` to `once`; toggling back on reinstates + * the remembered cadence, so neither a weekly preset nor a conversationally + * authored custom cron is silently rewritten to daily. + */ + const handleRecurringToggle = (checked: boolean) => { + onChange({ ...recurrence, frequency: checked ? lastRecurringFrequency.current : 'once' }) + } + + const handleFrequencyChange = (value: string) => { + const option = value as FrequencyOption + switch (option) { + case 'daily': + onChange({ ...recurrence, frequency: 'daily', weekdays: [], cron: undefined }) + return + case 'weekly': + onChange({ + ...recurrence, + frequency: 'weekly', + weekdays: [launch.getDay()], + cron: undefined, + }) + return + case 'weekdays': + onChange({ + ...recurrence, + frequency: 'weekly', + weekdays: [...WEEKDAY_PRESET], + cron: undefined, + }) + return + case 'monthly': + onChange({ ...recurrence, frequency: 'monthly', weekdays: [], cron: undefined }) + return + case 'custom': + onChange({ ...recurrence, frequency: 'custom' }) + } + } + + const handleEndChange = (value: string) => { + if (value === 'never') onChange({ ...recurrence, end: { type: 'never' } }) + else if (value === 'on') + onChange({ ...recurrence, end: { type: 'on', date: format(launch, 'yyyy-MM-dd') } }) + else { + const count = recurrence.end.type === 'after' ? recurrence.end.count : DEFAULT_END_AFTER_COUNT + onChange({ ...recurrence, end: { type: 'after', count } }) + } + } + + return ( +
+ +
+ + + + + {isRecurring && ( + <> + + + + + {recurrence.end.type === 'on' && ( + + onChange({ ...recurrence, end: { type: 'on', date } })} + fullWidth + /> + + )} + + {recurrence.end.type === 'after' && ( + { + const count = Math.max(1, Math.floor(Number(value) || 1)) + onChange({ ...recurrence, end: { type: 'after', count } }) + }} + /> + )} + + )} +
+
+ ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/task-modal.tsx b/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/task-modal.tsx index 829423504f3..0d05b31fdd9 100644 --- a/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/task-modal.tsx +++ b/apps/sim/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/task-modal.tsx @@ -18,7 +18,7 @@ import { PromptEditor, usePromptEditor, } from '@/app/workspace/[workspaceId]/home/components/user-input/components' -import { RecurrenceControl } from '@/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-control' +import { RecurrenceSection } from '@/app/workspace/[workspaceId]/scheduled-tasks/components/task-modal/recurrence-section' import type { CalendarSlot } from '@/app/workspace/[workspaceId]/scheduled-tasks/hooks/use-calendar' import { DEFAULT_RECURRENCE, @@ -117,10 +117,10 @@ interface TaskModalProps { /** * The "schedule a task" modal, shared by create (blank, or pre-filled from a - * duplicate) and edit (seeded from a task's schedule). The body is one prompt - * surface — the chat input's editor, so `@` mentions resources and `/` invokes - * skills exactly like talking to Sim — and the footer carries the recurrence, - * launch date/time, and (edit only) Delete. + * duplicate) and edit (seeded from a task's schedule). The body is the chat + * input's editor — so `@` mentions resources and `/` invokes skills exactly like + * talking to Sim — followed by the recurrence section; the footer carries the + * launch date/time and (edit only) Delete. */ export function TaskModal({ open, @@ -296,10 +296,11 @@ function TaskModalContent({ } /** - * Footer secondary actions. Delete is disabled while `submitting` because it - * bypasses the dismiss guard — it closes the modal via `closeTask`, not the - * guarded `onOpenChange` — so without the lock an in-flight edit and a delete - * could run against the same task at once. + * Footer secondary actions — the launch date/time pickers and (edit only) + * Delete. Delete is disabled while `submitting` because it bypasses the + * dismiss guard — it closes the modal via `closeTask`, not the guarded + * `onOpenChange` — so without the lock an in-flight edit and a delete could + * run against the same task at once. Recurrence lives in the body, not here. */ const secondaryActions: ChipModalFooterSlotAction[] = [ ...(edit && onRequestDelete @@ -312,15 +313,6 @@ function TaskModalContent({ }, ] : []), - { - custom: ( - - ), - }, { custom: }, { custom: }, ] @@ -338,6 +330,7 @@ function TaskModalContent({ onSubmit={handleSubmit} /> + { const fieldType = inferType(value) const fieldValue = diff --git a/apps/sim/background/webhook-execution.ts b/apps/sim/background/webhook-execution.ts index 41048f9208b..7e942e3f456 100644 --- a/apps/sim/background/webhook-execution.ts +++ b/apps/sim/background/webhook-execution.ts @@ -4,6 +4,7 @@ import { account, webhook } from '@sim/db/schema' import { createLogger, runWithRequestContext } from '@sim/logger' import { toError } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { task } from '@trigger.dev/sdk' import { eq } from 'drizzle-orm' import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types' @@ -37,12 +38,8 @@ const logger = createLogger('TriggerWebhookExecution') type WebhookAttachmentInput = Omit & { data: unknown } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function isSerializedBuffer(value: unknown): value is { type: 'Buffer'; data: number[] } { - return isRecord(value) && value.type === 'Buffer' && Array.isArray(value.data) + return isRecordLike(value) && value.type === 'Buffer' && Array.isArray(value.data) } function hasSupportedAttachmentData(value: unknown): boolean { @@ -90,7 +87,7 @@ function toAttachmentBuffer(data: unknown, name: string): Buffer { } function isWebhookAttachmentInput(value: unknown): value is WebhookAttachmentInput { - if (!isRecord(value)) { + if (!isRecordLike(value)) { return false } diff --git a/apps/sim/blocks/blocks/context_dev.ts b/apps/sim/blocks/blocks/context_dev.ts new file mode 100644 index 00000000000..26298c41ef8 --- /dev/null +++ b/apps/sim/blocks/blocks/context_dev.ts @@ -0,0 +1,940 @@ +import { ContextDevIcon } from '@/components/icons' +import type { BlockConfig, BlockMeta } from '@/blocks/types' +import { AuthMode, IntegrationType } from '@/blocks/types' +import type { ContextDevScrapeMarkdownResponse } from '@/tools/context_dev/types' + +/** Operations whose primary input is a full page URL. */ +const URL_OPS = [ + 'scrape_markdown', + 'scrape_html', + 'scrape_images', + 'screenshot', + 'crawl', + 'extract', + 'extract_product', +] +/** Operations whose primary input is a bare domain. */ +const DOMAIN_OPS = [ + 'map', + 'get_brand', + 'get_brand_simplified', + 'extract_products', + 'scrape_fonts', + 'scrape_styleguide', + 'prefetch_domain', +] +/** Classification operations keyed on a domain-or-name input. */ +const CLASSIFY_OPS = ['classify_naics', 'classify_sic'] +/** Brand operations that accept language/speed tuning. */ +const BRAND_LANG_OPS = [ + 'get_brand', + 'get_brand_by_name', + 'get_brand_by_email', + 'get_brand_by_ticker', + 'identify_transaction', +] +/** Operations that accept a cache max-age. */ +const MAX_AGE_OPS = [ + 'scrape_markdown', + 'scrape_html', + 'scrape_images', + 'screenshot', + 'crawl', + 'extract', + 'extract_product', + 'extract_products', + 'scrape_fonts', + 'scrape_styleguide', + 'get_brand', + 'get_brand_by_name', + 'get_brand_by_email', + 'get_brand_by_ticker', + 'get_brand_simplified', +] +/** Operations that accept a post-load browser wait. */ +const WAIT_FOR_OPS = ['scrape_markdown', 'scrape_html', 'scrape_images', 'screenshot', 'crawl'] + +/** + * Coerces a value that may be a number or numeric string into a number, or undefined. + */ +function toNumber(value: unknown): number | undefined { + if (value === undefined || value === null || value === '') return undefined + const parsed = Number(value) + return Number.isNaN(parsed) ? undefined : parsed +} + +/** + * Parses a value that may already be an array or a JSON-encoded array string. + */ +function toStringArray(value: unknown): string[] | undefined { + if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string') + if (typeof value === 'string' && value.trim() !== '') { + try { + const parsed = JSON.parse(value) + if (Array.isArray(parsed)) return parsed.filter((v): v is string => typeof v === 'string') + } catch { + return value + .split(',') + .map((v) => v.trim()) + .filter(Boolean) + } + } + return undefined +} + +export const ContextDevBlock: BlockConfig = { + type: 'context_dev', + name: 'Context.dev', + description: 'Scrape, crawl, search, extract, and enrich web and brand data', + authMode: AuthMode.ApiKey, + longDescription: + 'Integrate Context.dev into the workflow. Scrape pages to markdown or HTML, capture screenshots, list images, crawl entire sites, map sitemaps, search the web, extract structured data and products, pull design systems, classify industries, and retrieve brand assets by domain, name, email, ticker, or transaction — all from one API.', + docsLink: 'https://docs.sim.ai/integrations/context_dev', + category: 'tools', + integrationType: IntegrationType.Search, + bgColor: '#ffffff', + icon: ContextDevIcon, + subBlocks: [ + { + id: 'operation', + title: 'Operation', + type: 'dropdown', + options: [ + { label: 'Scrape Markdown', id: 'scrape_markdown' }, + { label: 'Scrape HTML', id: 'scrape_html' }, + { label: 'Scrape Images', id: 'scrape_images' }, + { label: 'Screenshot', id: 'screenshot' }, + { label: 'Crawl Website', id: 'crawl' }, + { label: 'Map Sitemap', id: 'map' }, + { label: 'Web Search', id: 'search' }, + { label: 'Extract Structured Data', id: 'extract' }, + { label: 'Extract Product', id: 'extract_product' }, + { label: 'Extract Products', id: 'extract_products' }, + { label: 'Scrape Fonts', id: 'scrape_fonts' }, + { label: 'Scrape Styleguide', id: 'scrape_styleguide' }, + { label: 'Classify NAICS', id: 'classify_naics' }, + { label: 'Classify SIC', id: 'classify_sic' }, + { label: 'Get Brand by Domain', id: 'get_brand' }, + { label: 'Get Brand by Name', id: 'get_brand_by_name' }, + { label: 'Get Brand by Email', id: 'get_brand_by_email' }, + { label: 'Get Brand by Ticker', id: 'get_brand_by_ticker' }, + { label: 'Get Brand (Simplified)', id: 'get_brand_simplified' }, + { label: 'Identify Transaction', id: 'identify_transaction' }, + { label: 'Prefetch Domain', id: 'prefetch_domain' }, + { label: 'Prefetch by Email', id: 'prefetch_by_email' }, + ], + value: () => 'scrape_markdown', + }, + { + id: 'url', + title: 'Website URL', + type: 'short-input', + placeholder: 'https://example.com', + condition: { field: 'operation', value: URL_OPS }, + required: { field: 'operation', value: URL_OPS }, + }, + { + id: 'domain', + title: 'Domain', + type: 'short-input', + placeholder: 'example.com', + condition: { field: 'operation', value: DOMAIN_OPS }, + required: { field: 'operation', value: DOMAIN_OPS }, + }, + { + id: 'input', + title: 'Domain or Company Name', + type: 'short-input', + placeholder: 'example.com or Company Name', + condition: { field: 'operation', value: CLASSIFY_OPS }, + required: { field: 'operation', value: CLASSIFY_OPS }, + }, + { + id: 'query', + title: 'Search Query', + type: 'short-input', + placeholder: 'Enter your search query', + condition: { field: 'operation', value: 'search' }, + required: { field: 'operation', value: 'search' }, + }, + { + id: 'name', + title: 'Company Name', + type: 'short-input', + placeholder: 'Apple Inc', + condition: { field: 'operation', value: 'get_brand_by_name' }, + required: { field: 'operation', value: 'get_brand_by_name' }, + }, + { + id: 'email', + title: 'Work Email', + type: 'short-input', + placeholder: 'name@company.com', + condition: { field: 'operation', value: ['get_brand_by_email', 'prefetch_by_email'] }, + required: { field: 'operation', value: ['get_brand_by_email', 'prefetch_by_email'] }, + }, + { + id: 'ticker', + title: 'Stock Ticker', + type: 'short-input', + placeholder: 'AAPL', + condition: { field: 'operation', value: 'get_brand_by_ticker' }, + required: { field: 'operation', value: 'get_brand_by_ticker' }, + }, + { + id: 'transactionInfo', + title: 'Transaction Descriptor', + type: 'short-input', + placeholder: 'SQ *COFFEE SHOP 1234', + condition: { field: 'operation', value: 'identify_transaction' }, + required: { field: 'operation', value: 'identify_transaction' }, + }, + { + id: 'schema', + title: 'Extraction Schema', + type: 'code', + language: 'json', + placeholder: 'Enter a JSON schema describing the data to extract...', + condition: { field: 'operation', value: 'extract' }, + required: { field: 'operation', value: 'extract' }, + wandConfig: { + enabled: true, + maintainHistory: true, + prompt: `You are an expert at writing JSON Schemas for structured web data extraction. +Generate ONLY the JSON schema based on the user's request. +The output MUST be a single, valid JSON object, starting with { and ending with }. +Use standard JSON Schema properties (type, description, properties, items, required). + +Current schema: {context} + +Do not include any explanations, markdown formatting, or other text outside the JSON object.`, + placeholder: 'Describe the data structure you want to extract...', + generationType: 'json-schema', + }, + }, + { + id: 'instructions', + title: 'Instructions', + type: 'long-input', + placeholder: 'Optional guidance for which links to prioritize', + mode: 'advanced', + condition: { field: 'operation', value: 'extract' }, + }, + { + id: 'useMainContentOnly', + title: 'Only Main Content', + type: 'switch', + condition: { field: 'operation', value: ['scrape_markdown', 'scrape_html', 'crawl'] }, + }, + { + id: 'includeLinks', + title: 'Include Links', + type: 'switch', + condition: { field: 'operation', value: ['scrape_markdown', 'crawl'] }, + }, + { + id: 'includeImages', + title: 'Include Images', + type: 'switch', + condition: { field: 'operation', value: ['scrape_markdown', 'crawl'] }, + }, + { + id: 'includeFrames', + title: 'Include Frames', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: ['scrape_markdown', 'scrape_html'] }, + }, + { + id: 'fullScreenshot', + title: 'Full Page Screenshot', + type: 'switch', + condition: { field: 'operation', value: 'screenshot' }, + }, + { + id: 'handleCookiePopup', + title: 'Dismiss Cookie Popups', + type: 'switch', + condition: { field: 'operation', value: 'screenshot' }, + }, + { + id: 'markdownEnabled', + title: 'Scrape Results to Markdown', + type: 'switch', + condition: { field: 'operation', value: 'search' }, + }, + { + id: 'tickerExchange', + title: 'Exchange', + type: 'short-input', + placeholder: 'NASDAQ', + condition: { field: 'operation', value: 'get_brand_by_ticker' }, + }, + { + id: 'sicType', + title: 'SIC Taxonomy', + type: 'dropdown', + options: [ + { label: 'Original SIC', id: 'original_sic' }, + { label: 'Latest SEC', id: 'latest_sec' }, + ], + value: () => 'original_sic', + condition: { field: 'operation', value: 'classify_sic' }, + }, + { + id: 'freshness', + title: 'Freshness', + type: 'dropdown', + options: [ + { label: 'Last 24 Hours', id: 'last_24_hours' }, + { label: 'Last Week', id: 'last_week' }, + { label: 'Last Month', id: 'last_month' }, + { label: 'Last Year', id: 'last_year' }, + ], + mode: 'advanced', + condition: { field: 'operation', value: 'search' }, + }, + { + id: 'includeDomains', + title: 'Include Domains', + type: 'long-input', + placeholder: '["example.com", "docs.example.com"]', + mode: 'advanced', + condition: { field: 'operation', value: 'search' }, + }, + { + id: 'excludeDomains', + title: 'Exclude Domains', + type: 'long-input', + placeholder: '["spam.com"]', + mode: 'advanced', + condition: { field: 'operation', value: 'search' }, + }, + { + id: 'queryFanout', + title: 'Query Fan-out', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'search' }, + }, + { + id: 'factCheck', + title: 'Fact Check', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'extract' }, + }, + { + id: 'followSubdomains', + title: 'Follow Subdomains', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: ['crawl', 'extract'] }, + }, + { + id: 'maxPages', + title: 'Max Pages', + type: 'short-input', + placeholder: '100', + mode: 'advanced', + condition: { field: 'operation', value: 'crawl' }, + }, + { + id: 'extractMaxPages', + title: 'Max Pages', + type: 'short-input', + placeholder: '5', + mode: 'advanced', + condition: { field: 'operation', value: 'extract' }, + }, + { + id: 'maxDepth', + title: 'Max Depth', + type: 'short-input', + placeholder: 'Maximum link depth', + mode: 'advanced', + condition: { field: 'operation', value: ['crawl', 'extract'] }, + }, + { + id: 'maxProducts', + title: 'Max Products', + type: 'short-input', + placeholder: '12', + mode: 'advanced', + condition: { field: 'operation', value: 'extract_products' }, + }, + { + id: 'urlRegex', + title: 'URL Regex', + type: 'short-input', + placeholder: 'Regex to filter URLs', + mode: 'advanced', + condition: { field: 'operation', value: ['crawl', 'map'] }, + }, + { + id: 'maxLinks', + title: 'Max Links', + type: 'short-input', + placeholder: '10000', + mode: 'advanced', + condition: { field: 'operation', value: 'map' }, + }, + { + id: 'viewportWidth', + title: 'Viewport Width', + type: 'short-input', + placeholder: '1920', + mode: 'advanced', + condition: { field: 'operation', value: 'screenshot' }, + }, + { + id: 'viewportHeight', + title: 'Viewport Height', + type: 'short-input', + placeholder: '1080', + mode: 'advanced', + condition: { field: 'operation', value: 'screenshot' }, + }, + { + id: 'enrichResolution', + title: 'Enrich: Resolution', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'scrape_images' }, + }, + { + id: 'enrichHostedUrl', + title: 'Enrich: Hosted URL', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'scrape_images' }, + }, + { + id: 'enrichClassification', + title: 'Enrich: Classification', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'scrape_images' }, + }, + { + id: 'minResults', + title: 'Min Results', + type: 'short-input', + placeholder: '1', + mode: 'advanced', + condition: { field: 'operation', value: CLASSIFY_OPS }, + }, + { + id: 'maxResults', + title: 'Max Results', + type: 'short-input', + placeholder: '5', + mode: 'advanced', + condition: { field: 'operation', value: CLASSIFY_OPS }, + }, + { + id: 'countryGl', + title: 'Country Code', + type: 'short-input', + placeholder: 'us', + mode: 'advanced', + condition: { field: 'operation', value: ['get_brand_by_name', 'identify_transaction'] }, + }, + { + id: 'city', + title: 'City', + type: 'short-input', + placeholder: 'San Francisco', + mode: 'advanced', + condition: { field: 'operation', value: 'identify_transaction' }, + }, + { + id: 'mcc', + title: 'Merchant Category Code', + type: 'short-input', + placeholder: '5812', + mode: 'advanced', + condition: { field: 'operation', value: 'identify_transaction' }, + }, + { + id: 'phone', + title: 'Phone', + type: 'short-input', + placeholder: '14155551234', + mode: 'advanced', + condition: { field: 'operation', value: 'identify_transaction' }, + }, + { + id: 'highConfidenceOnly', + title: 'High Confidence Only', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: 'identify_transaction' }, + }, + { + id: 'forceLanguage', + title: 'Force Language', + type: 'short-input', + placeholder: 'e.g., en, es, fr', + mode: 'advanced', + condition: { field: 'operation', value: BRAND_LANG_OPS }, + }, + { + id: 'maxSpeed', + title: 'Max Speed', + type: 'switch', + mode: 'advanced', + condition: { field: 'operation', value: BRAND_LANG_OPS }, + }, + { + id: 'waitForMs', + title: 'Wait For (ms)', + type: 'short-input', + placeholder: '0', + mode: 'advanced', + condition: { field: 'operation', value: WAIT_FOR_OPS }, + }, + { + id: 'stopAfterMs', + title: 'Stop After (ms)', + type: 'short-input', + placeholder: '80000', + mode: 'advanced', + condition: { field: 'operation', value: ['crawl', 'extract'] }, + }, + { + id: 'maxAgeMs', + title: 'Cache Max Age (ms)', + type: 'short-input', + placeholder: '86400000', + mode: 'advanced', + condition: { field: 'operation', value: MAX_AGE_OPS }, + }, + { + id: 'timeoutMS', + title: 'Timeout (ms)', + type: 'short-input', + placeholder: '60000', + mode: 'advanced', + }, + { + id: 'apiKey', + title: 'API Key', + type: 'short-input', + placeholder: 'Enter your Context.dev API key', + password: true, + required: true, + }, + ], + tools: { + access: [ + 'context_dev_scrape_markdown', + 'context_dev_scrape_html', + 'context_dev_scrape_images', + 'context_dev_screenshot', + 'context_dev_crawl', + 'context_dev_map', + 'context_dev_search', + 'context_dev_extract', + 'context_dev_extract_product', + 'context_dev_extract_products', + 'context_dev_scrape_fonts', + 'context_dev_scrape_styleguide', + 'context_dev_classify_naics', + 'context_dev_classify_sic', + 'context_dev_get_brand', + 'context_dev_get_brand_by_name', + 'context_dev_get_brand_by_email', + 'context_dev_get_brand_by_ticker', + 'context_dev_get_brand_simplified', + 'context_dev_identify_transaction', + 'context_dev_prefetch_domain', + 'context_dev_prefetch_by_email', + ], + config: { + tool: (params) => + params.operation ? `context_dev_${params.operation}` : 'context_dev_scrape_markdown', + params: (params) => { + const { operation, apiKey } = params + const result: Record = { apiKey } + + const setBool = (key: string) => { + if (params[key] != null) result[key] = params[key] + } + const setNumber = (key: string, target = key) => { + const n = toNumber(params[key]) + if (n !== undefined) result[target] = n + } + const setString = (key: string, target = key) => { + if (params[key]) result[target] = params[key] + } + + switch (operation) { + case 'scrape_markdown': + setString('url') + setBool('useMainContentOnly') + setBool('includeLinks') + setBool('includeImages') + setBool('includeFrames') + setNumber('maxAgeMs') + setNumber('waitForMs') + setNumber('timeoutMS') + break + case 'scrape_html': + setString('url') + setBool('useMainContentOnly') + setBool('includeFrames') + setNumber('maxAgeMs') + setNumber('waitForMs') + setNumber('timeoutMS') + break + case 'scrape_images': + setString('url') + setNumber('maxAgeMs') + setNumber('waitForMs') + setNumber('timeoutMS') + setBool('enrichResolution') + setBool('enrichHostedUrl') + setBool('enrichClassification') + break + case 'screenshot': + setString('url') + setBool('fullScreenshot') + setBool('handleCookiePopup') + setNumber('viewportWidth') + setNumber('viewportHeight') + setNumber('maxAgeMs') + setNumber('waitForMs') + setNumber('timeoutMS') + break + case 'crawl': + setString('url') + setNumber('maxPages') + setNumber('maxDepth') + setString('urlRegex') + setBool('useMainContentOnly') + setBool('includeLinks') + setBool('includeImages') + setBool('followSubdomains') + setNumber('maxAgeMs') + setNumber('waitForMs') + setNumber('stopAfterMs') + setNumber('timeoutMS') + break + case 'map': + setString('domain') + setNumber('maxLinks') + setString('urlRegex') + setNumber('timeoutMS') + break + case 'search': { + setString('query') + const include = toStringArray(params.includeDomains) + if (include?.length) result.includeDomains = include + const exclude = toStringArray(params.excludeDomains) + if (exclude?.length) result.excludeDomains = exclude + setString('freshness') + setBool('queryFanout') + setBool('markdownEnabled') + setNumber('timeoutMS') + break + } + case 'extract': { + setString('url') + if (params.schema) { + if (typeof params.schema === 'object') { + result.schema = params.schema + } else if (typeof params.schema === 'string') { + try { + result.schema = JSON.parse(params.schema) + } catch { + throw new Error('Extraction schema must be valid JSON') + } + } + } + setString('instructions') + setBool('factCheck') + setBool('followSubdomains') + setNumber('extractMaxPages', 'maxPages') + setNumber('maxDepth') + setNumber('maxAgeMs') + setNumber('stopAfterMs') + setNumber('timeoutMS') + break + } + case 'extract_product': + setString('url') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'extract_products': + setString('domain') + setNumber('maxProducts') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'scrape_fonts': + setString('domain') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'scrape_styleguide': + setString('domain') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'classify_naics': + setString('input') + setNumber('minResults') + setNumber('maxResults') + setNumber('timeoutMS') + break + case 'classify_sic': + setString('input') + setString('sicType', 'type') + setNumber('minResults') + setNumber('maxResults') + setNumber('timeoutMS') + break + case 'get_brand': + setString('domain') + setString('forceLanguage') + setBool('maxSpeed') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'get_brand_by_name': + setString('name') + setString('countryGl') + setString('forceLanguage') + setBool('maxSpeed') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'get_brand_by_email': + setString('email') + setString('forceLanguage') + setBool('maxSpeed') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'get_brand_by_ticker': + setString('ticker') + setString('tickerExchange') + setString('forceLanguage') + setBool('maxSpeed') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'get_brand_simplified': + setString('domain') + setNumber('maxAgeMs') + setNumber('timeoutMS') + break + case 'identify_transaction': + setString('transactionInfo') + setString('countryGl') + setString('city') + setString('mcc') + setNumber('phone') + setBool('highConfidenceOnly') + setString('forceLanguage') + setBool('maxSpeed') + setNumber('timeoutMS') + break + case 'prefetch_domain': + setString('domain') + setNumber('timeoutMS') + break + case 'prefetch_by_email': + setString('email') + setNumber('timeoutMS') + break + } + + return result + }, + }, + }, + inputs: { + apiKey: { type: 'string', description: 'Context.dev API key' }, + operation: { type: 'string', description: 'Operation to perform' }, + url: { type: 'string', description: 'Target website or page URL' }, + domain: { type: 'string', description: 'Target domain' }, + input: { type: 'string', description: 'Domain or company name for classification' }, + query: { type: 'string', description: 'Web search query' }, + name: { type: 'string', description: 'Company name for brand lookup' }, + email: { type: 'string', description: 'Work email for brand lookup or prefetch' }, + ticker: { type: 'string', description: 'Stock ticker for brand lookup' }, + transactionInfo: { type: 'string', description: 'Transaction descriptor to identify' }, + schema: { type: 'json', description: 'JSON schema for structured extraction' }, + instructions: { type: 'string', description: 'Extraction guidance' }, + useMainContentOnly: { type: 'boolean', description: 'Return only main content' }, + includeLinks: { type: 'boolean', description: 'Preserve hyperlinks' }, + includeImages: { type: 'boolean', description: 'Include image references' }, + includeFrames: { type: 'boolean', description: 'Render iframe contents inline' }, + fullScreenshot: { type: 'boolean', description: 'Capture the full page' }, + handleCookiePopup: { type: 'boolean', description: 'Dismiss cookie banners' }, + markdownEnabled: { type: 'boolean', description: 'Scrape search results to markdown' }, + tickerExchange: { type: 'string', description: 'Stock exchange for the ticker' }, + sicType: { type: 'string', description: 'SIC taxonomy version' }, + freshness: { type: 'string', description: 'Search recency filter' }, + includeDomains: { type: 'json', description: 'Domains to allowlist in search' }, + excludeDomains: { type: 'json', description: 'Domains to blocklist in search' }, + queryFanout: { type: 'boolean', description: 'Expand query into variants' }, + factCheck: { type: 'boolean', description: 'Ground extracted values in page facts' }, + followSubdomains: { type: 'boolean', description: 'Follow subdomain links' }, + maxPages: { type: 'number', description: 'Maximum pages to crawl (1-500)' }, + extractMaxPages: { + type: 'number', + description: 'Maximum pages to analyze for extraction (1-50)', + }, + maxDepth: { type: 'number', description: 'Maximum link depth' }, + maxProducts: { type: 'number', description: 'Maximum products to extract' }, + urlRegex: { type: 'string', description: 'Regex to filter URLs' }, + maxLinks: { type: 'number', description: 'Maximum sitemap URLs' }, + viewportWidth: { type: 'number', description: 'Screenshot viewport width' }, + viewportHeight: { type: 'number', description: 'Screenshot viewport height' }, + enrichResolution: { type: 'boolean', description: 'Measure scraped image dimensions' }, + enrichHostedUrl: { type: 'boolean', description: 'Host scraped images and return URLs' }, + enrichClassification: { type: 'boolean', description: 'Classify scraped images by type' }, + minResults: { type: 'number', description: 'Minimum classification results' }, + maxResults: { type: 'number', description: 'Maximum classification results' }, + countryGl: { type: 'string', description: 'ISO country code hint' }, + city: { type: 'string', description: 'City hint for transaction lookup' }, + mcc: { type: 'string', description: 'Merchant category code' }, + phone: { type: 'number', description: 'Phone number from transaction' }, + highConfidenceOnly: { type: 'boolean', description: 'Require high-confidence match' }, + forceLanguage: { type: 'string', description: 'Override detected brand language' }, + maxSpeed: { type: 'boolean', description: 'Skip slow brand operations' }, + waitForMs: { type: 'number', description: 'Browser wait time in ms' }, + stopAfterMs: { type: 'number', description: 'Soft crawl time budget in ms' }, + maxAgeMs: { type: 'number', description: 'Cache max age in ms' }, + timeoutMS: { type: 'number', description: 'Request timeout in ms' }, + }, + outputs: { + markdown: { type: 'string', description: 'Scraped markdown content' }, + html: { type: 'string', description: 'Scraped raw HTML content' }, + type: { type: 'string', description: 'Detected content type or resolved input type' }, + url: { type: 'string', description: 'Resolved target URL' }, + file: { type: 'file', description: 'Stored screenshot image file' }, + screenshotUrl: { type: 'string', description: 'Public URL of the captured screenshot' }, + screenshotType: { type: 'string', description: 'Screenshot type (viewport or fullPage)' }, + domain: { type: 'string', description: 'Resolved domain' }, + width: { type: 'number', description: 'Screenshot width in pixels' }, + height: { type: 'number', description: 'Screenshot height in pixels' }, + success: { type: 'boolean', description: 'Whether the scrape succeeded' }, + images: { type: 'json', description: 'Discovered image assets' }, + results: { type: 'json', description: 'Crawl pages or search results' }, + metadata: { type: 'json', description: 'Crawl or extraction summary metadata' }, + urls: { type: 'json', description: 'Discovered sitemap URLs' }, + meta: { type: 'json', description: 'Sitemap discovery stats' }, + query: { type: 'string', description: 'The query that was searched' }, + status: { type: 'string', description: 'Operation status' }, + message: { type: 'string', description: 'Prefetch result message' }, + urlsAnalyzed: { type: 'json', description: 'URLs analyzed during extraction' }, + data: { type: 'json', description: 'Structured data extracted from the site' }, + isProductPage: { type: 'boolean', description: 'Whether the URL is a product page' }, + platform: { type: 'string', description: 'Detected commerce platform' }, + product: { type: 'json', description: 'Extracted single product details' }, + products: { type: 'json', description: 'Extracted product catalog' }, + fonts: { type: 'json', description: 'Fonts with usage statistics' }, + fontLinks: { type: 'json', description: 'Font family download links' }, + styleguide: { type: 'json', description: 'Design system (colors, typography, components)' }, + codes: { type: 'json', description: 'Matched industry classification codes' }, + classification: { type: 'string', description: 'SIC taxonomy version used' }, + brand: { type: 'json', description: 'Brand data (logos, colors, socials, industry)' }, + creditsConsumed: { type: 'number', description: 'Credits consumed by this request' }, + creditsRemaining: { type: 'number', description: 'Credits remaining on the API key' }, + }, +} + +export const ContextDevBlockMeta = { + tags: ['web-scraping', 'enrichment', 'automation'], + url: 'https://www.context.dev', + templates: [ + { + icon: ContextDevIcon, + title: 'Context.dev knowledge-base builder', + prompt: + 'Build a workflow that maps a documentation site with Context.dev, crawls each page to clean markdown, chunks and embeds the content, and upserts it into a knowledge base for an answering agent.', + modules: ['knowledge-base', 'agent', 'workflows'], + category: 'engineering', + tags: ['research', 'sync'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev competitor monitor', + prompt: + 'Build a scheduled workflow that scrapes competitor pricing and changelog pages to markdown with Context.dev weekly, diffs against the prior snapshot, logs changes to a table, and posts notable updates to Slack.', + modules: ['scheduled', 'tables', 'agent', 'workflows'], + category: 'marketing', + tags: ['marketing', 'monitoring'], + alsoIntegrations: ['slack'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev lead enrichment', + prompt: + 'Create a workflow that takes a work email, uses Context.dev to retrieve brand data by email and classify the company into NAICS codes, and writes the enriched firmographics to a CRM record.', + modules: ['agent', 'tables', 'workflows'], + category: 'sales', + tags: ['enrichment', 'sales'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev structured data extractor', + prompt: + 'Build a workflow that takes a website URL and a JSON schema, uses Context.dev Extract to pull structured fields across the site, and returns the validated records as JSON.', + modules: ['agent', 'workflows'], + category: 'operations', + tags: ['automation', 'research'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev research brief', + prompt: + 'Create an agent that runs a Context.dev web search on a topic, scrapes the top results to markdown, and synthesizes a cited research brief saved as a file.', + modules: ['agent', 'files', 'workflows'], + category: 'productivity', + tags: ['research'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev design-system extractor', + prompt: + 'Build a workflow that takes a domain, uses Context.dev to scrape its styleguide and fonts plus a homepage screenshot, and stores the design tokens and assets as files for a design handoff.', + modules: ['agent', 'files', 'workflows'], + category: 'engineering', + tags: ['design', 'research'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev transaction enrichment', + prompt: + 'Create a workflow that takes raw bank transaction descriptors, uses Context.dev to identify the merchant brand behind each one, and appends the resolved company and logo to a table.', + modules: ['tables', 'agent', 'workflows'], + category: 'operations', + tags: ['enrichment', 'automation'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev product catalog importer', + prompt: + "Build a workflow that takes a brand domain, uses Context.dev to extract the brand's product catalog with pricing and features, and writes each product as a row in a table.", + modules: ['tables', 'agent', 'workflows'], + category: 'operations', + tags: ['enrichment', 'automation'], + }, + { + icon: ContextDevIcon, + title: 'Context.dev site change watcher', + prompt: + 'Build a scheduled workflow that maps a site sitemap with Context.dev, scrapes new or changed pages to markdown, summarizes the differences, and emails a digest.', + modules: ['scheduled', 'agent', 'workflows'], + category: 'operations', + tags: ['monitoring', 'automation'], + alsoIntegrations: ['gmail'], + }, + ], +} as const satisfies BlockMeta diff --git a/apps/sim/blocks/blocks/instantly.ts b/apps/sim/blocks/blocks/instantly.ts index c28097873a7..bdef8922b35 100644 --- a/apps/sim/blocks/blocks/instantly.ts +++ b/apps/sim/blocks/blocks/instantly.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { InstantlyIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' @@ -1100,12 +1101,12 @@ function parseStringList(value: unknown): string[] | undefined { } function parseJsonObject(value: unknown): Record | undefined { - if (isPlainObject(value)) return value + if (isRecordLike(value)) return value if (typeof value !== 'string' || value.trim() === '') return undefined try { const parsed: unknown = JSON.parse(value) - return isPlainObject(parsed) ? parsed : undefined + return isRecordLike(parsed) ? parsed : undefined } catch { return undefined } @@ -1249,10 +1250,6 @@ function optionalIdParam(value: unknown): string | undefined { return trimmed } -function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export const InstantlyBlockMeta = { tags: ['sales-engagement', 'email-marketing', 'automation'], url: 'https://instantly.ai', diff --git a/apps/sim/blocks/blocks/square.ts b/apps/sim/blocks/blocks/square.ts new file mode 100644 index 00000000000..17d4f7c295e --- /dev/null +++ b/apps/sim/blocks/blocks/square.ts @@ -0,0 +1,978 @@ +import { SquareIcon } from '@/components/icons' +import type { BlockConfig, BlockMeta } from '@/blocks/types' +import { AuthMode, IntegrationType } from '@/blocks/types' +import { normalizeFileInput } from '@/blocks/utils' +import type { SquareResponse } from '@/tools/square/types' + +export const SquareBlock: BlockConfig = { + type: 'square', + name: 'Square', + description: 'Process payments and manage Square commerce data', + authMode: AuthMode.ApiKey, + longDescription: + 'Integrate Square into the workflow. Take and refund payments, manage customers, build catalog items and images, create and search orders, and issue invoices. Authenticate with a Square access token (personal access token).', + docsLink: 'https://docs.sim.ai/integrations/square', + category: 'tools', + integrationType: IntegrationType.Commerce, + bgColor: '#000000', + icon: SquareIcon, + + subBlocks: [ + { + id: 'operation', + title: 'Operation', + type: 'dropdown', + options: [ + // Payments + { label: 'Create Payment', id: 'create_payment' }, + { label: 'Get Payment', id: 'get_payment' }, + { label: 'List Payments', id: 'list_payments' }, + { label: 'Cancel Payment', id: 'cancel_payment' }, + { label: 'Complete Payment', id: 'complete_payment' }, + // Refunds + { label: 'Refund Payment', id: 'refund_payment' }, + { label: 'Get Refund', id: 'get_refund' }, + { label: 'List Refunds', id: 'list_refunds' }, + // Customers + { label: 'Create Customer', id: 'create_customer' }, + { label: 'Get Customer', id: 'get_customer' }, + { label: 'List Customers', id: 'list_customers' }, + { label: 'Search Customers', id: 'search_customers' }, + { label: 'Update Customer', id: 'update_customer' }, + { label: 'Delete Customer', id: 'delete_customer' }, + // Locations + { label: 'List Locations', id: 'list_locations' }, + { label: 'Get Location', id: 'get_location' }, + // Orders + { label: 'Create Order', id: 'create_order' }, + { label: 'Get Order', id: 'get_order' }, + { label: 'Search Orders', id: 'search_orders' }, + { label: 'Pay Order', id: 'pay_order' }, + // Invoices + { label: 'Create Invoice', id: 'create_invoice' }, + { label: 'Get Invoice', id: 'get_invoice' }, + { label: 'List Invoices', id: 'list_invoices' }, + { label: 'Search Invoices', id: 'search_invoices' }, + { label: 'Publish Invoice', id: 'publish_invoice' }, + { label: 'Cancel Invoice', id: 'cancel_invoice' }, + { label: 'Delete Invoice', id: 'delete_invoice' }, + // Catalog + { label: 'Upsert Catalog Object', id: 'upsert_catalog_object' }, + { label: 'Get Catalog Object', id: 'get_catalog_object' }, + { label: 'List Catalog', id: 'list_catalog' }, + { label: 'Search Catalog Objects', id: 'search_catalog_objects' }, + { label: 'Create Catalog Image', id: 'create_catalog_image' }, + { label: 'Delete Catalog Object', id: 'delete_catalog_object' }, + // Inventory + { label: 'Batch Retrieve Inventory Counts', id: 'batch_retrieve_inventory_counts' }, + ], + value: () => 'create_payment', + }, + { + id: 'apiKey', + title: 'Square Access Token', + type: 'short-input', + password: true, + placeholder: 'Enter your Square access token', + required: true, + }, + + // Payments + { + id: 'sourceId', + title: 'Source ID', + type: 'short-input', + placeholder: 'Card nonce, card-on-file ID, or wallet token', + condition: { field: 'operation', value: 'create_payment' }, + required: { field: 'operation', value: 'create_payment' }, + }, + { + id: 'paymentId', + title: 'Payment ID', + type: 'short-input', + placeholder: 'Square payment ID', + condition: { + field: 'operation', + value: ['get_payment', 'refund_payment', 'cancel_payment', 'complete_payment'], + }, + required: { + field: 'operation', + value: ['get_payment', 'refund_payment', 'cancel_payment', 'complete_payment'], + }, + }, + { + id: 'refundId', + title: 'Refund ID', + type: 'short-input', + placeholder: 'Square refund ID', + condition: { field: 'operation', value: 'get_refund' }, + required: { field: 'operation', value: 'get_refund' }, + }, + { + id: 'status', + title: 'Status', + type: 'short-input', + placeholder: 'Filter by status (e.g. COMPLETED)', + condition: { field: 'operation', value: 'list_refunds' }, + mode: 'advanced', + }, + { + id: 'amount', + title: 'Amount', + type: 'short-input', + placeholder: 'Smallest denomination (e.g. 1000 for $10.00)', + condition: { field: 'operation', value: ['create_payment', 'refund_payment'] }, + required: { field: 'operation', value: ['create_payment', 'refund_payment'] }, + }, + { + id: 'currency', + title: 'Currency', + type: 'short-input', + placeholder: 'ISO 4217 code (e.g. USD)', + condition: { field: 'operation', value: ['create_payment', 'refund_payment'] }, + required: { field: 'operation', value: ['create_payment', 'refund_payment'] }, + }, + { + id: 'reason', + title: 'Refund Reason', + type: 'short-input', + placeholder: 'Reason for the refund', + condition: { field: 'operation', value: 'refund_payment' }, + }, + { + id: 'versionToken', + title: 'Version Token', + type: 'short-input', + placeholder: 'Optional version token for concurrency control', + condition: { field: 'operation', value: 'complete_payment' }, + mode: 'advanced', + }, + { + id: 'autocomplete', + title: 'Capture Immediately', + type: 'dropdown', + options: [ + { label: 'Yes', id: 'true' }, + { label: 'No', id: 'false' }, + ], + condition: { field: 'operation', value: 'create_payment' }, + mode: 'advanced', + }, + { + id: 'beginTime', + title: 'Begin Time', + type: 'short-input', + placeholder: 'RFC 3339 timestamp', + condition: { field: 'operation', value: ['list_payments', 'list_refunds'] }, + mode: 'advanced', + wandConfig: { + enabled: true, + prompt: 'Generate an RFC 3339 timestamp. Return ONLY the timestamp string.', + generationType: 'timestamp', + }, + }, + { + id: 'endTime', + title: 'End Time', + type: 'short-input', + placeholder: 'RFC 3339 timestamp', + condition: { field: 'operation', value: ['list_payments', 'list_refunds'] }, + mode: 'advanced', + wandConfig: { + enabled: true, + prompt: 'Generate an RFC 3339 timestamp. Return ONLY the timestamp string.', + generationType: 'timestamp', + }, + }, + + // Customers + { + id: 'customerId', + title: 'Customer ID', + type: 'short-input', + placeholder: 'Square customer ID', + condition: { + field: 'operation', + value: ['create_payment', 'get_customer', 'update_customer', 'delete_customer'], + }, + required: { + field: 'operation', + value: ['get_customer', 'update_customer', 'delete_customer'], + }, + }, + { + id: 'givenName', + title: 'First Name', + type: 'short-input', + placeholder: 'Customer first name', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + }, + { + id: 'familyName', + title: 'Last Name', + type: 'short-input', + placeholder: 'Customer last name', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + }, + { + id: 'companyName', + title: 'Company Name', + type: 'short-input', + placeholder: 'Customer business name', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + mode: 'advanced', + }, + { + id: 'nickname', + title: 'Nickname', + type: 'short-input', + placeholder: 'Customer nickname', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + mode: 'advanced', + }, + { + id: 'emailAddress', + title: 'Email Address', + type: 'short-input', + placeholder: 'customer@example.com', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + }, + { + id: 'phoneNumber', + title: 'Phone Number', + type: 'short-input', + placeholder: '+15551234567', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + mode: 'advanced', + }, + { + id: 'birthday', + title: 'Birthday', + type: 'short-input', + placeholder: 'YYYY-MM-DD or MM-DD', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + mode: 'advanced', + }, + { + id: 'address', + title: 'Address (JSON)', + type: 'code', + language: 'json', + placeholder: '{"address_line_1": "123 Main St", "locality": "New York", "country": "US"}', + condition: { field: 'operation', value: ['create_customer', 'update_customer'] }, + mode: 'advanced', + }, + { + id: 'sortField', + title: 'Sort Field', + type: 'dropdown', + options: [ + { label: 'Default', id: 'DEFAULT' }, + { label: 'Created At', id: 'CREATED_AT' }, + ], + condition: { field: 'operation', value: 'list_customers' }, + mode: 'advanced', + }, + { + id: 'sortOrder', + title: 'Sort Order', + type: 'dropdown', + options: [ + { label: 'Ascending', id: 'ASC' }, + { label: 'Descending', id: 'DESC' }, + ], + condition: { field: 'operation', value: 'list_customers' }, + mode: 'advanced', + }, + + // Shared note / reference (payments + customers) + { + id: 'note', + title: 'Note', + type: 'long-input', + placeholder: 'Optional note', + condition: { + field: 'operation', + value: ['create_payment', 'create_customer', 'update_customer'], + }, + mode: 'advanced', + }, + { + id: 'referenceId', + title: 'Reference ID', + type: 'short-input', + placeholder: 'Optional external reference', + condition: { + field: 'operation', + value: ['create_payment', 'create_customer', 'update_customer'], + }, + mode: 'advanced', + }, + + // Search query — shared across the three search operations. The placeholder + // stays schema-neutral (each endpoint expects a different query shape) and + // the examples for each are spelled out in the wand prompt. + { + id: 'query', + title: 'Query (JSON)', + type: 'code', + language: 'json', + placeholder: 'Square search query JSON for the selected operation', + condition: { + field: 'operation', + value: ['search_customers', 'search_orders', 'search_catalog_objects'], + }, + mode: 'advanced', + wandConfig: { + enabled: true, + prompt: + 'Generate a Square search query JSON object for the selected operation. For Search Customers use a filter like {"filter":{"email_address":{"exact":"a@b.com"}}}; for Search Orders use {"filter":{"state_filter":{"states":["OPEN"]}}}; for Search Catalog Objects use {"text_query":{"keywords":["coffee"]}}. Return ONLY the JSON object.', + generationType: 'json-object', + }, + }, + + // Orders + { + id: 'order', + title: 'Order (JSON)', + type: 'code', + language: 'json', + placeholder: + '{"location_id": "L123", "line_items": [{"name": "Coffee", "quantity": "1", "base_price_money": {"amount": 250, "currency": "USD"}}]}', + condition: { field: 'operation', value: 'create_order' }, + required: { field: 'operation', value: 'create_order' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a Square order JSON object with a location_id and line_items. Return ONLY the JSON object.', + generationType: 'json-object', + }, + }, + { + id: 'orderId', + title: 'Order ID', + type: 'short-input', + placeholder: 'Square order ID', + condition: { field: 'operation', value: ['create_payment', 'get_order', 'pay_order'] }, + required: { field: 'operation', value: ['get_order', 'pay_order'] }, + }, + { + id: 'paymentIds', + title: 'Payment IDs (JSON Array)', + type: 'code', + language: 'json', + placeholder: '["paymentId1", "paymentId2"]', + condition: { field: 'operation', value: 'pay_order' }, + mode: 'advanced', + }, + { + id: 'orderVersion', + title: 'Order Version', + type: 'short-input', + placeholder: 'Current order version', + condition: { field: 'operation', value: 'pay_order' }, + mode: 'advanced', + }, + { + id: 'locationIds', + title: 'Location IDs (JSON Array)', + type: 'code', + language: 'json', + placeholder: '["L123", "L456"]', + condition: { + field: 'operation', + value: ['search_orders', 'batch_retrieve_inventory_counts'], + }, + required: { field: 'operation', value: 'search_orders' }, + }, + + // Invoices + { + id: 'invoice', + title: 'Invoice (JSON)', + type: 'code', + language: 'json', + placeholder: + '{"location_id": "L123", "order_id": "O123", "primary_recipient": {"customer_id": "C123"}, "payment_requests": [{"request_type": "BALANCE"}]}', + condition: { field: 'operation', value: 'create_invoice' }, + required: { field: 'operation', value: 'create_invoice' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a Square invoice JSON object with location_id, order_id, primary_recipient, and payment_requests. Return ONLY the JSON object.', + generationType: 'json-object', + }, + }, + { + id: 'invoiceId', + title: 'Invoice ID', + type: 'short-input', + placeholder: 'Square invoice ID', + condition: { + field: 'operation', + value: ['get_invoice', 'publish_invoice', 'cancel_invoice', 'delete_invoice'], + }, + required: { + field: 'operation', + value: ['get_invoice', 'publish_invoice', 'cancel_invoice', 'delete_invoice'], + }, + }, + { + id: 'version', + title: 'Invoice Version', + type: 'short-input', + placeholder: 'Current invoice version (e.g. 0)', + condition: { + field: 'operation', + value: ['publish_invoice', 'cancel_invoice', 'delete_invoice'], + }, + required: { field: 'operation', value: ['publish_invoice', 'cancel_invoice'] }, + }, + + // Catalog + { + id: 'object', + title: 'Catalog Object (JSON)', + type: 'code', + language: 'json', + placeholder: '{"type": "ITEM", "id": "#Coffee", "item_data": {"name": "Coffee"}}', + condition: { field: 'operation', value: 'upsert_catalog_object' }, + required: { field: 'operation', value: 'upsert_catalog_object' }, + wandConfig: { + enabled: true, + prompt: + 'Generate a Square catalog object JSON for upsert. Use a temporary id like "#Name" for new objects. Return ONLY the JSON object.', + generationType: 'json-object', + }, + }, + { + id: 'objectId', + title: 'Catalog Object ID', + type: 'short-input', + placeholder: 'Square catalog object ID', + condition: { + field: 'operation', + value: ['get_catalog_object', 'create_catalog_image', 'delete_catalog_object'], + }, + required: { field: 'operation', value: ['get_catalog_object', 'delete_catalog_object'] }, + }, + { + id: 'catalogObjectIds', + title: 'Catalog Object IDs (JSON Array)', + type: 'code', + language: 'json', + placeholder: '["variationId1", "variationId2"]', + condition: { field: 'operation', value: 'batch_retrieve_inventory_counts' }, + mode: 'advanced', + }, + { + id: 'states', + title: 'Inventory States (JSON Array)', + type: 'code', + language: 'json', + placeholder: '["IN_STOCK", "SOLD"]', + condition: { field: 'operation', value: 'batch_retrieve_inventory_counts' }, + mode: 'advanced', + }, + { + id: 'updatedAfter', + title: 'Updated After', + type: 'short-input', + placeholder: 'RFC 3339 timestamp', + condition: { field: 'operation', value: 'batch_retrieve_inventory_counts' }, + mode: 'advanced', + wandConfig: { + enabled: true, + prompt: 'Generate an RFC 3339 timestamp. Return ONLY the timestamp string.', + generationType: 'timestamp', + }, + }, + { + id: 'includeRelatedObjects', + title: 'Include Related Objects', + type: 'dropdown', + options: [ + { label: 'Yes', id: 'true' }, + { label: 'No', id: 'false' }, + ], + condition: { field: 'operation', value: 'get_catalog_object' }, + mode: 'advanced', + }, + { + id: 'types', + title: 'Types', + type: 'short-input', + placeholder: 'Comma-separated (e.g. ITEM,CATEGORY)', + condition: { field: 'operation', value: 'list_catalog' }, + mode: 'advanced', + }, + { + id: 'objectTypes', + title: 'Object Types (JSON Array)', + type: 'code', + language: 'json', + placeholder: '["ITEM", "CATEGORY"]', + condition: { field: 'operation', value: 'search_catalog_objects' }, + mode: 'advanced', + }, + + // Catalog image upload (file) + { + id: 'uploadFile', + title: 'Image File', + type: 'file-upload', + canonicalParamId: 'file', + placeholder: 'Upload an image', + acceptedTypes: 'image/*', + mode: 'basic', + multiple: false, + condition: { field: 'operation', value: 'create_catalog_image' }, + required: { field: 'operation', value: 'create_catalog_image' }, + }, + { + id: 'fileRef', + title: 'Image File', + type: 'short-input', + canonicalParamId: 'file', + placeholder: 'Reference an image from previous blocks', + mode: 'advanced', + condition: { field: 'operation', value: 'create_catalog_image' }, + required: { field: 'operation', value: 'create_catalog_image' }, + }, + { + id: 'fileName', + title: 'File Name', + type: 'short-input', + placeholder: 'Optional filename override', + condition: { field: 'operation', value: 'create_catalog_image' }, + mode: 'advanced', + }, + { + id: 'caption', + title: 'Caption', + type: 'short-input', + placeholder: 'Image caption (alt text)', + condition: { field: 'operation', value: 'create_catalog_image' }, + }, + + // Shared pagination (list / search) + { + id: 'locationId', + title: 'Location ID', + type: 'short-input', + placeholder: 'Square location ID', + condition: { + field: 'operation', + value: [ + 'create_payment', + 'list_payments', + 'list_invoices', + 'search_invoices', + 'list_refunds', + 'get_location', + ], + }, + required: { field: 'operation', value: ['list_invoices', 'search_invoices', 'get_location'] }, + }, + { + id: 'limit', + title: 'Limit', + type: 'short-input', + placeholder: 'Max results per page', + condition: { + field: 'operation', + value: [ + 'list_payments', + 'list_refunds', + 'list_customers', + 'search_customers', + 'search_orders', + 'list_invoices', + 'search_invoices', + 'search_catalog_objects', + 'batch_retrieve_inventory_counts', + ], + }, + mode: 'advanced', + }, + { + id: 'cursor', + title: 'Cursor', + type: 'short-input', + placeholder: 'Pagination cursor from a previous response', + condition: { + field: 'operation', + value: [ + 'list_payments', + 'list_refunds', + 'list_customers', + 'search_customers', + 'search_orders', + 'list_invoices', + 'search_invoices', + 'search_catalog_objects', + 'list_catalog', + 'batch_retrieve_inventory_counts', + ], + }, + mode: 'advanced', + }, + + // Idempotency (create-style operations) + { + id: 'idempotencyKey', + title: 'Idempotency Key', + type: 'short-input', + placeholder: 'Optional unique key (auto-generated if omitted)', + condition: { + field: 'operation', + value: [ + 'create_payment', + 'refund_payment', + 'create_customer', + 'create_order', + 'pay_order', + 'create_invoice', + 'publish_invoice', + 'upsert_catalog_object', + 'create_catalog_image', + ], + }, + mode: 'advanced', + }, + ], + + tools: { + access: [ + 'square_create_payment', + 'square_get_payment', + 'square_list_payments', + 'square_cancel_payment', + 'square_complete_payment', + 'square_refund_payment', + 'square_get_refund', + 'square_list_refunds', + 'square_create_customer', + 'square_get_customer', + 'square_list_customers', + 'square_search_customers', + 'square_update_customer', + 'square_delete_customer', + 'square_list_locations', + 'square_get_location', + 'square_create_order', + 'square_get_order', + 'square_search_orders', + 'square_pay_order', + 'square_create_invoice', + 'square_get_invoice', + 'square_list_invoices', + 'square_search_invoices', + 'square_publish_invoice', + 'square_cancel_invoice', + 'square_delete_invoice', + 'square_upsert_catalog_object', + 'square_get_catalog_object', + 'square_list_catalog', + 'square_search_catalog_objects', + 'square_create_catalog_image', + 'square_delete_catalog_object', + 'square_batch_retrieve_inventory_counts', + ], + config: { + tool: (params) => `square_${params.operation}`, + params: (params) => { + const { + operation, + address, + query, + order, + invoice, + object, + locationIds, + objectTypes, + paymentIds, + catalogObjectIds, + states, + amount, + limit, + version, + orderVersion, + autocomplete, + includeRelatedObjects, + ...rest + } = params + + // The basic/advanced image inputs are collapsed into the canonical `file` + // param before this runs, so normalize from params.file. + const normalizedFile = normalizeFileInput(params.file, { single: true }) + + // Parse a JSON-typed input, naming the field in any error so the user + // knows exactly which input to fix, and validating the parsed shape so a + // valid-but-wrong-type value (e.g. a string where an array is expected) + // fails locally instead of as a confusing Square API error. + const parseJsonField = ( + value: unknown, + field: string, + expected: 'object' | 'array' + ): unknown => { + if (value === undefined || value === null || value === '') return undefined + let parsed: unknown = value + if (typeof value === 'string') { + try { + parsed = JSON.parse(value) + } catch (error) { + throw new Error( + `Invalid JSON in "${field}": ${error instanceof Error ? error.message : 'unknown error'}` + ) + } + } + if (expected === 'array' && !Array.isArray(parsed)) { + throw new Error(`"${field}" must be a JSON array`) + } + if ( + expected === 'object' && + (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) + ) { + throw new Error(`"${field}" must be a JSON object`) + } + return parsed + } + + const parsedAddress = parseJsonField(address, 'address', 'object') + const parsedQuery = parseJsonField(query, 'query', 'object') + const parsedOrder = parseJsonField(order, 'order', 'object') + const parsedInvoice = parseJsonField(invoice, 'invoice', 'object') + const parsedObject = parseJsonField(object, 'object', 'object') + const parsedLocationIds = parseJsonField(locationIds, 'locationIds', 'array') + const parsedObjectTypes = parseJsonField(objectTypes, 'objectTypes', 'array') + const parsedPaymentIds = parseJsonField(paymentIds, 'paymentIds', 'array') + const parsedCatalogObjectIds = parseJsonField(catalogObjectIds, 'catalogObjectIds', 'array') + const parsedStates = parseJsonField(states, 'states', 'array') + + // Coerce a numeric input, failing locally with a clear message rather than + // forwarding NaN to Square when the value is non-numeric. + const coerceNumber = (value: unknown, field: string): number | undefined => { + if (value === undefined || value === null || value === '') return undefined + const num = Number(value) + if (!Number.isFinite(num)) { + throw new Error(`"${field}" must be a valid number`) + } + return num + } + + // Accept both the dropdown's string values and real booleans (which can + // arrive via connected blocks or templated inputs). + const coerceBoolean = (value: unknown): boolean => value === true || value === 'true' + + const coercedAmount = coerceNumber(amount, 'amount') + const coercedLimit = coerceNumber(limit, 'limit') + const coercedVersion = coerceNumber(version, 'version') + const coercedOrderVersion = coerceNumber(orderVersion, 'orderVersion') + + return { + ...rest, + ...(normalizedFile && { file: normalizedFile }), + ...(parsedAddress !== undefined && { address: parsedAddress }), + ...(parsedQuery !== undefined && { query: parsedQuery }), + ...(parsedOrder !== undefined && { order: parsedOrder }), + ...(parsedInvoice !== undefined && { invoice: parsedInvoice }), + ...(parsedObject !== undefined && { object: parsedObject }), + ...(parsedLocationIds !== undefined && { locationIds: parsedLocationIds }), + ...(parsedObjectTypes !== undefined && { objectTypes: parsedObjectTypes }), + ...(parsedPaymentIds !== undefined && { paymentIds: parsedPaymentIds }), + ...(parsedCatalogObjectIds !== undefined && { catalogObjectIds: parsedCatalogObjectIds }), + ...(parsedStates !== undefined && { states: parsedStates }), + ...(coercedAmount !== undefined && { amount: coercedAmount }), + ...(coercedLimit !== undefined && { limit: coercedLimit }), + ...(coercedVersion !== undefined && { version: coercedVersion }), + ...(coercedOrderVersion !== undefined && { orderVersion: coercedOrderVersion }), + ...(autocomplete !== undefined && { autocomplete: coerceBoolean(autocomplete) }), + ...(includeRelatedObjects !== undefined && { + includeRelatedObjects: coerceBoolean(includeRelatedObjects), + }), + } + }, + }, + }, + + inputs: { + operation: { type: 'string', description: 'Operation to perform' }, + apiKey: { type: 'string', description: 'Square access token' }, + sourceId: { type: 'string', description: 'Payment source ID' }, + paymentId: { type: 'string', description: 'Payment ID' }, + refundId: { type: 'string', description: 'Refund ID' }, + status: { type: 'string', description: 'Status filter' }, + amount: { type: 'number', description: 'Amount in smallest currency denomination' }, + currency: { type: 'string', description: 'ISO 4217 currency code' }, + reason: { type: 'string', description: 'Refund reason' }, + versionToken: { type: 'string', description: 'Version token for payment concurrency control' }, + autocomplete: { type: 'boolean', description: 'Capture payment immediately' }, + beginTime: { type: 'string', description: 'Start of the reporting period (RFC 3339)' }, + endTime: { type: 'string', description: 'End of the reporting period (RFC 3339)' }, + customerId: { type: 'string', description: 'Customer ID' }, + givenName: { type: 'string', description: 'Customer first name' }, + familyName: { type: 'string', description: 'Customer last name' }, + companyName: { type: 'string', description: 'Customer company name' }, + nickname: { type: 'string', description: 'Customer nickname' }, + emailAddress: { type: 'string', description: 'Customer email address' }, + phoneNumber: { type: 'string', description: 'Customer phone number' }, + birthday: { type: 'string', description: 'Customer birthday (YYYY-MM-DD or MM-DD)' }, + address: { type: 'json', description: 'Customer address object' }, + note: { type: 'string', description: 'Note' }, + referenceId: { type: 'string', description: 'External reference ID' }, + sortField: { type: 'string', description: 'Field to sort by' }, + sortOrder: { type: 'string', description: 'Sort order (ASC or DESC)' }, + query: { type: 'json', description: 'Search query object' }, + order: { type: 'json', description: 'Order object' }, + orderId: { type: 'string', description: 'Order ID' }, + orderVersion: { type: 'number', description: 'Order version for payment' }, + paymentIds: { type: 'json', description: 'Array of payment IDs to apply to an order' }, + locationIds: { type: 'json', description: 'Array of location IDs' }, + invoice: { type: 'json', description: 'Invoice object' }, + invoiceId: { type: 'string', description: 'Invoice ID' }, + version: { type: 'number', description: 'Invoice version' }, + object: { type: 'json', description: 'Catalog object' }, + objectId: { type: 'string', description: 'Catalog object ID' }, + includeRelatedObjects: { type: 'boolean', description: 'Include related catalog objects' }, + types: { type: 'string', description: 'Comma-separated catalog object types' }, + objectTypes: { type: 'json', description: 'Array of catalog object types to search' }, + catalogObjectIds: { type: 'json', description: 'Array of catalog object IDs for inventory' }, + states: { type: 'json', description: 'Array of inventory states to filter by' }, + updatedAfter: { + type: 'string', + description: 'Only return inventory counts updated after this time', + }, + file: { type: 'json', description: 'Image file to upload (canonical param)' }, + fileName: { type: 'string', description: 'Filename override for the image' }, + caption: { type: 'string', description: 'Image caption' }, + locationId: { type: 'string', description: 'Location ID' }, + limit: { type: 'number', description: 'Maximum results to return' }, + cursor: { type: 'string', description: 'Pagination cursor' }, + idempotencyKey: { type: 'string', description: 'Idempotency key' }, + }, + + outputs: { + payment: { type: 'json', description: 'Payment object' }, + payments: { type: 'json', description: 'Array of payment objects' }, + refund: { type: 'json', description: 'Refund object' }, + refunds: { type: 'json', description: 'Array of refund objects' }, + customer: { type: 'json', description: 'Customer object' }, + customers: { type: 'json', description: 'Array of customer objects' }, + location: { type: 'json', description: 'Location object' }, + locations: { type: 'json', description: 'Array of location objects' }, + order: { type: 'json', description: 'Order object' }, + orders: { type: 'json', description: 'Array of order objects' }, + invoice: { type: 'json', description: 'Invoice object' }, + invoices: { type: 'json', description: 'Array of invoice objects' }, + object: { type: 'json', description: 'Catalog object' }, + objects: { type: 'json', description: 'Array of catalog objects' }, + counts: { type: 'json', description: 'Array of inventory count objects' }, + deleted: { type: 'boolean', description: 'Whether the resource was deleted' }, + deleted_object_ids: { type: 'json', description: 'IDs of deleted catalog objects' }, + deleted_at: { type: 'string', description: 'Timestamp when deletion occurred' }, + id: { type: 'string', description: 'ID of the affected resource' }, + metadata: { type: 'json', description: 'Operation summary metadata' }, + }, +} + +export const SquareBlockMeta = { + tags: ['payments', 'subscriptions', 'automation'], + url: 'https://squareup.com', + templates: [ + { + icon: SquareIcon, + title: 'Daily sales summary', + prompt: + 'Build a scheduled daily workflow that lists Square payments from the previous day across all locations, totals gross sales, refunds, and net revenue, writes the figures to a table for historical tracking, and posts a Slack summary with day-over-day trends.', + modules: ['scheduled', 'tables', 'agent', 'workflows'], + category: 'operations', + tags: ['finance', 'reporting', 'founder'], + alsoIntegrations: ['slack'], + }, + { + icon: SquareIcon, + title: 'Refund pattern monitor', + prompt: + 'Create a scheduled weekly workflow that lists Square payments and their refunds, classifies each refund by reason and location, flags any location with an unusually high refund rate, and emails finance a narrative report with recommended actions.', + modules: ['scheduled', 'agent', 'files', 'workflows'], + category: 'operations', + tags: ['finance', 'analysis', 'monitoring'], + alsoIntegrations: ['gmail'], + }, + { + icon: SquareIcon, + title: 'New customer welcome', + prompt: + 'Build a workflow that takes a new Square customer, creates a welcome email tailored to their purchase, adds them to an onboarding tracking table, and posts a notification to the customer success Slack channel.', + modules: ['tables', 'agent', 'workflows'], + category: 'operations', + tags: ['sales', 'automation'], + alsoIntegrations: ['gmail', 'slack'], + }, + { + icon: SquareIcon, + title: 'Invoice chase automation', + prompt: + 'Create a scheduled workflow that lists Square invoices for a location, finds those that are unpaid past their due date, sends a polite reminder email per customer, and logs every chase action to a collections table.', + modules: ['scheduled', 'tables', 'agent', 'workflows'], + category: 'operations', + tags: ['finance', 'automation', 'reporting'], + alsoIntegrations: ['gmail'], + }, + { + icon: SquareIcon, + title: 'Catalog image enrichment', + prompt: + 'Build a workflow that lists Square catalog items missing images, generates a product image for each one, uploads it as a catalog image attached to the item, and writes a report of which items were updated.', + modules: ['agent', 'files', 'workflows'], + category: 'operations', + tags: ['ecommerce', 'automation'], + }, + { + icon: SquareIcon, + title: 'Low-stock reorder alerts', + prompt: + 'Create a scheduled workflow that lists the Square catalog, identifies items flagged as low or out of stock, drafts a reorder summary grouped by supplier, and posts it to a Slack purchasing channel with the items and quantities to reorder.', + modules: ['scheduled', 'agent', 'workflows'], + category: 'operations', + tags: ['ecommerce', 'operations'], + alsoIntegrations: ['slack'], + }, + { + icon: SquareIcon, + title: 'Customer purchase history lookup', + prompt: + 'Build a workflow that searches Square customers by email, pulls their orders and payments, summarizes lifetime spend and most-purchased items, and returns a concise profile the support team can use during a conversation.', + modules: ['agent', 'workflows'], + category: 'support', + tags: ['support', 'analysis'], + }, + ], + skills: [ + { + name: 'take-payment', + description: 'Take a Square payment from a payment source and confirm the result.', + content: + '# Take Payment\n\nCharge a customer using Square.\n\n## Steps\n1. Run Create Payment with the source ID (card nonce or card on file), the amount in the smallest denomination, and the currency.\n2. Optionally attach a customer ID, location ID, or order ID.\n3. Confirm the result with Get Payment if you need the latest status.\n\n## Output\nReturn the payment ID, status (APPROVED, COMPLETED, or FAILED), and the amount charged. If a refund is needed, run Refund Payment with the payment ID.', + }, + { + name: 'issue-and-publish-invoice', + description: 'Create a Square invoice for an order and publish it to the customer.', + content: + '# Issue And Publish Invoice\n\nBill a customer with a Square invoice.\n\n## Steps\n1. Make sure an order exists (use Create Order if needed) and you have the customer ID.\n2. Run Create Invoice with an invoice object referencing the location, order, primary recipient (customer), and payment requests. Note the returned invoice ID and version.\n3. Run Publish Invoice with that invoice ID and version to send it to the customer.\n4. Track payment with Get Invoice.\n\n## Output\nReturn the invoice ID, status, and the public URL where the customer can pay.', + }, + { + name: 'manage-catalog-item', + description: 'Create or update a Square catalog item and attach an image to it.', + content: + '# Manage Catalog Item\n\nBuild out the Square catalog.\n\n## Steps\n1. Run Upsert Catalog Object with an ITEM object (use a temporary id like "#Name" for new items). Capture the returned object ID.\n2. To add a picture, run Create Catalog Image with the image file and the object ID to attach it to the item.\n3. Verify with Get Catalog Object or Search Catalog Objects.\n\n## Output\nReturn the catalog object ID, type, and version, plus the image object ID when an image was attached.', + }, + { + name: 'find-customer-activity', + description: 'Look up a Square customer and summarize their orders and payments.', + content: + '# Find Customer Activity\n\nBuild a purchase history view for one customer.\n\n## Steps\n1. Run Search Customers (by email or phone) or Get Customer to identify the customer and their ID.\n2. Run Search Orders across the relevant locations filtered to that customer.\n3. Run List Payments and match payments to the customer for a full financial picture.\n\n## Output\nReturn the customer ID and email plus a summary of their orders and payments: total spend, number of orders, and any refunds.', + }, + ], +} as const satisfies BlockMeta diff --git a/apps/sim/blocks/registry.ts b/apps/sim/blocks/registry.ts index 2cacc4576c6..1d2066d2656 100644 --- a/apps/sim/blocks/registry.ts +++ b/apps/sim/blocks/registry.ts @@ -38,6 +38,7 @@ import { CloudWatchBlock, CloudWatchBlockMeta } from '@/blocks/blocks/cloudwatch import { CodePipelineBlock, CodePipelineBlockMeta } from '@/blocks/blocks/codepipeline' import { ConditionBlock } from '@/blocks/blocks/condition' import { ConfluenceBlock, ConfluenceBlockMeta, ConfluenceV2Block } from '@/blocks/blocks/confluence' +import { ContextDevBlock, ContextDevBlockMeta } from '@/blocks/blocks/context_dev' import { ConvexBlock, ConvexBlockMeta } from '@/blocks/blocks/convex' import { CredentialBlock } from '@/blocks/blocks/credential' import { CrowdStrikeBlock, CrowdStrikeBlockMeta } from '@/blocks/blocks/crowdstrike' @@ -267,6 +268,7 @@ import { SlackBlock, SlackBlockMeta } from '@/blocks/blocks/slack' import { SmtpBlock } from '@/blocks/blocks/smtp' import { SpotifyBlock, SpotifyBlockMeta } from '@/blocks/blocks/spotify' import { SQSBlock, SQSBlockMeta } from '@/blocks/blocks/sqs' +import { SquareBlock, SquareBlockMeta } from '@/blocks/blocks/square' import { SSHBlock } from '@/blocks/blocks/ssh' import { StagehandBlock, StagehandBlockMeta } from '@/blocks/blocks/stagehand' import { StartTriggerBlock } from '@/blocks/blocks/start_trigger' @@ -368,6 +370,7 @@ const BLOCK_REGISTRY: Record = { condition: ConditionBlock, confluence: ConfluenceBlock, confluence_v2: ConfluenceV2Block, + context_dev: ContextDevBlock, convex: ConvexBlock, credential: CredentialBlock, crowdstrike: CrowdStrikeBlock, @@ -567,6 +570,7 @@ const BLOCK_REGISTRY: Record = { smtp: SmtpBlock, spotify: SpotifyBlock, sqs: SQSBlock, + square: SquareBlock, ssh: SSHBlock, stagehand: StagehandBlock, start_trigger: StartTriggerBlock, @@ -667,6 +671,7 @@ const BLOCK_META_REGISTRY: Record = { cloudwatch: CloudWatchBlockMeta, codepipeline: CodePipelineBlockMeta, confluence: ConfluenceBlockMeta, + context_dev: ContextDevBlockMeta, convex: ConvexBlockMeta, crowdstrike: CrowdStrikeBlockMeta, cursor: CursorBlockMeta, @@ -824,6 +829,7 @@ const BLOCK_META_REGISTRY: Record = { slack: SlackBlockMeta, spotify: SpotifyBlockMeta, sqs: SQSBlockMeta, + square: SquareBlockMeta, stagehand: StagehandBlockMeta, stripe: StripeBlockMeta, sts: STSBlockMeta, diff --git a/apps/sim/components/emcn/components/chip-modal/chip-modal.tsx b/apps/sim/components/emcn/components/chip-modal/chip-modal.tsx index fc6826aaee7..6d98dd2d875 100644 --- a/apps/sim/components/emcn/components/chip-modal/chip-modal.tsx +++ b/apps/sim/components/emcn/components/chip-modal/chip-modal.tsx @@ -62,8 +62,12 @@ import { Loader } from '@/components/emcn/icons' import { cn } from '@/lib/core/utils/cn' import { quickValidateEmail } from '@/lib/messaging/email/validation' -/** Shared inset separator used by the header and footer edges. */ -function ChipModalSeparator({ className }: { className?: string }) { +/** + * The modal's hairline divider — used by the header and footer edges, and + * exported so body sections (e.g. a settings band below a prompt) can draw the + * same line instead of re-deriving the `h-px bg-[var(--border)]` string. + */ +export function ChipModalSeparator({ className }: { className?: string }) { return
} diff --git a/apps/sim/components/emcn/components/index.ts b/apps/sim/components/emcn/components/index.ts index 96f730c5647..ae022fe63b2 100644 --- a/apps/sim/components/emcn/components/index.ts +++ b/apps/sim/components/emcn/components/index.ts @@ -53,6 +53,7 @@ export { ChipModalPromptBody, type ChipModalPromptBodyProps, type ChipModalProps, + ChipModalSeparator, type ChipModalTab, ChipModalTabs, type ChipModalTabsProps, diff --git a/apps/sim/components/icons.tsx b/apps/sim/components/icons.tsx index 8ea1529b1e8..2d6b6eb2c03 100644 --- a/apps/sim/components/icons.tsx +++ b/apps/sim/components/icons.tsx @@ -1958,6 +1958,17 @@ export function WhatsAppIcon(props: SVGProps) { ) } +export function SquareIcon(props: SVGProps) { + return ( + + + + ) +} + export function StripeIcon(props: SVGProps) { return ( ) { ) } +export function ContextDevIcon(props: SVGProps) { + return ( + + + + ) +} + export function ConvexIcon(props: SVGProps) { return ( { - const blocks = getAllBlocks().filter((b) => !b.hideFromToolbar && b.type !== 'start_trigger') + const blocks = getAllBlocks().filter((b) => !isBlockTypeAccessControlExempt(b.type)) return blocks.sort((a, b) => { const categoryOrder = { triggers: 0, blocks: 1, tools: 2 } const catA = categoryOrder[a.category] ?? 3 diff --git a/apps/sim/ee/access-control/utils/permission-check.test.ts b/apps/sim/ee/access-control/utils/permission-check.test.ts index a472579bbed..a28fd7ae417 100644 --- a/apps/sim/ee/access-control/utils/permission-check.test.ts +++ b/apps/sim/ee/access-control/utils/permission-check.test.ts @@ -9,6 +9,7 @@ const { mockIsOrganizationOnEnterprisePlan, mockGetWorkspaceWithOwner, mockGetProviderFromModel, + mockGetBlock, mockExplicitGroup, mockDefaultGroup, } = vi.hoisted(() => ({ @@ -40,6 +41,7 @@ const { mockIsOrganizationOnEnterprisePlan: vi.fn<() => Promise>(), mockGetWorkspaceWithOwner: vi.fn<() => Promise<{ organizationId: string | null } | null>>(), mockGetProviderFromModel: vi.fn<(model: string) => string>(), + mockGetBlock: vi.fn<(type: string) => { hideFromToolbar?: boolean } | undefined>(), // The explicit-group query joins permission_group_member -> permission_group; // the org-default query selects permission_group directly. The db mock returns // the explicit rows when `innerJoin` was called and the default rows otherwise. @@ -108,6 +110,11 @@ vi.mock('@/providers/utils', () => ({ getProviderFromModel: mockGetProviderFromModel, })) +vi.mock('@/blocks/registry', () => ({ + getBlock: mockGetBlock, + getAllBlocks: vi.fn(() => []), +})) + import { assertPermissionsAllowed, CustomToolsNotAllowedError, @@ -128,6 +135,15 @@ function setEnterpriseOrgWorkspace() { mockIsOrganizationOnEnterprisePlan.mockResolvedValue(true) } +/** + * Default every block to non-legacy. `vi.clearAllMocks()` (used by the + * describe-level hooks) keeps implementations, so reset here to stop a legacy + * `getBlock` implementation set in one test from leaking into later ones. + */ +beforeEach(() => { + mockGetBlock.mockImplementation(() => undefined) +}) + describe('IntegrationNotAllowedError', () => { it.concurrent('creates error with correct name and message', () => { const error = new IntegrationNotAllowedError('discord') @@ -280,6 +296,14 @@ describe('validateBlockType', () => { await validateBlockType(undefined, undefined, 'start_trigger') }) + it('always allows legacy blocks hidden from the toolbar', async () => { + mockGetBlock.mockImplementation((type) => + type === 'notion' ? { hideFromToolbar: true } : undefined + ) + + await validateBlockType(undefined, undefined, 'notion') + }) + it('matches case-insensitively', async () => { await validateBlockType(undefined, undefined, 'Slack') await validateBlockType(undefined, undefined, 'GOOGLE_DRIVE') @@ -445,6 +469,19 @@ describe('assertPermissionsAllowed', () => { ).rejects.toBeInstanceOf(IntegrationNotAllowedError) }) + it('exempts legacy blocks from the integration allowlist', async () => { + mockExplicitGroup.value = [{ config: { allowedIntegrations: ['slack'] } }] + mockGetBlock.mockImplementation((type) => + type === 'notion' ? { hideFromToolbar: true } : undefined + ) + + await assertPermissionsAllowed({ + userId: 'user-123', + workspaceId: 'workspace-1', + blockType: 'notion', + }) + }) + it('throws CustomToolsNotAllowedError when custom tools are disabled', async () => { mockExplicitGroup.value = [{ config: { disableCustomTools: true } }] diff --git a/apps/sim/ee/access-control/utils/permission-check.ts b/apps/sim/ee/access-control/utils/permission-check.ts index 20f3d92fbb9..7d304ea42a2 100644 --- a/apps/sim/ee/access-control/utils/permission-check.ts +++ b/apps/sim/ee/access-control/utils/permission-check.ts @@ -10,6 +10,7 @@ import { isInvitationsDisabled, isPublicApiDisabled, } from '@/lib/core/config/feature-flags' +import { isBlockTypeAccessControlExempt } from '@/lib/permission-groups/block-access' import { DEFAULT_PERMISSION_GROUP_CONFIG, type PermissionGroupConfig, @@ -287,7 +288,7 @@ export async function validateBlockType( blockType: string, ctx?: ExecutionContext ): Promise { - if (blockType === 'start_trigger') { + if (isBlockTypeAccessControlExempt(blockType)) { return } @@ -478,10 +479,10 @@ interface PermissionAssertion { export async function assertPermissionsAllowed(req: PermissionAssertion): Promise { const { userId, workspaceId, model, blockType, toolKind, ctx } = req - if (blockType === 'start_trigger') { - if (!model && !toolKind) { - return - } + const blockTypeExempt = blockType ? isBlockTypeAccessControlExempt(blockType) : false + + if (blockTypeExempt && !model && !toolKind) { + return } const config = @@ -509,7 +510,7 @@ export async function assertPermissionsAllowed(req: PermissionAssertion): Promis } } - if (blockType && blockType !== 'start_trigger') { + if (blockType && !blockTypeExempt) { if (config && config.allowedIntegrations !== null) { if (!config.allowedIntegrations.includes(blockType.toLowerCase())) { const envAllowlist = getAllowedIntegrationsFromEnv() diff --git a/apps/sim/ee/audit-logs/components/audit-logs.tsx b/apps/sim/ee/audit-logs/components/audit-logs.tsx index 717b66288a9..304a3817afe 100644 --- a/apps/sim/ee/audit-logs/components/audit-logs.tsx +++ b/apps/sim/ee/audit-logs/components/audit-logs.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { createLogger } from '@sim/logger' import { formatDateTime } from '@sim/utils/formatting' +import { isRecordLike } from '@sim/utils/object' import { ChevronDown } from 'lucide-react' import { Badge, @@ -51,10 +52,6 @@ function formatAction(action: string): string { return action.replace(/[._]/g, ' ') } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function formatMetadataLabel(key: string): string { return key .replace(/([a-z0-9])([A-Z])/g, '$1 $2') @@ -99,14 +96,14 @@ function renderMetadataValue(value: unknown) { ) } - if (isRecord(value)) { + if (isRecordLike(value)) { const entries = Object.entries(value).filter(([, nestedValue]) => nestedValue !== undefined) if (entries.length === 0) { return None } const hasComplexValues = entries.some(([, nestedValue]) => { - return Array.isArray(nestedValue) || isRecord(nestedValue) + return Array.isArray(nestedValue) || isRecordLike(nestedValue) }) if (!hasComplexValues) { @@ -136,7 +133,7 @@ function renderMetadataValue(value: unknown) { } function getMetadataEntries(metadata: unknown) { - if (!isRecord(metadata)) return [] + if (!isRecordLike(metadata)) return [] return Object.entries(metadata).filter(([key, value]) => { if (value === undefined) return false diff --git a/apps/sim/executor/execution/state.ts b/apps/sim/executor/execution/state.ts index c12cca8bb86..8f7567d06a8 100644 --- a/apps/sim/executor/execution/state.ts +++ b/apps/sim/executor/execution/state.ts @@ -1,24 +1,22 @@ import type { BlockStateController } from '@/executor/execution/types' import type { BlockState, NormalizedBlockOutput } from '@/executor/types' +import { SubflowNodeIdCodec } from '@/executor/utils/subflow-node-id-codec' import { buildOuterBranchScopedId, extractOuterBranchIndex, stripCloneSuffixes, } from '@/executor/utils/subflow-utils' -const BRANCH_SUFFIX_PATTERN = /₍\d+₎/u -const LOOP_SUFFIX_PATTERN = /_loop\d+/ - function normalizeLookupId(id: string): string { - return id.replace(/₍\d+₎/gu, '').replace(/_loop\d+/g, '') + return SubflowNodeIdCodec.normalizeLookupId(id) } function extractBranchSuffix(id: string): string { - return id.match(BRANCH_SUFFIX_PATTERN)?.[0] ?? '' + return SubflowNodeIdCodec.extractBranchSuffix(id) } function extractLoopSuffix(id: string): string { - return id.match(LOOP_SUFFIX_PATTERN)?.[0] ?? '' + return SubflowNodeIdCodec.extractLoopSuffix(id) } export interface LoopScope { iteration: number diff --git a/apps/sim/executor/utils/start-block.ts b/apps/sim/executor/utils/start-block.ts index ddd75ce221c..1c59a9cb2d4 100644 --- a/apps/sim/executor/utils/start-block.ts +++ b/apps/sim/executor/utils/start-block.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { inferContextFromKey, isInternalFileUrl, @@ -108,10 +109,6 @@ export function buildResolutionFromBlock(block: SerializedBlock): ExecutorStartR } } -function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function readMetadataSubBlockValue(block: SerializedBlock, key: string): unknown { const metadata = block.metadata if (!metadata || typeof metadata !== 'object') { @@ -140,7 +137,7 @@ function extractInputFormat(block: SerializedBlock): InputFormatField[] { } return source - .filter((field): field is InputFormatField => isPlainObject(field)) + .filter((field): field is InputFormatField => isRecordLike(field)) .map((field) => field) } @@ -291,11 +288,11 @@ function deriveInputFromFormat( if (!fieldName) continue let fieldValue: unknown - const workflowRecord = isPlainObject(workflowInput) ? workflowInput : undefined + const workflowRecord = isRecordLike(workflowInput) ? workflowInput : undefined if (workflowRecord) { const inputContainer = workflowRecord.input - if (isPlainObject(inputContainer) && Object.hasOwn(inputContainer, fieldName)) { + if (isRecordLike(inputContainer) && Object.hasOwn(inputContainer, fieldName)) { fieldValue = inputContainer[fieldName] } else if (Object.hasOwn(workflowRecord, fieldName)) { fieldValue = workflowRecord[fieldName] @@ -321,14 +318,14 @@ function deriveInputFromFormat( } function getRawInputCandidate(workflowInput: unknown): unknown { - if (isPlainObject(workflowInput) && Object.hasOwn(workflowInput, 'input')) { + if (isRecordLike(workflowInput) && Object.hasOwn(workflowInput, 'input')) { return workflowInput.input } return workflowInput } function normalizeStartFile(file: unknown): UserFile | null { - if (!isPlainObject(file)) { + if (!isRecordLike(file)) { return null } @@ -378,7 +375,7 @@ function normalizeStartFile(file: unknown): UserFile | null { } function getFilesFromWorkflowInput(workflowInput: unknown): UserFile[] | undefined { - if (!isPlainObject(workflowInput)) { + if (!isRecordLike(workflowInput)) { return undefined } const files = workflowInput.files @@ -400,7 +397,7 @@ function mergeFilesIntoOutput( const files = getFilesFromWorkflowInput(workflowInput) if (files) { output.files = files - } else if (isPlainObject(workflowInput) && Object.hasOwn(workflowInput, 'files')) { + } else if (isRecordLike(workflowInput) && Object.hasOwn(workflowInput, 'files')) { output.files = undefined } return output @@ -424,7 +421,7 @@ function buildUnifiedStartOutput( } } - if (isPlainObject(workflowInput)) { + if (isRecordLike(workflowInput)) { for (const [key, value] of Object.entries(workflowInput)) { if (key === 'onUploadError') continue // Skip keys already set by schema-coerced structuredInput to @@ -441,7 +438,7 @@ function buildUnifiedStartOutput( if (!Object.hasOwn(output, 'input')) { const fallbackInput = - isPlainObject(workflowInput) && typeof workflowInput.input !== 'undefined' + isRecordLike(workflowInput) && typeof workflowInput.input !== 'undefined' ? ensureString(workflowInput.input) : '' output.input = fallbackInput ? fallbackInput : undefined @@ -451,7 +448,7 @@ function buildUnifiedStartOutput( if (!Object.hasOwn(output, 'conversationId')) { const conversationId = - isPlainObject(workflowInput) && workflowInput.conversationId + isRecordLike(workflowInput) && workflowInput.conversationId ? ensureString(workflowInput.conversationId) : undefined if (conversationId) { @@ -465,7 +462,7 @@ function buildUnifiedStartOutput( } function buildApiOrInputOutput(finalInput: unknown, workflowInput: unknown): NormalizedBlockOutput { - const isObjectInput = isPlainObject(finalInput) + const isObjectInput = isRecordLike(finalInput) const output: NormalizedBlockOutput = isObjectInput ? { @@ -478,7 +475,7 @@ function buildApiOrInputOutput(finalInput: unknown, workflowInput: unknown): Nor } function buildChatOutput(workflowInput: unknown): NormalizedBlockOutput { - const source = isPlainObject(workflowInput) ? workflowInput : undefined + const source = isRecordLike(workflowInput) ? workflowInput : undefined const output: NormalizedBlockOutput = { input: ensureString(source?.input), @@ -502,7 +499,7 @@ function buildLegacyStarterOutput( } const output: NormalizedBlockOutput = {} - const finalObject = isPlainObject(finalInput) ? finalInput : undefined + const finalObject = isRecordLike(finalInput) ? finalInput : undefined if (finalObject) { safeAssign(output, finalObject) @@ -511,7 +508,7 @@ function buildLegacyStarterOutput( output.input = finalInput } - const conversationId = isPlainObject(workflowInput) ? workflowInput.conversationId : undefined + const conversationId = isRecordLike(workflowInput) ? workflowInput.conversationId : undefined if (conversationId) { output.conversationId = ensureString(conversationId) } @@ -523,9 +520,7 @@ function buildManualTriggerOutput( finalInput: unknown, workflowInput: unknown ): NormalizedBlockOutput { - const finalObject = isPlainObject(finalInput) - ? (finalInput as Record) - : undefined + const finalObject = isRecordLike(finalInput) ? (finalInput as Record) : undefined const output: NormalizedBlockOutput = finalObject ? { ...finalObject } : { input: finalInput } @@ -550,7 +545,7 @@ function buildIntegrationTriggerOutput( } } - if (isPlainObject(workflowInput)) { + if (isRecordLike(workflowInput)) { for (const [key, value] of Object.entries(workflowInput)) { if (structuredKeys?.has(key)) continue if (value !== undefined && value !== null) { diff --git a/apps/sim/executor/utils/subflow-node-id-codec.test.ts b/apps/sim/executor/utils/subflow-node-id-codec.test.ts new file mode 100644 index 00000000000..c38fdc3ecc3 --- /dev/null +++ b/apps/sim/executor/utils/subflow-node-id-codec.test.ts @@ -0,0 +1,175 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { SubflowNodeIdCodec } from '@/executor/utils/subflow-node-id-codec' + +describe('SubflowNodeIdCodec', () => { + describe('branch subscripts', () => { + it('builds and round-trips branch node IDs', () => { + const id = SubflowNodeIdCodec.buildBranchNodeId('block-1', 2) + expect(id).toBe('block-1₍2₎') + expect(SubflowNodeIdCodec.isBranchNodeId(id)).toBe(true) + expect(SubflowNodeIdCodec.extractBaseBlockId(id)).toBe('block-1') + expect(SubflowNodeIdCodec.extractBranchIndex(id)).toBe(2) + }) + + it('returns null index and false predicate for non-branch IDs', () => { + expect(SubflowNodeIdCodec.isBranchNodeId('block-1')).toBe(false) + expect(SubflowNodeIdCodec.extractBranchIndex('block-1')).toBeNull() + expect(SubflowNodeIdCodec.extractBaseBlockId('block-1')).toBe('block-1') + }) + + it('only strips a trailing branch subscript', () => { + expect(SubflowNodeIdCodec.extractBaseBlockId('a₍1₎b')).toBe('a₍1₎b') + expect(SubflowNodeIdCodec.extractBaseBlockId('a₍1₎b₍2₎')).toBe('a₍1₎b') + }) + }) + + describe('loop sentinels', () => { + it('builds and parses loop sentinel IDs', () => { + const start = SubflowNodeIdCodec.buildLoopSentinelStartId('loop-1') + const end = SubflowNodeIdCodec.buildLoopSentinelEndId('loop-1') + expect(start).toBe('loop-loop-1-sentinel-start') + expect(end).toBe('loop-loop-1-sentinel-end') + expect(SubflowNodeIdCodec.isLoopSentinelNodeId(start)).toBe(true) + expect(SubflowNodeIdCodec.isLoopSentinelNodeId(end)).toBe(true) + expect(SubflowNodeIdCodec.extractLoopIdFromSentinel(start)).toBe('loop-1') + expect(SubflowNodeIdCodec.extractLoopIdFromSentinel(end)).toBe('loop-1') + }) + + it('returns null when not a loop sentinel', () => { + expect(SubflowNodeIdCodec.isLoopSentinelNodeId('block-1')).toBe(false) + expect(SubflowNodeIdCodec.extractLoopIdFromSentinel('block-1')).toBeNull() + }) + }) + + describe('parallel sentinels', () => { + it('builds and parses parallel sentinel IDs', () => { + const start = SubflowNodeIdCodec.buildParallelSentinelStartId('p-1') + const end = SubflowNodeIdCodec.buildParallelSentinelEndId('p-1') + expect(start).toBe('parallel-p-1-sentinel-start') + expect(end).toBe('parallel-p-1-sentinel-end') + expect(SubflowNodeIdCodec.isParallelSentinelNodeId(start)).toBe(true) + expect(SubflowNodeIdCodec.isParallelSentinelNodeId(end)).toBe(true) + expect(SubflowNodeIdCodec.extractParallelIdFromSentinel(start)).toBe('p-1') + expect(SubflowNodeIdCodec.extractParallelIdFromSentinel(end)).toBe('p-1') + }) + + it('returns null when not a parallel sentinel', () => { + expect(SubflowNodeIdCodec.isParallelSentinelNodeId('block-1')).toBe(false) + expect(SubflowNodeIdCodec.extractParallelIdFromSentinel('block-1')).toBeNull() + }) + }) + + describe('outer-branch clone scoping', () => { + it('builds and extracts outer branch index', () => { + const id = SubflowNodeIdCodec.buildOuterBranchScopedId('loop-1', 3) + expect(id).toBe('loop-1__obranch-3') + expect(SubflowNodeIdCodec.extractOuterBranchIndex(id)).toBe(3) + }) + + it('extracts the innermost outer branch index for nested clones', () => { + const id = 'loop-1__obranch-2__obranch-5' + expect(SubflowNodeIdCodec.extractOuterBranchIndex(id)).toBe(2) + expect(SubflowNodeIdCodec.extractInnermostOuterBranchIndex(id)).toBe(5) + }) + + it('returns undefined when no outer branch suffix is present', () => { + expect(SubflowNodeIdCodec.extractOuterBranchIndex('loop-1')).toBeUndefined() + expect(SubflowNodeIdCodec.extractInnermostOuterBranchIndex('loop-1')).toBeUndefined() + }) + + it('strips outer-branch and clone-digest suffixes', () => { + expect(SubflowNodeIdCodec.stripOuterBranchSuffix('loop-1__obranch-2')).toBe('loop-1') + expect(SubflowNodeIdCodec.stripOuterBranchSuffix('loop-1__cloneABCDEF__obranch-2')).toBe( + 'loop-1' + ) + }) + + it('strips all clone suffixes and branch subscripts to the base block ID', () => { + expect(SubflowNodeIdCodec.stripCloneSuffixes('block-1__obranch-2₍3₎')).toBe('block-1') + expect(SubflowNodeIdCodec.stripCloneSuffixes('block-1__clone0a1f__obranch-2₍0₎')).toBe( + 'block-1' + ) + }) + }) + + describe('normalizeNodeId', () => { + it('normalizes branch, loop sentinel, and parallel sentinel IDs', () => { + expect(SubflowNodeIdCodec.normalizeNodeId('block-1₍2₎')).toBe('block-1') + expect(SubflowNodeIdCodec.normalizeNodeId('loop-loop-1-sentinel-start')).toBe('loop-1') + expect(SubflowNodeIdCodec.normalizeNodeId('parallel-p-1-sentinel-end')).toBe('p-1') + expect(SubflowNodeIdCodec.normalizeNodeId('block-1')).toBe('block-1') + }) + }) + + describe('loop digest lookup helpers', () => { + it('strips branch subscripts and loop digests for lookup keys', () => { + expect(SubflowNodeIdCodec.normalizeLookupId('block-1₍2₎_loop3')).toBe('block-1') + expect(SubflowNodeIdCodec.normalizeLookupId('block-1')).toBe('block-1') + }) + + it('extracts the leading branch suffix and loop digest segments', () => { + expect(SubflowNodeIdCodec.extractBranchSuffix('block-1₍2₎_loop3')).toBe('₍2₎') + expect(SubflowNodeIdCodec.extractBranchSuffix('block-1')).toBe('') + expect(SubflowNodeIdCodec.extractLoopSuffix('block-1₍2₎_loop3')).toBe('_loop3') + expect(SubflowNodeIdCodec.extractLoopSuffix('block-1')).toBe('') + }) + }) + + describe('findEffectiveContainerId', () => { + it('returns the original ID for branch 0 / missing scope', () => { + const map = new Map([['loop-1', {}]]) + expect(SubflowNodeIdCodec.findEffectiveContainerId('loop-1', 'block-1', map)).toBe('loop-1') + }) + + it('prefers the mapped cloned scope when present', () => { + const map = new Map([ + ['loop-1', {}], + ['loop-1__obranch-2', {}], + ]) + expect(SubflowNodeIdCodec.findEffectiveContainerId('loop-1', 'block-1', map, 2)).toBe( + 'loop-1__obranch-2' + ) + }) + + it('resolves the cloned scope from the current node ID suffix', () => { + const map = new Map([ + ['loop-1', {}], + ['loop-1__obranch-3', {}], + ]) + expect(SubflowNodeIdCodec.findEffectiveContainerId('loop-1', 'block-1__obranch-3', map)).toBe( + 'loop-1__obranch-3' + ) + }) + + it('prefers __clone scopes when the current node carries a clone marker', () => { + const map = new Map([ + ['loop-1__obranch-2', {}], + ['loop-1__cloneabc__obranch-2', {}], + ]) + expect( + SubflowNodeIdCodec.findEffectiveContainerId('loop-1', 'block-1__cloneabc__obranch-2', map) + ).toBe('loop-1__cloneabc__obranch-2') + }) + }) + + describe('round-trip parse ∘ build', () => { + it('builds then parses branch IDs symmetrically', () => { + for (const index of [0, 1, 7, 20]) { + const id = SubflowNodeIdCodec.buildBranchNodeId('base-id', index) + expect(SubflowNodeIdCodec.extractBranchIndex(id)).toBe(index) + expect(SubflowNodeIdCodec.extractBaseBlockId(id)).toBe('base-id') + } + }) + + it('builds then parses outer-branch scoped IDs symmetrically', () => { + for (const index of [1, 4, 19]) { + const id = SubflowNodeIdCodec.buildOuterBranchScopedId('base-id', index) + expect(SubflowNodeIdCodec.extractOuterBranchIndex(id)).toBe(index) + expect(SubflowNodeIdCodec.stripOuterBranchSuffix(id)).toBe('base-id') + } + }) + }) +}) diff --git a/apps/sim/executor/utils/subflow-node-id-codec.ts b/apps/sim/executor/utils/subflow-node-id-codec.ts new file mode 100644 index 00000000000..8b7aa2ecdff --- /dev/null +++ b/apps/sim/executor/utils/subflow-node-id-codec.ts @@ -0,0 +1,263 @@ +import { LOOP, PARALLEL } from '@/executor/constants' + +/** + * Single source of truth for parsing and building subflow node IDs. + * + * Runtime node IDs layer several encodings onto a workflow-level block ID: + * - Branch subscripts `₍N₎` mark a parallel branch instance. + * - Loop/parallel sentinels wrap a container ID (`loop-{id}-sentinel-start`). + * - Outer-branch clone suffixes `__obranch-N` and clone digests `__clone{hex}` + * scope a cloned subflow to a global outer parallel branch. + * - Loop digests `_loopN` scope a block output to a loop iteration. + * + * All regexes and string templates for these encodings live here so callers + * never reconstruct them inline. + */ + +const SENTINEL = { + LOOP_START: new RegExp(`${LOOP.SENTINEL.PREFIX}(.+)${LOOP.SENTINEL.START_SUFFIX}`), + LOOP_END: new RegExp(`${LOOP.SENTINEL.PREFIX}(.+)${LOOP.SENTINEL.END_SUFFIX}`), + PARALLEL_START: new RegExp(`${PARALLEL.SENTINEL.PREFIX}(.+)${PARALLEL.SENTINEL.START_SUFFIX}`), + PARALLEL_END: new RegExp(`${PARALLEL.SENTINEL.PREFIX}(.+)${PARALLEL.SENTINEL.END_SUFFIX}`), +} as const + +const BRANCH = { + MATCH: new RegExp(`${PARALLEL.BRANCH.PREFIX}\\d+${PARALLEL.BRANCH.SUFFIX}$`), + INDEX: new RegExp(`${PARALLEL.BRANCH.PREFIX}(\\d+)${PARALLEL.BRANCH.SUFFIX}$`), + SUFFIX: /₍\d+₎/u, + SUFFIX_GLOBAL: /₍\d+₎/gu, +} as const + +const OUTER_BRANCH = { + MATCH: /__obranch-(\d+)/, + MATCH_GLOBAL: /__obranch-(\d+)/g, + STRIP: /__obranch-\d+/g, +} as const + +const CLONE = { + DIGEST_STRIP: /__clone[0-9a-f]+/gi, + MARKER: '__clone', +} as const + +const LOOP_DIGEST = { + MATCH: /_loop\d+/, + STRIP: /_loop\d+/g, +} as const + +/** + * Builds the loop sentinel-start node ID for a container. + */ +function buildLoopSentinelStartId(loopId: string): string { + return `${LOOP.SENTINEL.PREFIX}${loopId}${LOOP.SENTINEL.START_SUFFIX}` +} + +/** + * Builds the loop sentinel-end node ID for a container. + */ +function buildLoopSentinelEndId(loopId: string): string { + return `${LOOP.SENTINEL.PREFIX}${loopId}${LOOP.SENTINEL.END_SUFFIX}` +} + +/** + * Builds the parallel sentinel-start node ID for a container. + */ +function buildParallelSentinelStartId(parallelId: string): string { + return `${PARALLEL.SENTINEL.PREFIX}${parallelId}${PARALLEL.SENTINEL.START_SUFFIX}` +} + +/** + * Builds the parallel sentinel-end node ID for a container. + */ +function buildParallelSentinelEndId(parallelId: string): string { + return `${PARALLEL.SENTINEL.PREFIX}${parallelId}${PARALLEL.SENTINEL.END_SUFFIX}` +} + +function isLoopSentinelNodeId(nodeId: string): boolean { + return ( + nodeId.startsWith(LOOP.SENTINEL.PREFIX) && + (nodeId.endsWith(LOOP.SENTINEL.START_SUFFIX) || nodeId.endsWith(LOOP.SENTINEL.END_SUFFIX)) + ) +} + +function isParallelSentinelNodeId(nodeId: string): boolean { + return ( + nodeId.startsWith(PARALLEL.SENTINEL.PREFIX) && + (nodeId.endsWith(PARALLEL.SENTINEL.START_SUFFIX) || + nodeId.endsWith(PARALLEL.SENTINEL.END_SUFFIX)) + ) +} + +function extractLoopIdFromSentinel(sentinelId: string): string | null { + const startMatch = sentinelId.match(SENTINEL.LOOP_START) + if (startMatch) return startMatch[1] + const endMatch = sentinelId.match(SENTINEL.LOOP_END) + if (endMatch) return endMatch[1] + return null +} + +function extractParallelIdFromSentinel(sentinelId: string): string | null { + const startMatch = sentinelId.match(SENTINEL.PARALLEL_START) + if (startMatch) return startMatch[1] + const endMatch = sentinelId.match(SENTINEL.PARALLEL_END) + if (endMatch) return endMatch[1] + return null +} + +function buildBranchNodeId(baseId: string, branchIndex: number): string { + return `${baseId}${PARALLEL.BRANCH.PREFIX}${branchIndex}${PARALLEL.BRANCH.SUFFIX}` +} + +function extractBaseBlockId(branchNodeId: string): string { + return branchNodeId.replace(BRANCH.MATCH, '') +} + +function extractBranchIndex(branchNodeId: string): number | null { + const match = branchNodeId.match(BRANCH.INDEX) + return match ? Number.parseInt(match[1], 10) : null +} + +function isBranchNodeId(nodeId: string): boolean { + return BRANCH.MATCH.test(nodeId) +} + +function extractOuterBranchIndex(clonedId: string): number | undefined { + const match = clonedId.match(OUTER_BRANCH.MATCH) + return match ? Number.parseInt(match[1], 10) : undefined +} + +function extractInnermostOuterBranchIndex(clonedId: string): number | undefined { + const matches = Array.from(clonedId.matchAll(OUTER_BRANCH.MATCH_GLOBAL)) + const lastMatch = matches.at(-1) + return lastMatch ? Number.parseInt(lastMatch[1], 10) : undefined +} + +function stripCloneSuffixes(nodeId: string): string { + return extractBaseBlockId(nodeId.replace(OUTER_BRANCH.STRIP, '').replace(CLONE.DIGEST_STRIP, '')) +} + +function buildOuterBranchScopedId(originalId: string, branchIndex: number): string { + return `${originalId}__obranch-${branchIndex}` +} + +function stripOuterBranchSuffix(id: string): string { + return id.replace(OUTER_BRANCH.STRIP, '').replace(CLONE.DIGEST_STRIP, '') +} + +function hasCloneMarker(id: string): boolean { + return id.includes(CLONE.MARKER) +} + +function normalizeNodeId(nodeId: string): string { + if (isBranchNodeId(nodeId)) { + return extractBaseBlockId(nodeId) + } + if (isLoopSentinelNodeId(nodeId)) { + return extractLoopIdFromSentinel(nodeId) || nodeId + } + if (isParallelSentinelNodeId(nodeId)) { + return extractParallelIdFromSentinel(nodeId) || nodeId + } + return nodeId +} + +function findEffectiveContainerId( + originalId: string, + currentNodeId: string, + executionMap: Map, + mappedBranchIndex?: number +): string { + if (mappedBranchIndex !== undefined && mappedBranchIndex > 0) { + const cloneSuffix = `__obranch-${mappedBranchIndex}` + const candidateId = buildOuterBranchScopedId(originalId, mappedBranchIndex) + if (executionMap.has(candidateId)) { + return candidateId + } + + for (const scopeId of executionMap.keys()) { + if (scopeId.endsWith(cloneSuffix) && stripOuterBranchSuffix(scopeId) === originalId) { + return scopeId + } + } + } + + const match = currentNodeId.match(OUTER_BRANCH.MATCH) + if (match) { + const branchIndex = Number.parseInt(match[1], 10) + const cloneSuffix = `__obranch-${branchIndex}` + if (hasCloneMarker(currentNodeId)) { + for (const scopeId of executionMap.keys()) { + if ( + hasCloneMarker(scopeId) && + scopeId.endsWith(cloneSuffix) && + stripOuterBranchSuffix(scopeId) === originalId + ) { + return scopeId + } + } + } + + const candidateId = buildOuterBranchScopedId(originalId, branchIndex) + if (executionMap.has(candidateId)) { + return candidateId + } + + for (const scopeId of executionMap.keys()) { + if (scopeId.endsWith(cloneSuffix) && stripOuterBranchSuffix(scopeId) === originalId) { + return scopeId + } + } + } + + return originalId +} + +/** + * Strips branch subscripts (`₍N₎`) and loop digests (`_loopN`) from a node ID, + * yielding the lookup key used by execution-state block-output resolution. + */ +function normalizeLookupId(id: string): string { + return id.replace(BRANCH.SUFFIX_GLOBAL, '').replace(LOOP_DIGEST.STRIP, '') +} + +/** + * Returns the leading branch subscript (`₍N₎`) of a node ID, or '' when absent. + */ +function extractBranchSuffix(id: string): string { + return id.match(BRANCH.SUFFIX)?.[0] ?? '' +} + +/** + * Returns the loop digest segment (`_loopN`) of a node ID, or '' when absent. + */ +function extractLoopSuffix(id: string): string { + return id.match(LOOP_DIGEST.MATCH)?.[0] ?? '' +} + +/** + * Codec exposing all subflow node-ID parsing/building operations as a single, + * pattern-free interface. Implementation owns every regex and string template. + */ +export const SubflowNodeIdCodec = { + buildLoopSentinelStartId, + buildLoopSentinelEndId, + buildParallelSentinelStartId, + buildParallelSentinelEndId, + isLoopSentinelNodeId, + isParallelSentinelNodeId, + extractLoopIdFromSentinel, + extractParallelIdFromSentinel, + buildBranchNodeId, + extractBaseBlockId, + extractBranchIndex, + isBranchNodeId, + extractOuterBranchIndex, + extractInnermostOuterBranchIndex, + stripCloneSuffixes, + buildOuterBranchScopedId, + stripOuterBranchSuffix, + normalizeNodeId, + findEffectiveContainerId, + normalizeLookupId, + extractBranchSuffix, + extractLoopSuffix, +} as const diff --git a/apps/sim/executor/utils/subflow-utils.ts b/apps/sim/executor/utils/subflow-utils.ts index 8a5846b7a5c..9cd0b44f27d 100644 --- a/apps/sim/executor/utils/subflow-utils.ts +++ b/apps/sim/executor/utils/subflow-utils.ts @@ -1,57 +1,42 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' -import { DEFAULTS, LOOP, PARALLEL } from '@/executor/constants' +import { DEFAULTS } from '@/executor/constants' import type { ContextExtensions } from '@/executor/execution/types' import { type BlockLog, type ExecutionContext, getNextExecutionOrder } from '@/executor/types' import { buildContainerIterationContext } from '@/executor/utils/iteration-context' +import { SubflowNodeIdCodec } from '@/executor/utils/subflow-node-id-codec' import type { SerializedWorkflow } from '@/serializer/types' const logger = createLogger('SubflowUtils') -const BRANCH_PATTERN = new RegExp(`${PARALLEL.BRANCH.PREFIX}\\d+${PARALLEL.BRANCH.SUFFIX}$`) -const BRANCH_INDEX_PATTERN = new RegExp(`${PARALLEL.BRANCH.PREFIX}(\\d+)${PARALLEL.BRANCH.SUFFIX}$`) -const LOOP_SENTINEL_START_PATTERN = new RegExp( - `${LOOP.SENTINEL.PREFIX}(.+)${LOOP.SENTINEL.START_SUFFIX}` -) -const LOOP_SENTINEL_END_PATTERN = new RegExp( - `${LOOP.SENTINEL.PREFIX}(.+)${LOOP.SENTINEL.END_SUFFIX}` -) -const PARALLEL_SENTINEL_START_PATTERN = new RegExp( - `${PARALLEL.SENTINEL.PREFIX}(.+)${PARALLEL.SENTINEL.START_SUFFIX}` -) -const PARALLEL_SENTINEL_END_PATTERN = new RegExp( - `${PARALLEL.SENTINEL.PREFIX}(.+)${PARALLEL.SENTINEL.END_SUFFIX}` -) - +/** + * Builds the loop sentinel-start node ID for a container. + */ export function buildSentinelStartId(loopId: string): string { - return `${LOOP.SENTINEL.PREFIX}${loopId}${LOOP.SENTINEL.START_SUFFIX}` + return SubflowNodeIdCodec.buildLoopSentinelStartId(loopId) } +/** + * Builds the loop sentinel-end node ID for a container. + */ export function buildSentinelEndId(loopId: string): string { - return `${LOOP.SENTINEL.PREFIX}${loopId}${LOOP.SENTINEL.END_SUFFIX}` + return SubflowNodeIdCodec.buildLoopSentinelEndId(loopId) } export function buildParallelSentinelStartId(parallelId: string): string { - return `${PARALLEL.SENTINEL.PREFIX}${parallelId}${PARALLEL.SENTINEL.START_SUFFIX}` + return SubflowNodeIdCodec.buildParallelSentinelStartId(parallelId) } export function buildParallelSentinelEndId(parallelId: string): string { - return `${PARALLEL.SENTINEL.PREFIX}${parallelId}${PARALLEL.SENTINEL.END_SUFFIX}` + return SubflowNodeIdCodec.buildParallelSentinelEndId(parallelId) } export function isLoopSentinelNodeId(nodeId: string): boolean { - return ( - nodeId.startsWith(LOOP.SENTINEL.PREFIX) && - (nodeId.endsWith(LOOP.SENTINEL.START_SUFFIX) || nodeId.endsWith(LOOP.SENTINEL.END_SUFFIX)) - ) + return SubflowNodeIdCodec.isLoopSentinelNodeId(nodeId) } export function isParallelSentinelNodeId(nodeId: string): boolean { - return ( - nodeId.startsWith(PARALLEL.SENTINEL.PREFIX) && - (nodeId.endsWith(PARALLEL.SENTINEL.START_SUFFIX) || - nodeId.endsWith(PARALLEL.SENTINEL.END_SUFFIX)) - ) + return SubflowNodeIdCodec.isParallelSentinelNodeId(nodeId) } export function isSentinelNodeId(nodeId: string): boolean { @@ -59,19 +44,11 @@ export function isSentinelNodeId(nodeId: string): boolean { } export function extractLoopIdFromSentinel(sentinelId: string): string | null { - const startMatch = sentinelId.match(LOOP_SENTINEL_START_PATTERN) - if (startMatch) return startMatch[1] - const endMatch = sentinelId.match(LOOP_SENTINEL_END_PATTERN) - if (endMatch) return endMatch[1] - return null + return SubflowNodeIdCodec.extractLoopIdFromSentinel(sentinelId) } export function extractParallelIdFromSentinel(sentinelId: string): string | null { - const startMatch = sentinelId.match(PARALLEL_SENTINEL_START_PATTERN) - if (startMatch) return startMatch[1] - const endMatch = sentinelId.match(PARALLEL_SENTINEL_END_PATTERN) - if (endMatch) return endMatch[1] - return null + return SubflowNodeIdCodec.extractParallelIdFromSentinel(sentinelId) } /** @@ -79,39 +56,32 @@ export function extractParallelIdFromSentinel(sentinelId: string): string | null * Example: ("blockId", 2) → "blockId₍2₎" */ export function buildBranchNodeId(baseId: string, branchIndex: number): string { - return `${baseId}${PARALLEL.BRANCH.PREFIX}${branchIndex}${PARALLEL.BRANCH.SUFFIX}` + return SubflowNodeIdCodec.buildBranchNodeId(baseId, branchIndex) } + export function extractBaseBlockId(branchNodeId: string): string { - return branchNodeId.replace(BRANCH_PATTERN, '') + return SubflowNodeIdCodec.extractBaseBlockId(branchNodeId) } export function extractBranchIndex(branchNodeId: string): number | null { - const match = branchNodeId.match(BRANCH_INDEX_PATTERN) - return match ? Number.parseInt(match[1], 10) : null + return SubflowNodeIdCodec.extractBranchIndex(branchNodeId) } export function isBranchNodeId(nodeId: string): boolean { - return BRANCH_PATTERN.test(nodeId) + return SubflowNodeIdCodec.isBranchNodeId(nodeId) } -const OUTER_BRANCH_PATTERN = /__obranch-(\d+)/ -const OUTER_BRANCH_STRIP_PATTERN = /__obranch-\d+/g -const CLONE_DIGEST_STRIP_PATTERN = /__clone[0-9a-f]+/gi - /** * Extracts the outer branch index from a cloned subflow ID. * Cloned IDs follow the pattern `{originalId}__obranch-{index}`. * Returns undefined if the ID is not a clone. */ export function extractOuterBranchIndex(clonedId: string): number | undefined { - const match = clonedId.match(OUTER_BRANCH_PATTERN) - return match ? Number.parseInt(match[1], 10) : undefined + return SubflowNodeIdCodec.extractOuterBranchIndex(clonedId) } export function extractInnermostOuterBranchIndex(clonedId: string): number | undefined { - const matches = Array.from(clonedId.matchAll(/__obranch-(\d+)/g)) - const lastMatch = matches.at(-1) - return lastMatch ? Number.parseInt(lastMatch[1], 10) : undefined + return SubflowNodeIdCodec.extractInnermostOuterBranchIndex(clonedId) } /** @@ -119,23 +89,21 @@ export function extractInnermostOuterBranchIndex(clonedId: string): number | und * from a node ID, returning the original workflow-level block ID. */ export function stripCloneSuffixes(nodeId: string): string { - return extractBaseBlockId( - nodeId.replace(OUTER_BRANCH_STRIP_PATTERN, '').replace(CLONE_DIGEST_STRIP_PATTERN, '') - ) + return SubflowNodeIdCodec.stripCloneSuffixes(nodeId) } /** * Builds a stable ID for an output scoped to a global outer parallel branch. */ export function buildOuterBranchScopedId(originalId: string, branchIndex: number): string { - return `${originalId}__obranch-${branchIndex}` + return SubflowNodeIdCodec.buildOuterBranchScopedId(originalId, branchIndex) } /** * Builds a cloned subflow ID from an original ID and outer branch index. */ export function buildClonedSubflowId(originalId: string, branchIndex: number): string { - return buildOuterBranchScopedId(originalId, branchIndex) + return SubflowNodeIdCodec.buildOuterBranchScopedId(originalId, branchIndex) } /** @@ -143,7 +111,7 @@ export function buildClonedSubflowId(originalId: string, branchIndex: number): s * returning the original workflow-level subflow ID. */ export function stripOuterBranchSuffix(id: string): string { - return id.replace(OUTER_BRANCH_STRIP_PATTERN, '').replace(CLONE_DIGEST_STRIP_PATTERN, '') + return SubflowNodeIdCodec.stripOuterBranchSuffix(id) } /** @@ -163,67 +131,16 @@ export function findEffectiveContainerId( executionMap: Map, mappedBranchIndex?: number ): string { - if (mappedBranchIndex !== undefined && mappedBranchIndex > 0) { - const cloneSuffix = `__obranch-${mappedBranchIndex}` - const candidateId = buildClonedSubflowId(originalId, mappedBranchIndex) - if (executionMap.has(candidateId)) { - return candidateId - } - - for (const scopeId of executionMap.keys()) { - if (scopeId.endsWith(cloneSuffix) && stripOuterBranchSuffix(scopeId) === originalId) { - return scopeId - } - } - } - - // Prefer the cloned variant when currentNodeId carries an __obranch-N suffix. - // During concurrent parallel-in-loop execution both the original (branch 0) - // and cloned variants coexist in the map; the clone is the correct scope. - const match = currentNodeId.match(OUTER_BRANCH_PATTERN) - if (match) { - const branchIndex = Number.parseInt(match[1], 10) - const cloneSuffix = `__obranch-${branchIndex}` - if (currentNodeId.includes('__clone')) { - for (const scopeId of executionMap.keys()) { - if ( - scopeId.includes('__clone') && - scopeId.endsWith(cloneSuffix) && - stripOuterBranchSuffix(scopeId) === originalId - ) { - return scopeId - } - } - } - - const candidateId = buildClonedSubflowId(originalId, branchIndex) - if (executionMap.has(candidateId)) { - return candidateId - } - - for (const scopeId of executionMap.keys()) { - if (scopeId.endsWith(cloneSuffix) && stripOuterBranchSuffix(scopeId) === originalId) { - return scopeId - } - } - } - - // Return original ID — for branch-0 (non-cloned) or when scope is missing. - // Callers handle the missing-scope case gracefully. - return originalId + return SubflowNodeIdCodec.findEffectiveContainerId( + originalId, + currentNodeId, + executionMap, + mappedBranchIndex + ) } export function normalizeNodeId(nodeId: string): string { - if (isBranchNodeId(nodeId)) { - return extractBaseBlockId(nodeId) - } - if (isLoopSentinelNodeId(nodeId)) { - return extractLoopIdFromSentinel(nodeId) || nodeId - } - if (isParallelSentinelNodeId(nodeId)) { - return extractParallelIdFromSentinel(nodeId) || nodeId - } - return nodeId + return SubflowNodeIdCodec.normalizeNodeId(nodeId) } type SubflowContainerType = 'loop' | 'parallel' diff --git a/apps/sim/hooks/queries/custom-tools.ts b/apps/sim/hooks/queries/custom-tools.ts index 542cb8cd8a0..f5370f2e4ad 100644 --- a/apps/sim/hooks/queries/custom-tools.ts +++ b/apps/sim/hooks/queries/custom-tools.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { requestJson } from '@/lib/api/client/request' import { @@ -50,10 +51,6 @@ type ApiCustomTool = Partial & { code?: string } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function normalizeCustomTool(tool: ApiCustomTool, workspaceId: string): CustomToolDefinition { const fallbackName = tool.schema.function?.name || tool.id const parameters = tool.schema.function?.parameters ?? { @@ -104,7 +101,7 @@ async function fetchCustomTools( const normalizedTools: CustomToolDefinition[] = [] data.forEach((tool, index) => { - if (!isRecord(tool)) { + if (!isRecordLike(tool)) { logger.warn(`Skipping invalid tool at index ${index}: not an object`) return } @@ -116,18 +113,18 @@ async function fetchCustomTools( logger.warn(`Skipping invalid tool at index ${index}: missing or invalid title`) return } - if (!isRecord(tool.schema)) { + if (!isRecordLike(tool.schema)) { logger.warn(`Skipping invalid tool at index ${index}: missing or invalid schema`) return } - if (!isRecord(tool.schema.function)) { + if (!isRecordLike(tool.schema.function)) { logger.warn(`Skipping invalid tool at index ${index}: missing function schema`) return } const functionSchema = tool.schema.function - const parameters = isRecord(functionSchema.parameters) ? functionSchema.parameters : {} - const properties = isRecord(parameters.properties) ? parameters.properties : {} + const parameters = isRecordLike(functionSchema.parameters) ? functionSchema.parameters : {} + const properties = isRecordLike(parameters.properties) ? parameters.properties : {} const required = Array.isArray(parameters.required) ? parameters.required.filter((value): value is string => typeof value === 'string') : undefined diff --git a/apps/sim/hooks/queries/mothership-chats.ts b/apps/sim/hooks/queries/mothership-chats.ts index bc7743804d6..01a4bf01a6c 100644 --- a/apps/sim/hooks/queries/mothership-chats.ts +++ b/apps/sim/hooks/queries/mothership-chats.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { keepPreviousData, skipToken, @@ -60,10 +61,6 @@ export const mothershipChatKeys = { detail: (chatId: string | undefined) => [...mothershipChatKeys.details(), chatId ?? ''] as const, } -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function assertValid(condition: unknown, message: string): asserts condition { if (!condition) { throw new Error(message) @@ -82,7 +79,7 @@ function isResourceType(value: unknown): value is MothershipResource['type'] { } function parseStreamSnapshot(value: unknown): MothershipChatHistory['streamSnapshot'] { - if (!isRecord(value)) { + if (!isRecordLike(value)) { return null } @@ -116,11 +113,11 @@ function normalizeMessages(value: unknown): PersistedMessage[] { return [] } - return value.filter(isRecord).map((message) => normalizeMessage(message)) + return value.filter(isRecordLike).map((message) => normalizeMessage(message)) } function parseResource(value: unknown, context: string): MothershipResource { - assertValid(isRecord(value), `${context} must be an object`) + assertValid(isRecordLike(value), `${context} must be an object`) assertValid(isResourceType(value.type), `${context}.type is invalid`) assertValid(typeof value.id === 'string', `${context}.id must be a string`) assertValid(typeof value.title === 'string', `${context}.title must be a string`) @@ -155,8 +152,8 @@ function parseChatHistory(value: unknown): MothershipChatHistory { const responseContext = 'Invalid chat response' const chatContext = `${responseContext}: chat` - assertValid(isRecord(value), `${responseContext}: body must be an object`) - assertValid(isRecord(value.chat), `${chatContext} must be an object`) + assertValid(isRecordLike(value), `${responseContext}: body must be an object`) + assertValid(isRecordLike(value.chat), `${chatContext} must be an object`) const chat = value.chat @@ -179,7 +176,7 @@ function parseChatHistory(value: unknown): MothershipChatHistory { } function parseChatResourcesResponse(value: unknown): { resources: MothershipResource[] } { - assertValid(isRecord(value), 'Invalid chat resources response: body must be an object') + assertValid(isRecordLike(value), 'Invalid chat resources response: body must be an object') return { resources: parseResources(value.resources, 'Invalid chat resources response: resources'), diff --git a/apps/sim/hooks/queries/workspace.ts b/apps/sim/hooks/queries/workspace.ts index cdb700fdb06..f91d769d1f2 100644 --- a/apps/sim/hooks/queries/workspace.ts +++ b/apps/sim/hooks/queries/workspace.ts @@ -8,12 +8,14 @@ import { deleteWorkspaceContract, getWorkspaceContract, getWorkspaceMembersContract, + getWorkspaceOwnerBillingContract, getWorkspacePermissionsContract, listWorkspacesContract, updateWorkspaceContract, type Workspace, type WorkspaceCreationPolicy, type WorkspaceMember, + type WorkspaceOwnerBilling, type WorkspacePermissions, type WorkspaceQueryScope, type WorkspacesResponse, @@ -33,6 +35,7 @@ export const workspaceKeys = { settings: (id: string) => [...workspaceKeys.detail(id), 'settings'] as const, permissions: (id: string) => [...workspaceKeys.detail(id), 'permissions'] as const, members: (id: string) => [...workspaceKeys.detail(id), 'members'] as const, + ownerBilling: (id: string) => [...workspaceKeys.detail(id), 'ownerBilling'] as const, adminLists: () => [...workspaceKeys.all, 'adminList'] as const, adminList: (userId: string | undefined) => [...workspaceKeys.adminLists(), userId ?? ''] as const, } @@ -108,6 +111,36 @@ export function useWorkspaceCreationPolicy(enabled = true) { }) } +async function fetchWorkspaceOwnerBilling( + workspaceId: string, + signal?: AbortSignal +): Promise { + return requestJson(getWorkspaceOwnerBillingContract, { + params: { id: workspaceId }, + signal, + }) +} + +/** + * Subscription access state of the workspace's billed account (its owner's + * rolled-up plan) — the workspace-scoped counterpart to `useSubscriptionData`. + * Feed the result to `getSubscriptionAccessState` to gate workspace features on + * the owner's plan rather than the viewer's, so a free member of a paid workspace + * isn't gated. + * + * `staleTime: 0` so consumers (e.g. the deploy modal) refetch on mount: a plan + * change happens outside this query's invalidation graph, and the cached value is + * shown during the background refetch (no flash), so gates self-heal on reopen. + */ +export function useWorkspaceOwnerBilling(workspaceId?: string) { + return useQuery({ + queryKey: workspaceKeys.ownerBilling(workspaceId ?? ''), + queryFn: ({ signal }) => fetchWorkspaceOwnerBilling(workspaceId as string, signal), + enabled: Boolean(workspaceId), + staleTime: 0, + }) +} + type CreateWorkspaceParams = Pick, 'name'> /** diff --git a/apps/sim/hooks/use-permission-config.ts b/apps/sim/hooks/use-permission-config.ts index 89e1e4ac65d..330e502c78a 100644 --- a/apps/sim/hooks/use-permission-config.ts +++ b/apps/sim/hooks/use-permission-config.ts @@ -7,6 +7,7 @@ import { ApiClientError } from '@/lib/api/client/errors' import { requestJson } from '@/lib/api/client/request' import { getAllowedIntegrationsContract } from '@/lib/api/contracts/common' import { getEnv, isTruthy } from '@/lib/core/config/env' +import { isBlockTypeAccessControlExempt } from '@/lib/permission-groups/block-access' import { DEFAULT_PERMISSION_GROUP_CONFIG, type PermissionGroupConfig, @@ -91,7 +92,7 @@ export function usePermissionConfig(): PermissionConfigResult { const isBlockAllowed = useMemo(() => { return (blockType: string) => { - if (blockType === 'start_trigger') return true + if (isBlockTypeAccessControlExempt(blockType)) return true if (mergedAllowedIntegrations === null) return true return mergedAllowedIntegrations.includes(blockType.toLowerCase()) } @@ -117,7 +118,7 @@ export function usePermissionConfig(): PermissionConfigResult { if (mergedAllowedIntegrations === null) return blocks return blocks.filter( (block) => - block.type === 'start_trigger' || + isBlockTypeAccessControlExempt(block.type) || mergedAllowedIntegrations.includes(block.type.toLowerCase()) ) } diff --git a/apps/sim/lib/api/contracts/a2a-agents.ts b/apps/sim/lib/api/contracts/a2a-agents.ts index 9f4190ed689..69b48292fb5 100644 --- a/apps/sim/lib/api/contracts/a2a-agents.ts +++ b/apps/sim/lib/api/contracts/a2a-agents.ts @@ -1,16 +1,13 @@ import type { AgentCapabilities, AgentSkill, Message } from '@a2a-js/sdk' +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import type { AgentAuthentication } from '@/lib/a2a/types' import { defineRouteContract } from '@/lib/api/contracts/types' const dateStringSchema = z.string() -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function isAgentAuthentication(value: unknown): value is AgentAuthentication { - if (!isRecord(value)) return false + if (!isRecordLike(value)) return false const schemes = value.schemes if (schemes === undefined) return true @@ -30,7 +27,7 @@ export const listA2AAgentsQuerySchema = z.object({ workspaceId: z.string({ error: 'workspaceId is required' }).min(1, 'workspaceId is required'), }) -export const a2aAgentCapabilitiesSchema = z.custom(isRecord, { +export const a2aAgentCapabilitiesSchema = z.custom(isRecordLike, { message: 'Agent capabilities must be an object', }) @@ -38,7 +35,7 @@ export const a2aAgentAuthenticationSchema = z.custom(isAgen message: 'Agent authentication must be an object', }) -export const a2aAgentSkillSchema = z.custom(isRecord, { +export const a2aAgentSkillSchema = z.custom(isRecordLike, { message: 'Agent skill must be an object', }) @@ -215,9 +212,7 @@ export type A2AJsonRpcRequest = z.output export const a2aMessageSendParamsSchema = z .object({ - message: z.custom( - (message) => typeof message === 'object' && message !== null && !Array.isArray(message) - ), + message: z.custom(isRecordLike), }) .passthrough() export type A2AMessageSendParams = z.output diff --git a/apps/sim/lib/api/contracts/selectors/jsm.ts b/apps/sim/lib/api/contracts/selectors/jsm.ts index 1e9fef1d629..f8fc3c40e93 100644 --- a/apps/sim/lib/api/contracts/selectors/jsm.ts +++ b/apps/sim/lib/api/contracts/selectors/jsm.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import { credentialWorkflowDomainBodySchema, @@ -159,10 +160,9 @@ export const jsmAttachFormBodySchema = jsmIssueFormsBodySchema.extend({ }) export const jsmSaveFormAnswersBodySchema = jsmIssueFormBodySchema.extend({ - answers: z.custom>( - (value) => typeof value === 'object' && value !== null && !Array.isArray(value), - { message: 'Answers object is required' } - ), + answers: z.custom>(isRecordLike, { + message: 'Answers object is required', + }), }) export const jsmProjectFormTemplatesBodySchema = jsmBaseBodySchema.extend({ diff --git a/apps/sim/lib/api/contracts/tables.ts b/apps/sim/lib/api/contracts/tables.ts index a21c1502f3c..d5e4c7fa5c6 100644 --- a/apps/sim/lib/api/contracts/tables.ts +++ b/apps/sim/lib/api/contracts/tables.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import { type ContractJsonResponse, defineRouteContract } from '@/lib/api/contracts/types' import type { @@ -13,10 +14,7 @@ import type { import { COLUMN_TYPES, NAME_PATTERN, TABLE_LIMITS } from '@/lib/table/constants' import { CSV_MAX_FILE_SIZE_BYTES } from '@/lib/table/import' -const isRecord = (value: unknown): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value) - -export const domainObjectSchema = () => z.custom(isRecord) +export const domainObjectSchema = () => z.custom(isRecordLike) /** * Column types are a fixed enum derived from `COLUMN_TYPES` so callers cannot diff --git a/apps/sim/lib/api/contracts/tools/aws/cloudwatch-put-metric-data.ts b/apps/sim/lib/api/contracts/tools/aws/cloudwatch-put-metric-data.ts index dfc91fc816c..a6bb830206c 100644 --- a/apps/sim/lib/api/contracts/tools/aws/cloudwatch-put-metric-data.ts +++ b/apps/sim/lib/api/contracts/tools/aws/cloudwatch-put-metric-data.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import type { ContractBody, @@ -60,7 +61,7 @@ const PutMetricDataSchema = z.object({ if (!val) return true try { const parsed = JSON.parse(val) - return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) + return isRecordLike(parsed) } catch { return false } diff --git a/apps/sim/lib/api/contracts/tools/index.ts b/apps/sim/lib/api/contracts/tools/index.ts index 7f9a6b5b737..decadf189c6 100644 --- a/apps/sim/lib/api/contracts/tools/index.ts +++ b/apps/sim/lib/api/contracts/tools/index.ts @@ -28,6 +28,7 @@ export * from './sap' export * from './search' export * from './servicenow' export * from './shared' +export * from './square' export * from './stagehand' export * from './thinking' export * from './typeform' diff --git a/apps/sim/lib/api/contracts/tools/square.ts b/apps/sim/lib/api/contracts/tools/square.ts new file mode 100644 index 00000000000..8be19a863cd --- /dev/null +++ b/apps/sim/lib/api/contracts/tools/square.ts @@ -0,0 +1,44 @@ +import { z } from 'zod' +import { defineRouteContract } from '@/lib/api/contracts/types' +import { FileInputSchema } from '@/lib/uploads/utils/file-schemas' + +/** + * Internal contract for the Square catalog image upload route. The route + * downloads the referenced file from storage and forwards it to Square's + * multipart `CreateCatalogImage` endpoint, returning the created image object. + * + * The `output.object` is a Square CatalogObject, whose shape is polymorphic by + * `type`, so it is intentionally left opaque while the envelope is typed. + */ +const squareCatalogImageResponseSchema = z.object({ + success: z.boolean(), + output: z + .object({ + object: z.unknown(), + metadata: z.object({ + id: z.string(), + type: z.string().nullable(), + version: z.number().nullable(), + }), + }) + .optional(), + error: z.string().optional(), +}) + +export const squareCatalogImageBodySchema = z.object({ + accessToken: z.string().min(1, 'Access token is required'), + file: FileInputSchema.optional().nullable(), + fileName: z.string().optional().nullable(), + objectId: z.string().optional().nullable(), + caption: z.string().optional().nullable(), + idempotencyKey: z.string().optional().nullable(), +}) + +export type SquareCatalogImageBody = z.input + +export const squareCatalogImageContract = defineRouteContract({ + method: 'POST', + path: '/api/tools/square/catalog-image', + body: squareCatalogImageBodySchema, + response: { mode: 'json', schema: squareCatalogImageResponseSchema }, +}) diff --git a/apps/sim/lib/api/contracts/v1/tables/index.ts b/apps/sim/lib/api/contracts/v1/tables/index.ts index 8beeec19a8a..9546e2a2c09 100644 --- a/apps/sim/lib/api/contracts/v1/tables/index.ts +++ b/apps/sim/lib/api/contracts/v1/tables/index.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import { createTableBodySchema, @@ -19,10 +20,7 @@ import { defineRouteContract } from '@/lib/api/contracts/types' import type { Filter, Sort } from '@/lib/table' import { TABLE_LIMITS } from '@/lib/table/constants' -const isRecord = (value: unknown): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value) - -const domainObjectSchema = () => z.custom(isRecord) +const domainObjectSchema = () => z.custom(isRecordLike) const optionalJsonObjectQuerySchema = (label: string) => z @@ -34,7 +32,7 @@ const optionalJsonObjectQuerySchema = (label: string) => try { const parsed: unknown = JSON.parse(value) - if (isRecord(parsed)) return parsed as T + if (isRecordLike(parsed)) return parsed as T } catch { ctx.addIssue({ code: 'custom', message: `Invalid ${label} JSON` }) return z.NEVER diff --git a/apps/sim/lib/api/contracts/workspaces.ts b/apps/sim/lib/api/contracts/workspaces.ts index 6a8a0de3948..361004bdf25 100644 --- a/apps/sim/lib/api/contracts/workspaces.ts +++ b/apps/sim/lib/api/contracts/workspaces.ts @@ -181,6 +181,35 @@ export const getWorkspaceContract = defineRouteContract({ }, }) +/** + * Subscription access fields of the workspace's billed account (its OWNER's + * rolled-up plan) — the workspace-scoped counterpart to the viewer `/api/billing` + * data. Feed to `getSubscriptionAccessState` to gate workspace features on the + * owner's plan instead of the signed-in viewer's. No usage/credit data. + */ +export const workspaceOwnerBillingSchema = z.object({ + plan: z.string(), + status: z.string().nullable(), + isPaid: z.boolean(), + isPro: z.boolean(), + isTeam: z.boolean(), + isEnterprise: z.boolean(), + isOrgScoped: z.boolean(), + organizationId: z.string().nullable(), +}) + +export type WorkspaceOwnerBilling = z.output + +export const getWorkspaceOwnerBillingContract = defineRouteContract({ + method: 'GET', + path: '/api/workspaces/[id]/owner-billing', + params: workspaceParamsSchema, + response: { + mode: 'json', + schema: workspaceOwnerBillingSchema, + }, +}) + export const updateWorkspaceContract = defineRouteContract({ method: 'PATCH', path: '/api/workspaces/[id]', diff --git a/apps/sim/lib/auth/access-control.ts b/apps/sim/lib/auth/access-control.ts index fe09a2b6737..c5972590296 100644 --- a/apps/sim/lib/auth/access-control.ts +++ b/apps/sim/lib/auth/access-control.ts @@ -1,3 +1,4 @@ +import { normalizeEmail } from '@sim/utils/string' import { fetchAppConfigProfile } from '@/lib/core/config/appconfig' import { env } from '@/lib/core/config/env' import { isAppConfigEnabled } from '@/lib/core/config/feature-flags' @@ -46,7 +47,7 @@ export function isEmailBlockedByAccessControl( config: AccessControlConfig ): boolean { if (!email) return false - const normalized = email.trim().toLowerCase() + const normalized = normalizeEmail(email) if (config.blockedEmails.includes(normalized)) return true return isEmailInDenylist(normalized, config.blockedSignupDomains) } diff --git a/apps/sim/lib/billing/core/workspace-access.test.ts b/apps/sim/lib/billing/core/workspace-access.test.ts new file mode 100644 index 00000000000..5ff234c9b73 --- /dev/null +++ b/apps/sim/lib/billing/core/workspace-access.test.ts @@ -0,0 +1,59 @@ +/** + * @vitest-environment node + */ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockGetWorkspaceBilledAccountUserId, mockGetHighestPrioritySubscription } = vi.hoisted( + () => ({ + mockGetWorkspaceBilledAccountUserId: vi.fn(), + mockGetHighestPrioritySubscription: vi.fn(), + }) +) + +vi.mock('@/lib/workspaces/utils', () => ({ + getWorkspaceBilledAccountUserId: mockGetWorkspaceBilledAccountUserId, +})) + +vi.mock('@/lib/billing/core/subscription', () => ({ + getHighestPrioritySubscription: mockGetHighestPrioritySubscription, +})) + +import { getWorkspaceOwnerSubscriptionAccess } from '@/lib/billing/core/workspace-access' + +describe('getWorkspaceOwnerSubscriptionAccess', () => { + beforeEach(() => { + vi.clearAllMocks() + mockGetWorkspaceBilledAccountUserId.mockResolvedValue('owner-1') + }) + + it('reports paid + org-scoped for an org team plan billed to the owner', async () => { + mockGetHighestPrioritySubscription.mockResolvedValue({ + plan: 'team_25000', + status: 'active', + referenceId: 'org-1', + }) + const access = await getWorkspaceOwnerSubscriptionAccess('ws-1') + expect(access).toMatchObject({ + plan: 'team_25000', + isPaid: true, + isTeam: true, + isPro: false, + isEnterprise: false, + isOrgScoped: true, + organizationId: 'org-1', + }) + }) + + it('reports free when the billed account has no subscription', async () => { + mockGetHighestPrioritySubscription.mockResolvedValue(null) + const access = await getWorkspaceOwnerSubscriptionAccess('ws-1') + expect(access).toMatchObject({ plan: 'free', isPaid: false, isOrgScoped: false }) + }) + + it('reports free when the workspace has no billed account', async () => { + mockGetWorkspaceBilledAccountUserId.mockResolvedValue(null) + const access = await getWorkspaceOwnerSubscriptionAccess('ws-1') + expect(access.isPaid).toBe(false) + expect(mockGetHighestPrioritySubscription).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/billing/core/workspace-access.ts b/apps/sim/lib/billing/core/workspace-access.ts new file mode 100644 index 00000000000..db83bf8c8d4 --- /dev/null +++ b/apps/sim/lib/billing/core/workspace-access.ts @@ -0,0 +1,56 @@ +import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription' +import { isEnterprise, isPaid, isPro, isTeam } from '@/lib/billing/plan-helpers' +import { + hasPaidSubscriptionStatus, + isOrgScopedSubscription, +} from '@/lib/billing/subscriptions/utils' +import { getWorkspaceBilledAccountUserId } from '@/lib/workspaces/utils' + +/** + * The subscription access fields of a workspace's billed account, as a workspace- + * scoped counterpart to the viewer's `/api/billing` data. Feed this to the + * client `getSubscriptionAccessState` to derive `hasUsablePaidAccess` etc. for + * the WORKSPACE (its owner's rolled-up plan), instead of the signed-in viewer's + * individual plan — so a free member of a paid workspace isn't gated. + * + * Carries no usage/credit/Stripe data: safe to expose to any workspace member. + */ +export interface WorkspaceOwnerSubscriptionAccess { + plan: string + status: string | null + isPaid: boolean + isPro: boolean + isTeam: boolean + isEnterprise: boolean + isOrgScoped: boolean + organizationId: string | null +} + +/** + * Resolves the workspace's billed account and returns its subscription access + * fields (rolled up over org memberships). Mirrors the flag derivation in + * `getSimplifiedBillingSummary` so the result matches the viewer `/api/billing` + * shape for the owner. + */ +export async function getWorkspaceOwnerSubscriptionAccess( + workspaceId: string +): Promise { + const billedUserId = await getWorkspaceBilledAccountUserId(workspaceId) + const subscription = billedUserId ? await getHighestPrioritySubscription(billedUserId) : null + + const plan = subscription?.plan ?? 'free' + const hasPaidEntitlement = hasPaidSubscriptionStatus(subscription?.status) + const orgScoped = + subscription && billedUserId ? isOrgScopedSubscription(subscription, billedUserId) : false + + return { + plan, + status: subscription?.status ?? null, + isPaid: hasPaidEntitlement && isPaid(plan), + isPro: hasPaidEntitlement && isPro(plan), + isTeam: hasPaidEntitlement && isTeam(plan), + isEnterprise: hasPaidEntitlement && isEnterprise(plan), + isOrgScoped: orgScoped, + organizationId: orgScoped && subscription ? subscription.referenceId : null, + } +} diff --git a/apps/sim/lib/billing/index.ts b/apps/sim/lib/billing/index.ts index 83a938f633c..eff8e32c75f 100644 --- a/apps/sim/lib/billing/index.ts +++ b/apps/sim/lib/billing/index.ts @@ -30,6 +30,7 @@ export { getUserUsageLimit as getUsageLimit, updateUserUsageLimit as updateUsageLimit, } from '@/lib/billing/core/usage' +export * from '@/lib/billing/core/workspace-access' export * from '@/lib/billing/credits/balance' export * from '@/lib/billing/credits/purchase' export { diff --git a/apps/sim/lib/copilot/chat/effective-transcript.ts b/apps/sim/lib/copilot/chat/effective-transcript.ts index 78514fd9f0c..cd5f432b142 100644 --- a/apps/sim/lib/copilot/chat/effective-transcript.ts +++ b/apps/sim/lib/copilot/chat/effective-transcript.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { normalizeMessage, type PersistedMessage } from '@/lib/copilot/chat/persisted-message' import { resolveStreamToolOutcome } from '@/lib/copilot/chat/stream-tool-outcome' import { @@ -32,12 +33,8 @@ export function getLiveAssistantMessageId(streamId: string): string { return `live-assistant:${streamId}` } -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function asPayloadRecord(value: unknown): Record | undefined { - return isRecord(value) ? value : undefined + return isRecordLike(value) ? value : undefined } function isTerminalStreamStatus(status: string | null | undefined): boolean { @@ -64,7 +61,7 @@ function buildInlineErrorTag(payload: MothershipStreamV1ErrorPayload): string { } function resolveToolDisplayTitle(ui: unknown): string | undefined { - if (!isRecord(ui)) return undefined + if (!isRecordLike(ui)) return undefined return typeof ui.title === 'string' ? ui.title : typeof ui.phaseLabel === 'string' @@ -318,7 +315,7 @@ function buildLiveAssistantMessage(params: { ...(parentForBlock ? { parentToolCallId: parentForBlock } : {}), ...spanIdentity, displayTitle, - params: isRecord(payload.arguments) ? payload.arguments : undefined, + params: isRecordLike(payload.arguments) ? payload.arguments : undefined, state: typeof payload.status === 'string' ? payload.status : 'executing', }) continue diff --git a/apps/sim/lib/copilot/chat/stream-tool-outcome.ts b/apps/sim/lib/copilot/chat/stream-tool-outcome.ts index 88faa018467..ef0feed1cbd 100644 --- a/apps/sim/lib/copilot/chat/stream-tool-outcome.ts +++ b/apps/sim/lib/copilot/chat/stream-tool-outcome.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { MothershipStreamV1ToolOutcome } from '@/lib/copilot/generated/mothership-stream-v1' type TerminalToolOutcome = @@ -13,16 +14,12 @@ interface ResolveStreamToolOutcomeParams { success?: boolean } -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - export function resolveStreamToolOutcome({ output, status, success, }: ResolveStreamToolOutcomeParams): TerminalToolOutcome { - const outputRecord = isRecord(output) ? output : undefined + const outputRecord = isRecordLike(output) ? output : undefined const isCancelled = outputRecord?.reason === 'user_cancelled' || outputRecord?.cancelledByUser === true || diff --git a/apps/sim/lib/copilot/generated/tool-catalog-v1.ts b/apps/sim/lib/copilot/generated/tool-catalog-v1.ts index 4abbd46b8db..87178f69903 100644 --- a/apps/sim/lib/copilot/generated/tool-catalog-v1.ts +++ b/apps/sim/lib/copilot/generated/tool-catalog-v1.ts @@ -30,6 +30,7 @@ export interface ToolCatalogEntry { | 'download_to_workspace_file' | 'edit_content' | 'edit_workflow' + | 'enrichment_run' | 'ffmpeg' | 'file' | 'function_execute' @@ -97,7 +98,6 @@ export interface ToolCatalogEntry { | 'set_global_workflow_variables' | 'superagent' | 'table' - | 'touch_plan' | 'update_deployment_version' | 'update_job_history' | 'update_workspace_mcp_server' @@ -131,6 +131,7 @@ export interface ToolCatalogEntry { | 'download_to_workspace_file' | 'edit_content' | 'edit_workflow' + | 'enrichment_run' | 'ffmpeg' | 'file' | 'function_execute' @@ -198,7 +199,6 @@ export interface ToolCatalogEntry { | 'set_global_workflow_variables' | 'superagent' | 'table' - | 'touch_plan' | 'update_deployment_version' | 'update_job_history' | 'update_workspace_mcp_server' @@ -1073,6 +1073,56 @@ export const EditWorkflow: ToolCatalogEntry = { requiredPermission: 'write', } +export const EnrichmentRun: ToolCatalogEntry = { + id: 'enrichment_run', + name: 'enrichment_run', + route: 'sim', + mode: 'async', + parameters: { + type: 'object', + properties: { + enrichmentId: { + type: 'string', + description: + "Which enrichment to run. Discover the full set and each one's inputs/outputs via user_table.list_enrichments.", + enum: [ + 'work-email', + 'phone-number', + 'company-domain', + 'company-info', + 'email-verification', + ], + }, + inputs: { + type: 'object', + description: + 'Map of the enrichment\'s input id → value, e.g. { "fullName": "Jane Doe", "companyDomain": "acme.com" }. Provide a value for every required input.', + }, + }, + required: ['enrichmentId', 'inputs'], + }, + resultSchema: { + type: 'object', + properties: { + matched: { + type: 'boolean', + description: 'True when a provider returned a non-empty result.', + }, + provider: { + type: 'string', + description: + 'Internal label of the provider that produced the result (billing/diagnostics only — do NOT surface it to the user), or null on no match.', + }, + result: { + type: 'object', + description: 'Mapped output values from the winning provider (empty object on no match).', + }, + }, + required: ['matched', 'result'], + }, + requiredPermission: 'write', +} + export const Ffmpeg: ToolCatalogEntry = { id: 'ffmpeg', name: 'ffmpeg', @@ -1106,7 +1156,7 @@ export const Ffmpeg: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1126,7 +1176,7 @@ export const Ffmpeg: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1207,8 +1257,7 @@ export const Ffmpeg: ToolCatalogEntry = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1287,7 +1336,7 @@ export const FunctionExecute: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1307,7 +1356,7 @@ export const FunctionExecute: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1372,8 +1421,7 @@ export const FunctionExecute: ToolCatalogEntry = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1449,7 +1497,7 @@ export const GenerateAudio: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1469,7 +1517,7 @@ export const GenerateAudio: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1539,8 +1587,7 @@ export const GenerateAudio: ToolCatalogEntry = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1599,7 +1646,7 @@ export const GenerateImage: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1619,7 +1666,7 @@ export const GenerateImage: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1674,8 +1721,7 @@ export const GenerateImage: ToolCatalogEntry = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1737,7 +1783,7 @@ export const GenerateVideo: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1757,7 +1803,7 @@ export const GenerateVideo: ToolCatalogEntry = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1833,8 +1879,7 @@ export const GenerateVideo: ToolCatalogEntry = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -3694,54 +3739,6 @@ export const Table: ToolCatalogEntry = { internal: true, } -export const TouchPlan: ToolCatalogEntry = { - id: 'touch_plan', - name: 'touch_plan', - route: 'sim', - mode: 'async', - parameters: { - type: 'object', - properties: { - name: { - type: 'string', - description: - 'Plan file name or relative path under .plans, e.g. "implementation.md" or "phase-1/implementation.md". If no extension is supplied, ".md" is appended.', - }, - scope: { - type: 'string', - description: - 'Plan scope. Use "workspace" for root .plans/** main-agent plans. Use "workflow" for workflows/{workflow}/.plans/** subplans. If omitted with workflowPath, workflow scope is assumed; otherwise workspace scope is assumed.', - enum: ['workspace', 'workflow'], - }, - title: { - type: 'string', - description: 'Optional short user-visible label for the plan creation.', - }, - workflowPath: { - type: 'string', - description: - 'Required for scope "workflow". Canonical workflow VFS path, e.g. "workflows/My%20Workflow" or "workflows/Folder/My%20Workflow". Copy paths verbatim from glob/read/grep output — they are percent-encoded per segment (spaces are %20, an in-name slash is %2F; parentheses and dots stay literal). Both the encoded path and the plain name resolve, so copy the returned path exactly rather than retyping or decoding it. Do not use workflow IDs.', - }, - }, - required: ['name'], - }, - resultSchema: { - type: 'object', - properties: { - data: { - type: 'object', - description: - 'Contains id, name, scope, vfsPath, backingVfsPath, and workflowId for workflow plans. Use vfsPath for follow-up workspace_file calls.', - }, - message: { type: 'string', description: 'Human-readable outcome.' }, - success: { type: 'boolean', description: 'Whether the plan file was created.' }, - }, - required: ['success', 'message'], - }, - requiredPermission: 'write', - capabilities: ['file_output'], -} - export const UpdateDeploymentVersion: ToolCatalogEntry = { id: 'update_deployment_version', name: 'update_deployment_version', @@ -4627,6 +4624,7 @@ export const TOOL_CATALOG: Record = { [DownloadToWorkspaceFile.id]: DownloadToWorkspaceFile, [EditContent.id]: EditContent, [EditWorkflow.id]: EditWorkflow, + [EnrichmentRun.id]: EnrichmentRun, [Ffmpeg.id]: Ffmpeg, [File.id]: File, [FunctionExecute.id]: FunctionExecute, @@ -4694,7 +4692,6 @@ export const TOOL_CATALOG: Record = { [SetGlobalWorkflowVariables.id]: SetGlobalWorkflowVariables, [Superagent.id]: Superagent, [Table.id]: Table, - [TouchPlan.id]: TouchPlan, [UpdateDeploymentVersion.id]: UpdateDeploymentVersion, [UpdateJobHistory.id]: UpdateJobHistory, [UpdateWorkspaceMcpServer.id]: UpdateWorkspaceMcpServer, diff --git a/apps/sim/lib/copilot/generated/tool-schemas-v1.ts b/apps/sim/lib/copilot/generated/tool-schemas-v1.ts index 0c4c0d06517..a93837798b1 100644 --- a/apps/sim/lib/copilot/generated/tool-schemas-v1.ts +++ b/apps/sim/lib/copilot/generated/tool-schemas-v1.ts @@ -10,7 +10,7 @@ export interface ToolRuntimeSchemaEntry { } export const TOOL_RUNTIME_SCHEMAS: Record = { - agent: { + ['agent']: { parameters: { properties: { request: { @@ -23,7 +23,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - auth: { + ['auth']: { parameters: { properties: { request: { @@ -36,7 +36,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - check_deployment_status: { + ['check_deployment_status']: { parameters: { type: 'object', properties: { @@ -48,7 +48,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - complete_job: { + ['complete_job']: { parameters: { type: 'object', properties: { @@ -61,7 +61,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - crawl_website: { + ['crawl_website']: { parameters: { type: 'object', properties: { @@ -96,7 +96,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - create_file: { + ['create_file']: { parameters: { type: 'object', properties: { @@ -162,7 +162,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - create_file_folder: { + ['create_file_folder']: { parameters: { type: 'object', properties: { @@ -180,7 +180,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - create_folder: { + ['create_folder']: { parameters: { type: 'object', properties: { @@ -201,7 +201,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - create_workflow: { + ['create_workflow']: { parameters: { type: 'object', properties: { @@ -226,7 +226,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - create_workspace_mcp_server: { + ['create_workspace_mcp_server']: { parameters: { type: 'object', properties: { @@ -259,7 +259,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - delete_file: { + ['delete_file']: { parameters: { type: 'object', properties: { @@ -289,7 +289,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - delete_file_folder: { + ['delete_file_folder']: { parameters: { type: 'object', properties: { @@ -305,7 +305,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - delete_folder: { + ['delete_folder']: { parameters: { type: 'object', properties: { @@ -321,7 +321,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - delete_workflow: { + ['delete_workflow']: { parameters: { type: 'object', properties: { @@ -337,7 +337,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - delete_workspace_mcp_server: { + ['delete_workspace_mcp_server']: { parameters: { type: 'object', properties: { @@ -350,7 +350,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - deploy: { + ['deploy']: { parameters: { properties: { request: { @@ -364,7 +364,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - deploy_api: { + ['deploy_api']: { parameters: { type: 'object', properties: { @@ -448,7 +448,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { ], }, }, - deploy_chat: { + ['deploy_chat']: { parameters: { type: 'object', properties: { @@ -607,7 +607,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { ], }, }, - deploy_mcp: { + ['deploy_mcp']: { parameters: { type: 'object', properties: { @@ -723,7 +723,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['deploymentType', 'deploymentStatus'], }, }, - diff_workflows: { + ['diff_workflows']: { parameters: { type: 'object', properties: { @@ -747,7 +747,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - download_to_workspace_file: { + ['download_to_workspace_file']: { parameters: { type: 'object', properties: { @@ -796,7 +796,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - edit_content: { + ['edit_content']: { parameters: { type: 'object', properties: { @@ -828,7 +828,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - edit_workflow: { + ['edit_workflow']: { parameters: { type: 'object', properties: { @@ -867,7 +867,51 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - ffmpeg: { + ['enrichment_run']: { + parameters: { + type: 'object', + properties: { + enrichmentId: { + type: 'string', + description: + "Which enrichment to run. Discover the full set and each one's inputs/outputs via user_table.list_enrichments.", + enum: [ + 'work-email', + 'phone-number', + 'company-domain', + 'company-info', + 'email-verification', + ], + }, + inputs: { + type: 'object', + description: + 'Map of the enrichment\'s input id → value, e.g. { "fullName": "Jane Doe", "companyDomain": "acme.com" }. Provide a value for every required input.', + }, + }, + required: ['enrichmentId', 'inputs'], + }, + resultSchema: { + type: 'object', + properties: { + matched: { + type: 'boolean', + description: 'True when a provider returned a non-empty result.', + }, + provider: { + type: 'string', + description: + 'Internal label of the provider that produced the result (billing/diagnostics only — do NOT surface it to the user), or null on no match.', + }, + result: { + type: 'object', + description: 'Mapped output values from the winning provider (empty object on no match).', + }, + }, + required: ['matched', 'result'], + }, + }, + ['ffmpeg']: { parameters: { type: 'object', properties: { @@ -902,7 +946,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -922,7 +966,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1009,8 +1053,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1049,7 +1092,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - file: { + ['file']: { parameters: { properties: { prompt: { @@ -1062,7 +1105,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - function_execute: { + ['function_execute']: { parameters: { type: 'object', properties: { @@ -1086,7 +1129,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1106,7 +1149,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1177,8 +1220,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1201,7 +1243,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - generate_api_key: { + ['generate_api_key']: { parameters: { type: 'object', properties: { @@ -1219,7 +1261,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - generate_audio: { + ['generate_audio']: { parameters: { type: 'object', properties: { @@ -1243,7 +1285,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1263,7 +1305,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1339,8 +1381,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1372,7 +1413,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - generate_image: { + ['generate_image']: { parameters: { type: 'object', properties: { @@ -1396,7 +1437,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1416,7 +1457,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1477,8 +1518,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1501,7 +1541,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - generate_video: { + ['generate_video']: { parameters: { type: 'object', properties: { @@ -1534,7 +1574,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS folder path, e.g. "files/Reports" or "workflows/My%20Workflow/.plans". By default this mounts at "/home/user/{path}". Workflow alias directories mount under "/home/user/workflows/...".', + 'Canonical VFS folder path, e.g. "files/Reports". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1554,7 +1594,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { path: { type: 'string', description: - 'Canonical VFS file path, e.g. "files/Reports/sales.csv" or "workflows/My%20Workflow/changelog.md". By default this mounts at "/home/user/{path}". Workflow alias paths mount under "/home/user/workflows/...".', + 'Canonical VFS file path, e.g. "files/Reports/sales.csv". By default this mounts at "/home/user/{path}".', }, sandboxPath: { type: 'string', @@ -1636,8 +1676,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, path: { type: 'string', - description: - 'Canonical destination VFS path, e.g. "files/Reports/chart.png", "workflows/My%20Workflow/changelog.md", or "workflows/My%20Workflow/.plans/plan.md".', + description: 'Canonical destination VFS path, e.g. "files/Reports/chart.png".', }, sandboxPath: { type: 'string', @@ -1669,7 +1708,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_block_outputs: { + ['get_block_outputs']: { parameters: { type: 'object', properties: { @@ -1690,7 +1729,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_block_upstream_references: { + ['get_block_upstream_references']: { parameters: { type: 'object', properties: { @@ -1712,7 +1751,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_deployed_workflow_state: { + ['get_deployed_workflow_state']: { parameters: { type: 'object', properties: { @@ -1725,7 +1764,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_deployment_log: { + ['get_deployment_log']: { parameters: { type: 'object', properties: { @@ -1738,7 +1777,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_job_logs: { + ['get_job_logs']: { parameters: { type: 'object', properties: { @@ -1763,7 +1802,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_page_contents: { + ['get_page_contents']: { parameters: { type: 'object', properties: { @@ -1791,14 +1830,14 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_platform_actions: { + ['get_platform_actions']: { parameters: { type: 'object', properties: {}, }, resultSchema: undefined, }, - get_workflow_data: { + ['get_workflow_data']: { parameters: { type: 'object', properties: { @@ -1817,7 +1856,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - get_workflow_run_options: { + ['get_workflow_run_options']: { parameters: { type: 'object', properties: { @@ -1830,7 +1869,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - glob: { + ['glob']: { parameters: { type: 'object', properties: { @@ -1849,7 +1888,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - grep: { + ['grep']: { parameters: { type: 'object', properties: { @@ -1897,7 +1936,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - job: { + ['job']: { parameters: { properties: { request: { @@ -1910,7 +1949,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - knowledge: { + ['knowledge']: { parameters: { properties: { request: { @@ -1923,7 +1962,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - knowledge_base: { + ['knowledge_base']: { parameters: { type: 'object', properties: { @@ -2116,7 +2155,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - list_file_folders: { + ['list_file_folders']: { parameters: { type: 'object', properties: { @@ -2128,7 +2167,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - list_folders: { + ['list_folders']: { parameters: { type: 'object', properties: { @@ -2140,7 +2179,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - list_integration_tools: { + ['list_integration_tools']: { parameters: { properties: { integration: { @@ -2154,14 +2193,14 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - list_user_workspaces: { + ['list_user_workspaces']: { parameters: { type: 'object', properties: {}, }, resultSchema: undefined, }, - list_workspace_mcp_servers: { + ['list_workspace_mcp_servers']: { parameters: { type: 'object', properties: { @@ -2174,7 +2213,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - load_deployment: { + ['load_deployment']: { parameters: { type: 'object', properties: { @@ -2193,7 +2232,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - load_integration_tool: { + ['load_integration_tool']: { parameters: { properties: { tool_ids: { @@ -2210,7 +2249,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - manage_credential: { + ['manage_credential']: { parameters: { type: 'object', properties: { @@ -2239,7 +2278,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - manage_custom_tool: { + ['manage_custom_tool']: { parameters: { type: 'object', properties: { @@ -2319,7 +2358,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - manage_job: { + ['manage_job']: { parameters: { type: 'object', properties: { @@ -2394,7 +2433,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - manage_mcp_tool: { + ['manage_mcp_tool']: { parameters: { type: 'object', properties: { @@ -2446,7 +2485,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - manage_skill: { + ['manage_skill']: { parameters: { type: 'object', properties: { @@ -2479,7 +2518,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - materialize_file: { + ['materialize_file']: { parameters: { type: 'object', properties: { @@ -2503,7 +2542,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - media: { + ['media']: { parameters: { properties: { prompt: { @@ -2516,7 +2555,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - move_file: { + ['move_file']: { parameters: { type: 'object', properties: { @@ -2537,7 +2576,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - move_file_folder: { + ['move_file_folder']: { parameters: { type: 'object', properties: { @@ -2555,7 +2594,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - move_folder: { + ['move_folder']: { parameters: { type: 'object', properties: { @@ -2573,7 +2612,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - move_workflow: { + ['move_workflow']: { parameters: { type: 'object', properties: { @@ -2593,7 +2632,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - oauth_get_auth_link: { + ['oauth_get_auth_link']: { parameters: { type: 'object', properties: { @@ -2607,7 +2646,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - oauth_request_access: { + ['oauth_request_access']: { parameters: { type: 'object', properties: { @@ -2621,7 +2660,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - open_resource: { + ['open_resource']: { parameters: { type: 'object', properties: { @@ -2655,7 +2694,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - promote_to_live: { + ['promote_to_live']: { parameters: { type: 'object', properties: { @@ -2674,7 +2713,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - query_logs: { + ['query_logs']: { parameters: { type: 'object', properties: { @@ -2785,7 +2824,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - read: { + ['read']: { parameters: { type: 'object', properties: { @@ -2812,7 +2851,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - redeploy: { + ['redeploy']: { parameters: { type: 'object', properties: { @@ -2891,7 +2930,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { ], }, }, - rename_file: { + ['rename_file']: { parameters: { type: 'object', properties: { @@ -2927,7 +2966,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - rename_file_folder: { + ['rename_file_folder']: { parameters: { type: 'object', properties: { @@ -2944,7 +2983,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - rename_workflow: { + ['rename_workflow']: { parameters: { type: 'object', properties: { @@ -2961,7 +3000,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - research: { + ['research']: { parameters: { properties: { topic: { @@ -2974,7 +3013,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - respond: { + ['respond']: { parameters: { additionalProperties: true, properties: { @@ -2997,7 +3036,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - restore_resource: { + ['restore_resource']: { parameters: { type: 'object', properties: { @@ -3015,7 +3054,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - run: { + ['run']: { parameters: { properties: { context: { @@ -3032,7 +3071,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - run_block: { + ['run_block']: { parameters: { type: 'object', properties: { @@ -3064,7 +3103,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - run_from_block: { + ['run_from_block']: { parameters: { type: 'object', properties: { @@ -3096,7 +3135,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - run_workflow: { + ['run_workflow']: { parameters: { type: 'object', properties: { @@ -3134,7 +3173,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - run_workflow_until_block: { + ['run_workflow_until_block']: { parameters: { type: 'object', properties: { @@ -3177,7 +3216,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - scrape_page: { + ['scrape_page']: { parameters: { type: 'object', properties: { @@ -3198,7 +3237,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - search_documentation: { + ['search_documentation']: { parameters: { type: 'object', properties: { @@ -3215,7 +3254,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - search_library_docs: { + ['search_library_docs']: { parameters: { type: 'object', properties: { @@ -3236,7 +3275,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - search_online: { + ['search_online']: { parameters: { type: 'object', properties: { @@ -3276,7 +3315,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - search_patterns: { + ['search_patterns']: { parameters: { type: 'object', properties: { @@ -3298,7 +3337,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - set_block_enabled: { + ['set_block_enabled']: { parameters: { type: 'object', properties: { @@ -3320,7 +3359,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - set_environment_variables: { + ['set_environment_variables']: { parameters: { type: 'object', properties: { @@ -3354,7 +3393,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - set_global_workflow_variables: { + ['set_global_workflow_variables']: { parameters: { type: 'object', properties: { @@ -3395,7 +3434,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - superagent: { + ['superagent']: { parameters: { properties: { task: { @@ -3409,7 +3448,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - table: { + ['table']: { parameters: { properties: { request: { @@ -3422,54 +3461,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - touch_plan: { - parameters: { - type: 'object', - properties: { - name: { - type: 'string', - description: - 'Plan file name or relative path under .plans, e.g. "implementation.md" or "phase-1/implementation.md". If no extension is supplied, ".md" is appended.', - }, - scope: { - type: 'string', - description: - 'Plan scope. Use "workspace" for root .plans/** main-agent plans. Use "workflow" for workflows/{workflow}/.plans/** subplans. If omitted with workflowPath, workflow scope is assumed; otherwise workspace scope is assumed.', - enum: ['workspace', 'workflow'], - }, - title: { - type: 'string', - description: 'Optional short user-visible label for the plan creation.', - }, - workflowPath: { - type: 'string', - description: - 'Required for scope "workflow". Canonical workflow VFS path, e.g. "workflows/My%20Workflow" or "workflows/Folder/My%20Workflow". Copy paths verbatim from glob/read/grep output — they are percent-encoded per segment (spaces are %20, an in-name slash is %2F; parentheses and dots stay literal). Both the encoded path and the plain name resolve, so copy the returned path exactly rather than retyping or decoding it. Do not use workflow IDs.', - }, - }, - required: ['name'], - }, - resultSchema: { - type: 'object', - properties: { - data: { - type: 'object', - description: - 'Contains id, name, scope, vfsPath, backingVfsPath, and workflowId for workflow plans. Use vfsPath for follow-up workspace_file calls.', - }, - message: { - type: 'string', - description: 'Human-readable outcome.', - }, - success: { - type: 'boolean', - description: 'Whether the plan file was created.', - }, - }, - required: ['success', 'message'], - }, - }, - update_deployment_version: { + ['update_deployment_version']: { parameters: { type: 'object', properties: { @@ -3498,7 +3490,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - update_job_history: { + ['update_job_history']: { parameters: { type: 'object', properties: { @@ -3516,7 +3508,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - update_workspace_mcp_server: { + ['update_workspace_mcp_server']: { parameters: { type: 'object', properties: { @@ -3541,7 +3533,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - user_memory: { + ['user_memory']: { parameters: { type: 'object', properties: { @@ -3590,7 +3582,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - user_table: { + ['user_table']: { parameters: { type: 'object', properties: { @@ -3952,7 +3944,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { required: ['success', 'message'], }, }, - workflow: { + ['workflow']: { parameters: { properties: { prompt: { @@ -3965,7 +3957,7 @@ export const TOOL_RUNTIME_SCHEMAS: Record = { }, resultSchema: undefined, }, - workspace_file: { + ['workspace_file']: { parameters: { type: 'object', properties: { diff --git a/apps/sim/lib/copilot/request/handlers/types.ts b/apps/sim/lib/copilot/request/handlers/types.ts index bff45b9a97d..9f41a996adf 100644 --- a/apps/sim/lib/copilot/request/handlers/types.ts +++ b/apps/sim/lib/copilot/request/handlers/types.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import type { AsyncCompletionSignal, AsyncTerminalCompletionSnapshot, @@ -37,10 +38,6 @@ export type ToolScope = 'main' | MothershipStreamV1StreamScope['lane'] const logger = createLogger('CopilotHandlerHelpers') -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - export function addContentBlock( context: StreamingContext, block: Omit @@ -228,7 +225,7 @@ export async function emitSyntheticToolResult( : undefined const resultPayload = isCancelled - ? isRecord(completionData) + ? isRecordLike(completionData) ? { ...completionData, reason: 'user_cancelled', cancelledByUser: true } : completionData !== undefined ? { output: completionData, reason: 'user_cancelled', cancelledByUser: true } diff --git a/apps/sim/lib/copilot/request/session/contract.ts b/apps/sim/lib/copilot/request/session/contract.ts index d084690186e..947b162a0ca 100644 --- a/apps/sim/lib/copilot/request/session/contract.ts +++ b/apps/sim/lib/copilot/request/session/contract.ts @@ -1,4 +1,5 @@ import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import type { MothershipStreamV1EventEnvelope, MothershipStreamV1StreamRef, @@ -150,10 +151,6 @@ export type ParseStreamEventEnvelopeResult = // Structural helpers (CSP-safe – no codegen / eval / new Function) // --------------------------------------------------------------------------- -function isRecord(value: unknown): value is JsonRecord { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function isOptionalString(value: unknown): value is string | undefined { return value === undefined || typeof value === 'string' } @@ -164,7 +161,7 @@ function isOptionalFiniteNumber(value: unknown): value is number | undefined { function isStreamRef(value: unknown): value is MothershipStreamV1StreamRef { return ( - isRecord(value) && + isRecordLike(value) && typeof value.streamId === 'string' && value.streamId.length > 0 && isOptionalString(value.chatId) && @@ -174,7 +171,7 @@ function isStreamRef(value: unknown): value is MothershipStreamV1StreamRef { function isTrace(value: unknown): value is MothershipStreamV1Trace { return ( - isRecord(value) && + isRecordLike(value) && typeof value.requestId === 'string' && isOptionalString(value.goTraceId) && isOptionalString(value.spanId) @@ -183,7 +180,7 @@ function isTrace(value: unknown): value is MothershipStreamV1Trace { function isStreamScope(value: unknown): value is MothershipStreamV1StreamScope { return ( - isRecord(value) && + isRecordLike(value) && value.lane === 'subagent' && isOptionalString(value.agentId) && isOptionalString(value.parentToolCallId) @@ -210,7 +207,7 @@ function isValidEnvelopeShell(value: unknown): value is JsonRecord & { type: string payload: JsonRecord } { - if (!isRecord(value)) return false + if (!isRecordLike(value)) return false if (value.v !== 1) return false if (typeof value.seq !== 'number' || !Number.isFinite(value.seq)) return false if (typeof value.ts !== 'string') return false @@ -218,7 +215,7 @@ function isValidEnvelopeShell(value: unknown): value is JsonRecord & { if (value.trace !== undefined && !isTrace(value.trace)) return false if (value.scope !== undefined && !isStreamScope(value.scope)) return false if (typeof value.type !== 'string' || !KNOWN_EVENT_TYPES.has(value.type)) return false - if (!isRecord(value.payload)) return false + if (!isRecordLike(value.payload)) return false return true } @@ -271,7 +268,7 @@ function isValidResourcePayload(payload: JsonRecord): boolean { return ( (payload.op === MothershipStreamV1ResourceOp.upsert || payload.op === MothershipStreamV1ResourceOp.remove) && - isRecord(payload.resource) && + isRecordLike(payload.resource) && typeof (payload.resource as JsonRecord).id === 'string' && typeof (payload.resource as JsonRecord).type === 'string' ) @@ -331,7 +328,7 @@ function isSyntheticEnvelopeBase(value: unknown): value is Omit< payload?: unknown } { return ( - isRecord(value) && + isRecordLike(value) && value.v === 1 && value.type === 'tool' && typeof value.seq === 'number' && @@ -345,7 +342,7 @@ function isSyntheticEnvelopeBase(value: unknown): value is Omit< function isSyntheticFilePreviewTarget(value: unknown): value is SyntheticFilePreviewTarget { return ( - isRecord(value) && + isRecordLike(value) && (value.kind === 'new_file' || value.kind === 'file_id') && isOptionalString(value.fileId) && isOptionalString(value.fileName) @@ -353,7 +350,7 @@ function isSyntheticFilePreviewTarget(value: unknown): value is SyntheticFilePre } function isSyntheticFilePreviewPayload(value: unknown): value is SyntheticFilePreviewPayload { - if (!isRecord(value)) { + if (!isRecordLike(value)) { return false } @@ -371,7 +368,7 @@ function isSyntheticFilePreviewPayload(value: unknown): value is SyntheticFilePr isOptionalString(value.title) ) case FILE_PREVIEW_PHASE.editMeta: - return isRecord(value.edit) + return isRecordLike(value.edit) case FILE_PREVIEW_PHASE.content: return ( typeof value.content === 'string' && @@ -382,7 +379,7 @@ function isSyntheticFilePreviewPayload(value: unknown): value is SyntheticFilePr isOptionalString(value.fileId) && isOptionalString(value.targetKind) && isOptionalString(value.operation) && - (value.edit === undefined || isRecord(value.edit)) + (value.edit === undefined || isRecordLike(value.edit)) ) case FILE_PREVIEW_PHASE.complete: return isOptionalString(value.fileId) && isOptionalFiniteNumber(value.previewVersion) @@ -402,23 +399,25 @@ export function isSyntheticFilePreviewEventEnvelope( // --------------------------------------------------------------------------- export function isToolCallStreamEvent(event: SessionStreamEvent): event is ToolCallStreamEvent { - return event.type === 'tool' && isRecord(event.payload) && event.payload.phase === 'call' + return event.type === 'tool' && isRecordLike(event.payload) && event.payload.phase === 'call' } export function isToolArgsDeltaStreamEvent( event: SessionStreamEvent ): event is ToolArgsDeltaStreamEvent { - return event.type === 'tool' && isRecord(event.payload) && event.payload.phase === 'args_delta' + return ( + event.type === 'tool' && isRecordLike(event.payload) && event.payload.phase === 'args_delta' + ) } export function isToolResultStreamEvent(event: SessionStreamEvent): event is ToolResultStreamEvent { - return event.type === 'tool' && isRecord(event.payload) && event.payload.phase === 'result' + return event.type === 'tool' && isRecordLike(event.payload) && event.payload.phase === 'result' } export function isSubagentSpanStreamEvent( event: SessionStreamEvent ): event is SubagentSpanStreamEvent { - return event.type === 'span' && isRecord(event.payload) && event.payload.kind === 'subagent' + return event.type === 'span' && isRecordLike(event.payload) && event.payload.kind === 'subagent' } // --------------------------------------------------------------------------- @@ -441,13 +440,13 @@ export function parsePersistedStreamEventEnvelope(value: unknown): ParseStreamEv } const hints: string[] = [] - if (!isRecord(value)) { + if (!isRecordLike(value)) { hints.push('value is not an object') } else { if (value.v !== 1) hints.push(`unexpected v=${JSON.stringify(value.v)}`) if (typeof value.type !== 'string') hints.push('missing type') else if (!KNOWN_EVENT_TYPES.has(value.type)) hints.push(`unknown type="${value.type}"`) - if (!isRecord(value.payload)) hints.push('missing or invalid payload') + if (!isRecordLike(value.payload)) hints.push('missing or invalid payload') } return { diff --git a/apps/sim/lib/copilot/request/tools/executor.ts b/apps/sim/lib/copilot/request/tools/executor.ts index d50705558a3..b9a78eae0bf 100644 --- a/apps/sim/lib/copilot/request/tools/executor.ts +++ b/apps/sim/lib/copilot/request/tools/executor.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import type { AsyncCompletionEnvelope, AsyncCompletionSignal, @@ -70,10 +71,6 @@ export { waitForToolCompletion } from '@/lib/copilot/request/tools/client' const logger = createLogger('CopilotSseToolExecution') -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function hasOutputValue(result: { output?: unknown } | undefined): result is { output: unknown } { return result !== undefined && Object.hasOwn(result, 'output') } @@ -133,11 +130,11 @@ function summarizeToolResultForSpan(result: { function extractAttachmentShape( output: unknown ): { imageCount: number; imageBytes: number; mediaType?: string } | null { - if (!isRecord(output)) return null + if (!isRecordLike(output)) return null const candidate = (output as Record).attachment - if (!isRecord(candidate)) return null + if (!isRecordLike(candidate)) return null const source = (candidate as Record).source - if (!isRecord(source)) return null + if (!isRecordLike(source)) return null const type = typeof (candidate as Record).type === 'string' ? ((candidate as Record).type as string) @@ -168,7 +165,7 @@ function buildCompletionSignal(input: { function getCreateWorkflowOutput( output: unknown ): { workflowId?: string; workspaceId?: string } | undefined { - if (!isRecord(output)) { + if (!isRecordLike(output)) { return undefined } diff --git a/apps/sim/lib/copilot/tools/client/run-tool-execution.ts b/apps/sim/lib/copilot/tools/client/run-tool-execution.ts index 18104b415fe..44117d1195e 100644 --- a/apps/sim/lib/copilot/tools/client/run-tool-execution.ts +++ b/apps/sim/lib/copilot/tools/client/run-tool-execution.ts @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { ASYNC_TOOL_CONFIRMATION_STATUS, type AsyncCompletionData, @@ -45,10 +46,6 @@ class CompletionReportError extends Error { } } -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function resolveWorkflowInput(params: Record): unknown { if (Object.hasOwn(params, 'workflow_input')) { return params.workflow_input @@ -604,7 +601,7 @@ async function reportCompletion( const res = await send(body) if (res.ok) return - if (isRecord(data) && bodySize > LARGE_PAYLOAD_THRESHOLD) { + if (isRecordLike(data) && bodySize > LARGE_PAYLOAD_THRESHOLD) { const { logs: _logs, ...dataWithoutLogs } = data logger.warn('[RunTool] reportCompletion failed with large payload, retrying without logs', { toolCallId, diff --git a/apps/sim/lib/copilot/tools/server/enrichment/enrichment-run.ts b/apps/sim/lib/copilot/tools/server/enrichment/enrichment-run.ts new file mode 100644 index 00000000000..bde0e4873b5 --- /dev/null +++ b/apps/sim/lib/copilot/tools/server/enrichment/enrichment-run.ts @@ -0,0 +1,66 @@ +import { createLogger } from '@sim/logger' +import { EnrichmentRun } from '@/lib/copilot/generated/tool-catalog-v1' +import type { BaseServerTool } from '@/lib/copilot/tools/server/base-tool' +import { getEnrichment } from '@/enrichments/registry' +import { runEnrichment } from '@/enrichments/run' + +interface EnrichmentRunParams { + enrichmentId: string + inputs: Record +} + +interface EnrichmentRunResult { + matched: boolean + result: Record + provider: string | null + /** Hosted-key cost surfaced for per-round billing (omitted for BYOK / free). */ + _serviceCost?: { service: string; cost: number } +} + +/** + * Direct one-off enrichment lookup. Runs the same provider cascade as table + * enrichments (`runEnrichment`) for a single entity and returns the result + * inline — no table required. The hosted-key cost is surfaced as `_serviceCost` + * so copilot's per-round billing charges for it, matching how the media tools + * bill (see image/generate-image.ts). + */ +export const enrichmentRunServerTool: BaseServerTool = { + name: EnrichmentRun.id, + async execute(params: EnrichmentRunParams, context): Promise { + const logger = createLogger('EnrichmentRunServerTool') + const { enrichmentId, inputs } = params + + if (!enrichmentId || typeof enrichmentId !== 'string') { + throw new Error('enrichmentId is required') + } + const workspaceId = context?.workspaceId + if (!workspaceId) { + throw new Error('workspaceId is required to run an enrichment') + } + const enrichment = getEnrichment(enrichmentId) + if (!enrichment) { + throw new Error(`Unknown enrichment "${enrichmentId}"`) + } + + const { result, cost, error, provider } = await runEnrichment(enrichment, inputs ?? {}, { + workspaceId, + signal: context?.abortSignal, + }) + + const matched = Object.keys(result).length > 0 + logger.info('Enrichment run', { enrichmentId, matched, provider, cost }) + + // A genuine "no match" returns normally (matched: false). Only surface an + // error when every provider that ran failed (infra/auth/rate-limit). + if (error && !matched) { + throw new Error(error) + } + + return { + matched, + result, + provider, + ...(cost > 0 ? { _serviceCost: { service: provider ?? enrichmentId, cost } } : {}), + } + }, +} diff --git a/apps/sim/lib/copilot/tools/server/files/create-file.ts b/apps/sim/lib/copilot/tools/server/files/create-file.ts index d7b9489d6fd..146d0237773 100644 --- a/apps/sim/lib/copilot/tools/server/files/create-file.ts +++ b/apps/sim/lib/copilot/tools/server/files/create-file.ts @@ -56,7 +56,7 @@ export const createFileServerTool: BaseServerTool ({ - ensureWorkspaceAccess: vi.fn(), - resolveWorkflowAliasForWorkspace: vi.fn(), - writeWorkspaceFileByPath: vi.fn(), -})) - -vi.mock('@/lib/copilot/tools/handlers/access', () => ({ - ensureWorkspaceAccess: mocks.ensureWorkspaceAccess, -})) - -vi.mock('@/lib/copilot/vfs/workflow-alias-resolver', () => ({ - resolveWorkflowAliasForWorkspace: mocks.resolveWorkflowAliasForWorkspace, -})) - -vi.mock('@/lib/copilot/vfs/resource-writer', () => ({ - writeWorkspaceFileByPath: mocks.writeWorkspaceFileByPath, -})) - -vi.mock('@/lib/core/config/feature-flags', () => ({ - isMothershipBetaFeaturesEnabled: true, -})) - -import { touchPlanServerTool } from './touch-plan' - -describe('touch_plan server tool', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.ensureWorkspaceAccess.mockResolvedValue(undefined) - }) - - it('creates a workflow-local plan alias and returns backing metadata', async () => { - mocks.resolveWorkflowAliasForWorkspace.mockResolvedValue({ - kind: 'plan_file', - scope: 'workflow', - workflowId: 'wf_1', - workflowName: 'My Workflow', - workflowPath: 'workflows/My%20Workflow', - aliasPath: 'workflows/My%20Workflow/.plans/implementation.md', - backingPath: 'files/.plans/wf_1/implementation.md', - backingFolderPath: 'files/.plans/wf_1', - planRelativePath: 'implementation.md', - }) - mocks.writeWorkspaceFileByPath.mockResolvedValue({ - id: 'file-plan', - name: 'implementation.md', - vfsPath: 'workflows/My%20Workflow/.plans/implementation.md', - backingVfsPath: 'files/.plans/wf_1/implementation.md', - }) - - const result = await touchPlanServerTool.execute( - { workflowPath: 'workflows/My Workflow', name: 'implementation' }, - { userId: 'user-1', workspaceId: 'workspace-1' } - ) - - expect(mocks.resolveWorkflowAliasForWorkspace).toHaveBeenCalledWith({ - workspaceId: 'workspace-1', - path: 'workflows/My%20Workflow/.plans/implementation.md', - }) - expect(mocks.writeWorkspaceFileByPath).toHaveBeenCalledWith({ - workspaceId: 'workspace-1', - userId: 'user-1', - target: { - path: 'workflows/My%20Workflow/.plans/implementation.md', - mode: 'create', - mimeType: 'text/markdown', - }, - buffer: Buffer.from('', 'utf-8'), - inferredMimeType: 'text/markdown', - }) - expect(result).toMatchObject({ - success: true, - data: { - id: 'file-plan', - scope: 'workflow', - vfsPath: 'workflows/My%20Workflow/.plans/implementation.md', - backingVfsPath: 'files/.plans/wf_1/implementation.md', - workflowId: 'wf_1', - }, - }) - }) - - it('creates a workspace root plan alias and returns backing metadata', async () => { - mocks.resolveWorkflowAliasForWorkspace.mockResolvedValue({ - kind: 'plan_file', - scope: 'workspace', - aliasPath: '.plans/migration.md', - backingPath: 'files/.plans/workspace/migration.md', - backingFolderPath: 'files/.plans/workspace', - planRelativePath: 'migration.md', - }) - mocks.writeWorkspaceFileByPath.mockResolvedValue({ - id: 'file-root-plan', - name: 'migration.md', - vfsPath: '.plans/migration.md', - backingVfsPath: 'files/.plans/workspace/migration.md', - }) - - const result = await touchPlanServerTool.execute( - { scope: 'workspace', name: 'migration' }, - { userId: 'user-1', workspaceId: 'workspace-1' } - ) - - expect(mocks.resolveWorkflowAliasForWorkspace).toHaveBeenCalledWith({ - workspaceId: 'workspace-1', - path: '.plans/migration.md', - }) - expect(mocks.writeWorkspaceFileByPath).toHaveBeenCalledWith({ - workspaceId: 'workspace-1', - userId: 'user-1', - target: { - path: '.plans/migration.md', - mode: 'create', - mimeType: 'text/markdown', - }, - buffer: Buffer.from('', 'utf-8'), - inferredMimeType: 'text/markdown', - }) - expect(result).toMatchObject({ - success: true, - data: { - id: 'file-root-plan', - scope: 'workspace', - vfsPath: '.plans/migration.md', - backingVfsPath: 'files/.plans/workspace/migration.md', - }, - }) - }) - - it('rejects missing workflows before writing', async () => { - mocks.resolveWorkflowAliasForWorkspace.mockResolvedValue(null) - - const result = await touchPlanServerTool.execute( - { workflowPath: 'workflows/Missing', name: 'implementation.md' }, - { userId: 'user-1', workspaceId: 'workspace-1' } - ) - - expect(result.success).toBe(false) - expect(result.message).toContain('Workflow not found') - expect(mocks.writeWorkspaceFileByPath).not.toHaveBeenCalled() - }) -}) diff --git a/apps/sim/lib/copilot/tools/server/files/touch-plan.ts b/apps/sim/lib/copilot/tools/server/files/touch-plan.ts deleted file mode 100644 index 168903236ba..00000000000 --- a/apps/sim/lib/copilot/tools/server/files/touch-plan.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { createLogger } from '@sim/logger' -import { ensureWorkspaceAccess } from '@/lib/copilot/tools/handlers/access' -import { - assertServerToolNotAborted, - type BaseServerTool, - type ServerToolContext, -} from '@/lib/copilot/tools/server/base-tool' -import { - canonicalizeVfsPath, - decodeVfsPathSegments, - encodeVfsPathSegments, -} from '@/lib/copilot/vfs/path-utils' -import { writeWorkspaceFileByPath } from '@/lib/copilot/vfs/resource-writer' -import { resolveWorkflowAliasForWorkspace } from '@/lib/copilot/vfs/workflow-alias-resolver' -import { isMothershipBetaFeaturesEnabled } from '@/lib/core/config/feature-flags' - -const logger = createLogger('TouchPlanServerTool') -const TOUCH_PLAN_TOOL_ID = 'touch_plan' - -interface TouchPlanArgs { - scope?: 'workspace' | 'workflow' - workflowPath?: string - name: string - title?: string - args?: Record -} - -interface TouchPlanResult { - success: boolean - message: string - data?: { - id: string - name: string - vfsPath: string - backingVfsPath?: string - scope: 'workspace' | 'workflow' - workflowId?: string - } -} - -function normalizeWorkflowPath(path: string): string { - const trimmed = path.trim().replace(/^\/+|\/+$/g, '') - const withoutKnownLeaf = trimmed - .replace(/\/(meta|state|executions|deployment|versions|links)\.json$/, '') - .replace(/\/changelog\.md$/, '') - .replace(/\/\.plans$/, '') - - const canonical = canonicalizeVfsPath(withoutKnownLeaf) - if (!canonical.startsWith('workflows/')) { - throw new Error('workflowPath must be a canonical workflows/... VFS path') - } - return canonical -} - -function normalizePlanRelativePath(name: string): string { - const segments = decodeVfsPathSegments(name) - if (segments.length === 0) { - throw new Error('Plan name is required') - } - const leaf = segments.at(-1) ?? '' - const leafWithExtension = leaf.includes('.') ? leaf : `${leaf}.md` - return encodeVfsPathSegments([...segments.slice(0, -1), leafWithExtension]) -} - -export const touchPlanServerTool: BaseServerTool = { - name: TOUCH_PLAN_TOOL_ID, - async execute(params: TouchPlanArgs, context?: ServerToolContext): Promise { - if (!isMothershipBetaFeaturesEnabled) { - return { success: false, message: 'touch_plan is not available' } - } - if (!context?.userId) { - throw new Error('Authentication required') - } - const workspaceId = context.workspaceId - if (!workspaceId) { - return { success: false, message: 'Workspace ID is required' } - } - await ensureWorkspaceAccess(workspaceId, context.userId, 'write') - - const nested = params.args - const nestedScope = nested?.scope as TouchPlanArgs['scope'] | undefined - const scope = - params.scope || - nestedScope || - (params.workflowPath || nested?.workflowPath ? 'workflow' : 'workspace') - const workflowPath = params.workflowPath || (nested?.workflowPath as string) || '' - const name = params.name || (nested?.name as string) || '' - if (!name) { - return { success: false, message: 'touch_plan requires name' } - } - if (scope !== 'workspace' && scope !== 'workflow') { - return { success: false, message: 'touch_plan scope must be "workspace" or "workflow"' } - } - if (scope === 'workflow' && !workflowPath) { - return { - success: false, - message: 'touch_plan with workflow scope requires workflowPath and name', - } - } - - const planRelativePath = normalizePlanRelativePath(name) - const aliasPath = - scope === 'workspace' - ? `.plans/${planRelativePath}` - : `${normalizeWorkflowPath(workflowPath)}/.plans/${planRelativePath}` - const alias = await resolveWorkflowAliasForWorkspace({ workspaceId, path: aliasPath }) - if (!alias || alias.kind !== 'plan_file') { - return { - success: false, - message: - scope === 'workflow' - ? `Workflow not found for plan path: ${aliasPath}` - : `Unsupported workspace plan path: ${aliasPath}`, - } - } - - assertServerToolNotAborted(context) - const result = await writeWorkspaceFileByPath({ - workspaceId, - userId: context.userId, - target: { - path: aliasPath, - mode: 'create', - mimeType: 'text/markdown', - }, - buffer: Buffer.from('', 'utf-8'), - inferredMimeType: 'text/markdown', - }) - - logger.info('Workflow plan touched via copilot', { - workspaceId, - workflowId: alias.scope === 'workflow' ? alias.workflowId : undefined, - scope: alias.scope, - vfsPath: result.vfsPath, - backingVfsPath: result.backingVfsPath, - userId: context.userId, - }) - - return { - success: true, - message: `${alias.scope === 'workspace' ? 'Workspace' : 'Workflow'} plan "${result.vfsPath}" created successfully`, - data: { - id: result.id, - name: result.name, - vfsPath: result.vfsPath, - backingVfsPath: result.backingVfsPath, - scope: alias.scope, - workflowId: alias.scope === 'workflow' ? alias.workflowId : undefined, - }, - } - }, -} diff --git a/apps/sim/lib/copilot/tools/server/router.ts b/apps/sim/lib/copilot/tools/server/router.ts index a151b25a511..7780f97eb73 100644 --- a/apps/sim/lib/copilot/tools/server/router.ts +++ b/apps/sim/lib/copilot/tools/server/router.ts @@ -19,7 +19,6 @@ import { MoveFileFolder, RenameFile, RenameFileFolder, - TouchPlan, UserTable, WorkspaceFile, } from '@/lib/copilot/generated/tool-catalog-v1' @@ -31,6 +30,7 @@ import { import { getBlocksMetadataServerTool } from '@/lib/copilot/tools/server/blocks/get-blocks-metadata-tool' import { getTriggerBlocksServerTool } from '@/lib/copilot/tools/server/blocks/get-trigger-blocks' import { searchDocumentationServerTool } from '@/lib/copilot/tools/server/docs/search-documentation' +import { enrichmentRunServerTool } from '@/lib/copilot/tools/server/enrichment/enrichment-run' import { createFileServerTool } from '@/lib/copilot/tools/server/files/create-file' import { deleteFileServerTool } from '@/lib/copilot/tools/server/files/delete-file' import { downloadToWorkspaceFileServerTool } from '@/lib/copilot/tools/server/files/download-to-workspace-file' @@ -44,7 +44,6 @@ import { renameFileFolderServerTool, } from '@/lib/copilot/tools/server/files/file-folders' import { renameFileServerTool } from '@/lib/copilot/tools/server/files/rename-file' -import { touchPlanServerTool } from '@/lib/copilot/tools/server/files/touch-plan' import { workspaceFileServerTool } from '@/lib/copilot/tools/server/files/workspace-file' import { validateGeneratedToolPayload } from '@/lib/copilot/tools/server/generated-schema' import { generateImageServerTool } from '@/lib/copilot/tools/server/image/generate-image' @@ -59,7 +58,6 @@ import { getCredentialsServerTool } from '@/lib/copilot/tools/server/user/get-cr import { setEnvironmentVariablesServerTool } from '@/lib/copilot/tools/server/user/set-environment-variables' import { editWorkflowServerTool } from '@/lib/copilot/tools/server/workflow/edit-workflow' import { queryLogsServerTool } from '@/lib/copilot/tools/server/workflow/query-logs' -import { isMothershipBetaFeaturesEnabled } from '@/lib/core/config/feature-flags' export type ExecuteResponseSuccess = z.output @@ -112,7 +110,6 @@ const WRITE_ACTIONS: Record = { [WorkspaceFile.id]: ['create', 'append', 'update', 'delete', 'rename', 'patch'], [editContentServerTool.name]: ['*'], [CreateFile.id]: ['*'], - [TouchPlan.id]: ['*'], [RenameFile.id]: ['*'], [DeleteFile.id]: ['*'], [MoveFile.id]: ['*'], @@ -125,6 +122,8 @@ const WRITE_ACTIONS: Record = { [GenerateVideo.id]: ['generate'], [GenerateAudio.id]: ['generate'], [Ffmpeg.id]: ['*'], + // Paid external-provider lookups (hosted-key cost), like the media tools. + [enrichmentRunServerTool.name]: ['*'], } function isWritePermission(userPermission: string): boolean { @@ -151,11 +150,11 @@ const baseServerToolRegistry: Record = { [setEnvironmentVariablesServerTool.name]: setEnvironmentVariablesServerTool, [getCredentialsServerTool.name]: getCredentialsServerTool, [knowledgeBaseServerTool.name]: knowledgeBaseServerTool, + [enrichmentRunServerTool.name]: enrichmentRunServerTool, [userTableServerTool.name]: userTableServerTool, [workspaceFileServerTool.name]: workspaceFileServerTool, [editContentServerTool.name]: editContentServerTool, [createFileServerTool.name]: createFileServerTool, - [touchPlanServerTool.name]: touchPlanServerTool, [renameFileServerTool.name]: renameFileServerTool, [deleteFileServerTool.name]: deleteFileServerTool, [moveFileServerTool.name]: moveFileServerTool, @@ -172,12 +171,7 @@ const baseServerToolRegistry: Record = { } function getServerToolRegistry(): Record { - if (isMothershipBetaFeaturesEnabled) { - return baseServerToolRegistry - } - const registry = { ...baseServerToolRegistry } - delete registry[touchPlanServerTool.name] - return registry + return baseServerToolRegistry } export function getRegisteredServerToolNames(): string[] { diff --git a/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts b/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts index b042789c194..f27adb77b4e 100644 --- a/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts +++ b/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { generateId, isValidUuid } from '@sim/utils/id' +import { sortObjectKeysDeep } from '@sim/utils/object' import type { PermissionGroupConfig } from '@/lib/permission-groups/types' import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/block-outputs' import { @@ -384,25 +385,9 @@ export function normalizeResponseFormat(value: any): string { // If it's an object, stringify it with consistent formatting if (obj && typeof obj === 'object') { - // Sort keys recursively for consistent comparison - const sortKeys = (item: any): any => { - if (Array.isArray(item)) { - return item.map(sortKeys) - } - if (item !== null && typeof item === 'object') { - return Object.keys(item) - .sort() - .reduce((result: any, key: string) => { - result[key] = sortKeys(item[key]) - return result - }, {}) - } - return item - } - // Return pretty-printed with 2-space indentation for UI readability // The sanitizer will normalize it to minified format for comparison - return JSON.stringify(sortKeys(obj), null, 2) + return JSON.stringify(sortObjectKeysDeep(obj), null, 2) } return String(value) diff --git a/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/validation.ts b/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/validation.ts index bce551f32b6..bf43f411f29 100644 --- a/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/validation.ts +++ b/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/validation.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' import { validateSelectorIds } from '@/lib/copilot/validation/selector-validator' +import { isBlockTypeAccessControlExempt } from '@/lib/permission-groups/block-access' import type { PermissionGroupConfig } from '@/lib/permission-groups/types' import { buildCanonicalIndex, @@ -714,6 +715,9 @@ export function isBlockTypeAllowed( blockType: string, permissionConfig: PermissionGroupConfig | null ): boolean { + if (isBlockTypeAccessControlExempt(blockType)) { + return true + } if (!permissionConfig || permissionConfig.allowedIntegrations === null) { return true } diff --git a/apps/sim/lib/copilot/vfs/resource-writer.ts b/apps/sim/lib/copilot/vfs/resource-writer.ts index 476c9186c83..460f6ba36dd 100644 --- a/apps/sim/lib/copilot/vfs/resource-writer.ts +++ b/apps/sim/lib/copilot/vfs/resource-writer.ts @@ -207,9 +207,7 @@ async function resolveWorkflowAliasFileTarget(args: { includeReservedSystemFolders: true, }) if (!folderId) { - throw new Error( - `Plan backing directory is not provisioned for ${args.alias.aliasPath}. Create the plan with touch_plan first.` - ) + throw new Error(`Plan backing directory is not provisioned for ${args.alias.aliasPath}.`) } return { diff --git a/apps/sim/lib/core/utils/records.test.ts b/apps/sim/lib/core/utils/records.test.ts index 97a46f0e5dc..80195d71ccc 100644 --- a/apps/sim/lib/core/utils/records.test.ts +++ b/apps/sim/lib/core/utils/records.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { - isPlainRecord, normalizeRecord, normalizeRecordMap, normalizeStringRecord, @@ -8,13 +7,6 @@ import { } from '@/lib/core/utils/records' describe('record normalization utilities', () => { - it('identifies plain records without accepting arrays or null', () => { - expect(isPlainRecord({})).toBe(true) - expect(isPlainRecord(Object.create(null))).toBe(true) - expect(isPlainRecord([])).toBe(false) - expect(isPlainRecord(null)).toBe(false) - }) - it('normalizes unknown values to object records', () => { expect(normalizeRecord({ value: 1 })).toEqual({ value: 1 }) expect(normalizeRecord([])).toEqual({}) diff --git a/apps/sim/lib/core/utils/records.ts b/apps/sim/lib/core/utils/records.ts index f5e0c4842ca..b13554b5c54 100644 --- a/apps/sim/lib/core/utils/records.ts +++ b/apps/sim/lib/core/utils/records.ts @@ -1,18 +1,8 @@ +import { isPlainRecord } from '@sim/utils/object' + export type UnknownRecord = Record export type StringRecord = Record -/** - * Returns true only for object-map values, excluding arrays and null. - */ -export function isPlainRecord(value: unknown): value is UnknownRecord { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - return false - } - - const prototype = Object.getPrototypeOf(value) - return prototype === Object.prototype || prototype === null -} - /** * Normalizes optional execution context maps to the record shape expected by * internal API contracts. diff --git a/apps/sim/lib/execution/sandbox/bundles/docx.cjs b/apps/sim/lib/execution/sandbox/bundles/docx.cjs index 01697107612..f94ae48b832 100644 --- a/apps/sim/lib/execution/sandbox/bundles/docx.cjs +++ b/apps/sim/lib/execution/sandbox/bundles/docx.cjs @@ -1,42 +1,27 @@ // sandbox bundle: docx // generated by apps/sim/lib/execution/sandbox/bundles/build.ts // do not edit by hand. run `bun run build:sandbox-bundles` to regenerate. -(()=>{var R5=Object.create;var{getPrototypeOf:L5,defineProperty:p1,getOwnPropertyNames:I5}=Object;var O5=Object.prototype.hasOwnProperty;function F5(B){return this[B]}var H5,W5,P5=(B,U,G)=>{var Y=B!=null&&typeof B==="object";if(Y){var Q=U?H5??=new WeakMap:W5??=new WeakMap,K=Q.get(B);if(K)return K}G=B!=null?R5(L5(B)):{};let Z=U||!B||!B.__esModule?p1(G,"default",{value:B,enumerable:!0}):G;for(let J of I5(B))if(!O5.call(Z,J))p1(Z,J,{get:F5.bind(B,J),enumerable:!0});if(Y)Q.set(B,Z);return Z};var w5=(B,U)=>()=>(U||B((U={exports:{}}).exports,U),U.exports);var A5=(B)=>B;function j5(B,U){this[B]=A5.bind(null,U)}var N5=(B,U)=>{for(var G in U)p1(B,G,{get:U[G],enumerable:!0,configurable:!0,set:j5.bind(U,G)})};var h6=w5((L7,_6)=>{var z0=_6.exports={},p0,r0;function Y8(){throw Error("setTimeout has not been defined")}function Z8(){throw Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function")p0=setTimeout;else p0=Y8}catch(B){p0=Y8}try{if(typeof clearTimeout==="function")r0=clearTimeout;else r0=Z8}catch(B){r0=Z8}})();function g6(B){if(p0===setTimeout)return setTimeout(B,0);if((p0===Y8||!p0)&&setTimeout)return p0=setTimeout,setTimeout(B,0);try{return p0(B,0)}catch(U){try{return p0.call(null,B,0)}catch(G){return p0.call(this,B,0)}}}function UU(B){if(r0===clearTimeout)return clearTimeout(B);if((r0===Z8||!r0)&&clearTimeout)return r0=clearTimeout,clearTimeout(B);try{return r0(B)}catch(U){try{return r0.call(null,B)}catch(G){return r0.call(this,B)}}}var Q2=[],b2=!1,z2,j1=-1;function GU(){if(!b2||!z2)return;if(b2=!1,z2.length)Q2=z2.concat(Q2);else j1=-1;if(Q2.length)f6()}function f6(){if(b2)return;var B=g6(GU);b2=!0;var U=Q2.length;while(U){z2=Q2,Q2=[];while(++j11)for(var G=1;G"u")O6.global=globalThis;var l0=[],h0=[],r1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(j2=0,F6=r1.length;j20)throw Error("Invalid string. Length must be a multiple of 4");var G=B.indexOf("=");if(G===-1)G=U;var Y=G===U?0:4-G%4;return[G,Y]}function E5(B,U){return(B+U)*3/4-U}function T5(B){var U,G=z5(B),Y=G[0],Q=G[1],K=new Uint8Array(E5(Y,Q)),Z=0,J=Q>0?Y-4:Y,M;for(M=0;M>16&255,K[Z++]=U>>8&255,K[Z++]=U&255;if(Q===2)U=h0[B.charCodeAt(M)]<<2|h0[B.charCodeAt(M+1)]>>4,K[Z++]=U&255;if(Q===1)U=h0[B.charCodeAt(M)]<<10|h0[B.charCodeAt(M+1)]<<4|h0[B.charCodeAt(M+2)]>>2,K[Z++]=U>>8&255,K[Z++]=U&255;return K}function D5(B){return l0[B>>18&63]+l0[B>>12&63]+l0[B>>6&63]+l0[B&63]}function C5(B,U,G){var Y,Q=[];for(var K=U;KJ?J:Z+K));if(Y===1)U=B[G-1],Q.push(l0[U>>2]+l0[U<<4&63]+"==");else if(Y===2)U=(B[G-2]<<8)+B[G-1],Q.push(l0[U>>10]+l0[U>>4&63]+l0[U<<2&63]+"=");return Q.join("")}function w1(B,U,G,Y,Q){var K,Z,J=Q*8-Y-1,M=(1<>1,I=-7,F=G?Q-1:0,D=G?-1:1,w=B[U+F];F+=D,K=w&(1<<-I)-1,w>>=-I,I+=J;for(;I>0;K=K*256+B[U+F],F+=D,I-=8);Z=K&(1<<-I)-1,K>>=-I,I+=Y;for(;I>0;Z=Z*256+B[U+F],F+=D,I-=8);if(K===0)K=1-W;else if(K===M)return Z?NaN:(w?-1:1)*(1/0);else Z=Z+Math.pow(2,Y),K=K-W;return(w?-1:1)*Z*Math.pow(2,K-Y)}function j6(B,U,G,Y,Q,K){var Z,J,M,W=K*8-Q-1,I=(1<>1,D=Q===23?Math.pow(2,-24)-Math.pow(2,-77):0,w=Y?0:K-1,P=Y?1:-1,A=U<0||U===0&&1/U<0?1:0;if(U=Math.abs(U),isNaN(U)||U===1/0)J=isNaN(U)?1:0,Z=I;else{if(Z=Math.floor(Math.log(U)/Math.LN2),U*(M=Math.pow(2,-Z))<1)Z--,M*=2;if(Z+F>=1)U+=D/M;else U+=D*Math.pow(2,1-F);if(U*M>=2)Z++,M/=2;if(Z+F>=I)J=0,Z=I;else if(Z+F>=1)J=(U*M-1)*Math.pow(2,Q),Z=Z+F;else J=U*Math.pow(2,F-1)*Math.pow(2,Q),Z=0}for(;Q>=8;B[G+w]=J&255,w+=P,J/=256,Q-=8);Z=Z<0;B[G+w]=Z&255,w+=P,Z/=256,W-=8);B[G+w-P]|=A*128}var W6=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null,k5=50,i1=2147483647;var{btoa:Z7,atob:Q7,File:J7,Blob:K7}=globalThis;function Z2(B){if(B>i1)throw RangeError('The value "'+B+'" is invalid for option "size"');let U=new Uint8Array(B);return Object.setPrototypeOf(U,J0.prototype),U}function e1(B,U,G){return class extends G{constructor(){super();Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${B}]`,this.stack,delete this.name}get code(){return B}set code(Y){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:Y,writable:!0})}toString(){return`${this.name} [${B}]: ${this.message}`}}}var $5=e1("ERR_BUFFER_OUT_OF_BOUNDS",function(B){if(B)return`${B} is outside of buffer bounds`;return"Attempt to access memory outside buffer bounds"},RangeError),S5=e1("ERR_INVALID_ARG_TYPE",function(B,U){return`The "${B}" argument must be of type number. Received type ${typeof U}`},TypeError),n1=e1("ERR_OUT_OF_RANGE",function(B,U,G){let Y=`The value of "${B}" is out of range.`,Q=G;if(Number.isInteger(G)&&Math.abs(G)>4294967296)Q=A6(String(G));else if(typeof G==="bigint"){if(Q=String(G),G>BigInt(2)**BigInt(32)||G<-(BigInt(2)**BigInt(32)))Q=A6(Q);Q+="n"}return Y+=` It must be ${U}. Received ${Q}`,Y},RangeError);function J0(B,U,G){if(typeof B==="number"){if(typeof U==="string")throw TypeError('The "string" argument must be of type string. Received type number');return B8(B)}return N6(B,U,G)}Object.defineProperty(J0.prototype,"parent",{enumerable:!0,get:function(){if(!J0.isBuffer(this))return;return this.buffer}});Object.defineProperty(J0.prototype,"offset",{enumerable:!0,get:function(){if(!J0.isBuffer(this))return;return this.byteOffset}});J0.poolSize=8192;function N6(B,U,G){if(typeof B==="string")return v5(B,U);if(ArrayBuffer.isView(B))return y5(B);if(B==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof B);if(a0(B,ArrayBuffer)||B&&a0(B.buffer,ArrayBuffer))return o1(B,U,G);if(typeof SharedArrayBuffer<"u"&&(a0(B,SharedArrayBuffer)||B&&a0(B.buffer,SharedArrayBuffer)))return o1(B,U,G);if(typeof B==="number")throw TypeError('The "value" argument must not be of type number. Received type number');let Y=B.valueOf&&B.valueOf();if(Y!=null&&Y!==B)return J0.from(Y,U,G);let Q=g5(B);if(Q)return Q;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof B[Symbol.toPrimitive]==="function")return J0.from(B[Symbol.toPrimitive]("string"),U,G);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof B)}J0.from=function(B,U,G){return N6(B,U,G)};Object.setPrototypeOf(J0.prototype,Uint8Array.prototype);Object.setPrototypeOf(J0,Uint8Array);function z6(B){if(typeof B!=="number")throw TypeError('"size" argument must be of type number');else if(B<0)throw RangeError('The value "'+B+'" is invalid for option "size"')}function b5(B,U,G){if(z6(B),B<=0)return Z2(B);if(U!==void 0)return typeof G==="string"?Z2(B).fill(U,G):Z2(B).fill(U);return Z2(B)}J0.alloc=function(B,U,G){return b5(B,U,G)};function B8(B){return z6(B),Z2(B<0?0:U8(B)|0)}J0.allocUnsafe=function(B){return B8(B)};J0.allocUnsafeSlow=function(B){return B8(B)};function v5(B,U){if(typeof U!=="string"||U==="")U="utf8";if(!J0.isEncoding(U))throw TypeError("Unknown encoding: "+U);let G=E6(B,U)|0,Y=Z2(G),Q=Y.write(B,U);if(Q!==G)Y=Y.slice(0,Q);return Y}function s1(B){let U=B.length<0?0:U8(B.length)|0,G=Z2(U);for(let Y=0;Y=i1)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i1.toString(16)+" bytes");return B|0}J0.isBuffer=function(B){return B!=null&&B._isBuffer===!0&&B!==J0.prototype};J0.compare=function(B,U){if(a0(B,Uint8Array))B=J0.from(B,B.offset,B.byteLength);if(a0(U,Uint8Array))U=J0.from(U,U.offset,U.byteLength);if(!J0.isBuffer(B)||!J0.isBuffer(U))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(B===U)return 0;let G=B.length,Y=U.length;for(let Q=0,K=Math.min(G,Y);QY.length){if(!J0.isBuffer(K))K=J0.from(K);K.copy(Y,Q)}else Uint8Array.prototype.set.call(Y,K,Q);else if(!J0.isBuffer(K))throw TypeError('"list" argument must be an Array of Buffers');else K.copy(Y,Q);Q+=K.length}return Y};function E6(B,U){if(J0.isBuffer(B))return B.length;if(ArrayBuffer.isView(B)||a0(B,ArrayBuffer))return B.byteLength;if(typeof B!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof B);let G=B.length,Y=arguments.length>2&&arguments[2]===!0;if(!Y&&G===0)return 0;let Q=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return G;case"utf8":case"utf-8":return t1(B).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G*2;case"hex":return G>>>1;case"base64":return y6(B).length;default:if(Q)return Y?-1:t1(B).length;U=(""+U).toLowerCase(),Q=!0}}J0.byteLength=E6;function f5(B,U,G){let Y=!1;if(U===void 0||U<0)U=0;if(U>this.length)return"";if(G===void 0||G>this.length)G=this.length;if(G<=0)return"";if(G>>>=0,U>>>=0,G<=U)return"";if(!B)B="utf8";while(!0)switch(B){case"hex":return p5(this,U,G);case"utf8":case"utf-8":return D6(this,U,G);case"ascii":return l5(this,U,G);case"latin1":case"binary":return a5(this,U,G);case"base64":return c5(this,U,G);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r5(this,U,G);default:if(Y)throw TypeError("Unknown encoding: "+B);B=(B+"").toLowerCase(),Y=!0}}J0.prototype._isBuffer=!0;function N2(B,U,G){let Y=B[U];B[U]=B[G],B[G]=Y}J0.prototype.swap16=function(){let B=this.length;if(B%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;UU)B+=" ... ";return""};if(W6)J0.prototype[W6]=J0.prototype.inspect;J0.prototype.compare=function(B,U,G,Y,Q){if(a0(B,Uint8Array))B=J0.from(B,B.offset,B.byteLength);if(!J0.isBuffer(B))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof B);if(U===void 0)U=0;if(G===void 0)G=B?B.length:0;if(Y===void 0)Y=0;if(Q===void 0)Q=this.length;if(U<0||G>B.length||Y<0||Q>this.length)throw RangeError("out of range index");if(Y>=Q&&U>=G)return 0;if(Y>=Q)return-1;if(U>=G)return 1;if(U>>>=0,G>>>=0,Y>>>=0,Q>>>=0,this===B)return 0;let K=Q-Y,Z=G-U,J=Math.min(K,Z),M=this.slice(Y,Q),W=B.slice(U,G);for(let I=0;I2147483647)G=2147483647;else if(G<-2147483648)G=-2147483648;if(G=+G,Number.isNaN(G))G=Q?0:B.length-1;if(G<0)G=B.length+G;if(G>=B.length)if(Q)return-1;else G=B.length-1;else if(G<0)if(Q)G=0;else return-1;if(typeof U==="string")U=J0.from(U,Y);if(J0.isBuffer(U)){if(U.length===0)return-1;return P6(B,U,G,Y,Q)}else if(typeof U==="number"){if(U=U&255,typeof Uint8Array.prototype.indexOf==="function")if(Q)return Uint8Array.prototype.indexOf.call(B,U,G);else return Uint8Array.prototype.lastIndexOf.call(B,U,G);return P6(B,[U],G,Y,Q)}throw TypeError("val must be string, number or Buffer")}function P6(B,U,G,Y,Q){let K=1,Z=B.length,J=U.length;if(Y!==void 0){if(Y=String(Y).toLowerCase(),Y==="ucs2"||Y==="ucs-2"||Y==="utf16le"||Y==="utf-16le"){if(B.length<2||U.length<2)return-1;K=2,Z/=2,J/=2,G/=2}}function M(I,F){if(K===1)return I[F];else return I.readUInt16BE(F*K)}let W;if(Q){let I=-1;for(W=G;WZ)G=Z-J;for(W=G;W>=0;W--){let I=!0;for(let F=0;FQ)Y=Q;let K=U.length;if(Y>K/2)Y=K/2;let Z;for(Z=0;Z>>0,isFinite(G)){if(G=G>>>0,Y===void 0)Y="utf8"}else Y=G,G=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Q=this.length-U;if(G===void 0||G>Q)G=Q;if(B.length>0&&(G<0||U<0)||U>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!Y)Y="utf8";let K=!1;for(;;)switch(Y){case"hex":return x5(this,B,U,G);case"utf8":case"utf-8":return _5(this,B,U,G);case"ascii":case"latin1":case"binary":return h5(this,B,U,G);case"base64":return u5(this,B,U,G);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return d5(this,B,U,G);default:if(K)throw TypeError("Unknown encoding: "+Y);Y=(""+Y).toLowerCase(),K=!0}};J0.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function c5(B,U,G){if(U===0&&G===B.length)return H6(B);else return H6(B.slice(U,G))}function D6(B,U,G){G=Math.min(B.length,G);let Y=[],Q=U;while(Q239?4:K>223?3:K>191?2:1;if(Q+J<=G){let M,W,I,F;switch(J){case 1:if(K<128)Z=K;break;case 2:if(M=B[Q+1],(M&192)===128){if(F=(K&31)<<6|M&63,F>127)Z=F}break;case 3:if(M=B[Q+1],W=B[Q+2],(M&192)===128&&(W&192)===128){if(F=(K&15)<<12|(M&63)<<6|W&63,F>2047&&(F<55296||F>57343))Z=F}break;case 4:if(M=B[Q+1],W=B[Q+2],I=B[Q+3],(M&192)===128&&(W&192)===128&&(I&192)===128){if(F=(K&15)<<18|(M&63)<<12|(W&63)<<6|I&63,F>65535&&F<1114112)Z=F}}}if(Z===null)Z=65533,J=1;else if(Z>65535)Z-=65536,Y.push(Z>>>10&1023|55296),Z=56320|Z&1023;Y.push(Z),Q+=J}return m5(Y)}var w6=4096;function m5(B){let U=B.length;if(U<=w6)return String.fromCharCode.apply(String,B);let G="",Y=0;while(YY)G=Y;let Q="";for(let K=U;KG)B=G;if(U<0){if(U+=G,U<0)U=0}else if(U>G)U=G;if(UG)throw RangeError("Trying to access beyond buffer length")}J0.prototype.readUintLE=J0.prototype.readUIntLE=function(B,U,G){if(B=B>>>0,U=U>>>0,!G)$0(B,U,this.length);let Y=this[B],Q=1,K=0;while(++K>>0,U=U>>>0,!G)$0(B,U,this.length);let Y=this[B+--U],Q=1;while(U>0&&(Q*=256))Y+=this[B+--U]*Q;return Y};J0.prototype.readUint8=J0.prototype.readUInt8=function(B,U){if(B=B>>>0,!U)$0(B,1,this.length);return this[B]};J0.prototype.readUint16LE=J0.prototype.readUInt16LE=function(B,U){if(B=B>>>0,!U)$0(B,2,this.length);return this[B]|this[B+1]<<8};J0.prototype.readUint16BE=J0.prototype.readUInt16BE=function(B,U){if(B=B>>>0,!U)$0(B,2,this.length);return this[B]<<8|this[B+1]};J0.prototype.readUint32LE=J0.prototype.readUInt32LE=function(B,U){if(B=B>>>0,!U)$0(B,4,this.length);return(this[B]|this[B+1]<<8|this[B+2]<<16)+this[B+3]*16777216};J0.prototype.readUint32BE=J0.prototype.readUInt32BE=function(B,U){if(B=B>>>0,!U)$0(B,4,this.length);return this[B]*16777216+(this[B+1]<<16|this[B+2]<<8|this[B+3])};J0.prototype.readBigUInt64LE=I2(function(B){B=B>>>0,S2(B,"offset");let U=this[B],G=this[B+7];if(U===void 0||G===void 0)n2(B,this.length-8);let Y=U+this[++B]*256+this[++B]*65536+this[++B]*16777216,Q=this[++B]+this[++B]*256+this[++B]*65536+G*16777216;return BigInt(Y)+(BigInt(Q)<>>0,S2(B,"offset");let U=this[B],G=this[B+7];if(U===void 0||G===void 0)n2(B,this.length-8);let Y=U*16777216+this[++B]*65536+this[++B]*256+this[++B],Q=this[++B]*16777216+this[++B]*65536+this[++B]*256+G;return(BigInt(Y)<>>0,U=U>>>0,!G)$0(B,U,this.length);let Y=this[B],Q=1,K=0;while(++K=Q)Y-=Math.pow(2,8*U);return Y};J0.prototype.readIntBE=function(B,U,G){if(B=B>>>0,U=U>>>0,!G)$0(B,U,this.length);let Y=U,Q=1,K=this[B+--Y];while(Y>0&&(Q*=256))K+=this[B+--Y]*Q;if(Q*=128,K>=Q)K-=Math.pow(2,8*U);return K};J0.prototype.readInt8=function(B,U){if(B=B>>>0,!U)$0(B,1,this.length);if(!(this[B]&128))return this[B];return(255-this[B]+1)*-1};J0.prototype.readInt16LE=function(B,U){if(B=B>>>0,!U)$0(B,2,this.length);let G=this[B]|this[B+1]<<8;return G&32768?G|4294901760:G};J0.prototype.readInt16BE=function(B,U){if(B=B>>>0,!U)$0(B,2,this.length);let G=this[B+1]|this[B]<<8;return G&32768?G|4294901760:G};J0.prototype.readInt32LE=function(B,U){if(B=B>>>0,!U)$0(B,4,this.length);return this[B]|this[B+1]<<8|this[B+2]<<16|this[B+3]<<24};J0.prototype.readInt32BE=function(B,U){if(B=B>>>0,!U)$0(B,4,this.length);return this[B]<<24|this[B+1]<<16|this[B+2]<<8|this[B+3]};J0.prototype.readBigInt64LE=I2(function(B){B=B>>>0,S2(B,"offset");let U=this[B],G=this[B+7];if(U===void 0||G===void 0)n2(B,this.length-8);let Y=this[B+4]+this[B+5]*256+this[B+6]*65536+(G<<24);return(BigInt(Y)<>>0,S2(B,"offset");let U=this[B],G=this[B+7];if(U===void 0||G===void 0)n2(B,this.length-8);let Y=(U<<24)+this[++B]*65536+this[++B]*256+this[++B];return(BigInt(Y)<>>0,!U)$0(B,4,this.length);return w1(this,B,!0,23,4)};J0.prototype.readFloatBE=function(B,U){if(B=B>>>0,!U)$0(B,4,this.length);return w1(this,B,!1,23,4)};J0.prototype.readDoubleLE=function(B,U){if(B=B>>>0,!U)$0(B,8,this.length);return w1(this,B,!0,52,8)};J0.prototype.readDoubleBE=function(B,U){if(B=B>>>0,!U)$0(B,8,this.length);return w1(this,B,!1,52,8)};function g0(B,U,G,Y,Q,K){if(!J0.isBuffer(B))throw TypeError('"buffer" argument must be a Buffer instance');if(U>Q||UB.length)throw RangeError("Index out of range")}J0.prototype.writeUintLE=J0.prototype.writeUIntLE=function(B,U,G,Y){if(B=+B,U=U>>>0,G=G>>>0,!Y){let Z=Math.pow(2,8*G)-1;g0(this,B,U,G,Z,0)}let Q=1,K=0;this[U]=B&255;while(++K>>0,G=G>>>0,!Y){let Z=Math.pow(2,8*G)-1;g0(this,B,U,G,Z,0)}let Q=G-1,K=1;this[U+Q]=B&255;while(--Q>=0&&(K*=256))this[U+Q]=B/K&255;return U+G};J0.prototype.writeUint8=J0.prototype.writeUInt8=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,1,255,0);return this[U]=B&255,U+1};J0.prototype.writeUint16LE=J0.prototype.writeUInt16LE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,2,65535,0);return this[U]=B&255,this[U+1]=B>>>8,U+2};J0.prototype.writeUint16BE=J0.prototype.writeUInt16BE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,2,65535,0);return this[U]=B>>>8,this[U+1]=B&255,U+2};J0.prototype.writeUint32LE=J0.prototype.writeUInt32LE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,4,4294967295,0);return this[U+3]=B>>>24,this[U+2]=B>>>16,this[U+1]=B>>>8,this[U]=B&255,U+4};J0.prototype.writeUint32BE=J0.prototype.writeUInt32BE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,4,4294967295,0);return this[U]=B>>>24,this[U+1]=B>>>16,this[U+2]=B>>>8,this[U+3]=B&255,U+4};function C6(B,U,G,Y,Q){v6(U,Y,Q,B,G,7);let K=Number(U&BigInt(4294967295));B[G++]=K,K=K>>8,B[G++]=K,K=K>>8,B[G++]=K,K=K>>8,B[G++]=K;let Z=Number(U>>BigInt(32)&BigInt(4294967295));return B[G++]=Z,Z=Z>>8,B[G++]=Z,Z=Z>>8,B[G++]=Z,Z=Z>>8,B[G++]=Z,G}function k6(B,U,G,Y,Q){v6(U,Y,Q,B,G,7);let K=Number(U&BigInt(4294967295));B[G+7]=K,K=K>>8,B[G+6]=K,K=K>>8,B[G+5]=K,K=K>>8,B[G+4]=K;let Z=Number(U>>BigInt(32)&BigInt(4294967295));return B[G+3]=Z,Z=Z>>8,B[G+2]=Z,Z=Z>>8,B[G+1]=Z,Z=Z>>8,B[G]=Z,G+8}J0.prototype.writeBigUInt64LE=I2(function(B,U=0){return C6(this,B,U,BigInt(0),BigInt("0xffffffffffffffff"))});J0.prototype.writeBigUInt64BE=I2(function(B,U=0){return k6(this,B,U,BigInt(0),BigInt("0xffffffffffffffff"))});J0.prototype.writeIntLE=function(B,U,G,Y){if(B=+B,U=U>>>0,!Y){let J=Math.pow(2,8*G-1);g0(this,B,U,G,J-1,-J)}let Q=0,K=1,Z=0;this[U]=B&255;while(++Q>0)-Z&255}return U+G};J0.prototype.writeIntBE=function(B,U,G,Y){if(B=+B,U=U>>>0,!Y){let J=Math.pow(2,8*G-1);g0(this,B,U,G,J-1,-J)}let Q=G-1,K=1,Z=0;this[U+Q]=B&255;while(--Q>=0&&(K*=256)){if(B<0&&Z===0&&this[U+Q+1]!==0)Z=1;this[U+Q]=(B/K>>0)-Z&255}return U+G};J0.prototype.writeInt8=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,1,127,-128);if(B<0)B=255+B+1;return this[U]=B&255,U+1};J0.prototype.writeInt16LE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,2,32767,-32768);return this[U]=B&255,this[U+1]=B>>>8,U+2};J0.prototype.writeInt16BE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,2,32767,-32768);return this[U]=B>>>8,this[U+1]=B&255,U+2};J0.prototype.writeInt32LE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,4,2147483647,-2147483648);return this[U]=B&255,this[U+1]=B>>>8,this[U+2]=B>>>16,this[U+3]=B>>>24,U+4};J0.prototype.writeInt32BE=function(B,U,G){if(B=+B,U=U>>>0,!G)g0(this,B,U,4,2147483647,-2147483648);if(B<0)B=4294967295+B+1;return this[U]=B>>>24,this[U+1]=B>>>16,this[U+2]=B>>>8,this[U+3]=B&255,U+4};J0.prototype.writeBigInt64LE=I2(function(B,U=0){return C6(this,B,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});J0.prototype.writeBigInt64BE=I2(function(B,U=0){return k6(this,B,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function $6(B,U,G,Y,Q,K){if(G+Y>B.length)throw RangeError("Index out of range");if(G<0)throw RangeError("Index out of range")}function S6(B,U,G,Y,Q){if(U=+U,G=G>>>0,!Q)$6(B,U,G,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return j6(B,U,G,Y,23,4),G+4}J0.prototype.writeFloatLE=function(B,U,G){return S6(this,B,U,!0,G)};J0.prototype.writeFloatBE=function(B,U,G){return S6(this,B,U,!1,G)};function b6(B,U,G,Y,Q){if(U=+U,G=G>>>0,!Q)$6(B,U,G,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return j6(B,U,G,Y,52,8),G+8}J0.prototype.writeDoubleLE=function(B,U,G){return b6(this,B,U,!0,G)};J0.prototype.writeDoubleBE=function(B,U,G){return b6(this,B,U,!1,G)};J0.prototype.copy=function(B,U,G,Y){if(!J0.isBuffer(B))throw TypeError("argument should be a Buffer");if(!G)G=0;if(!Y&&Y!==0)Y=this.length;if(U>=B.length)U=B.length;if(!U)U=0;if(Y>0&&Y=this.length)throw RangeError("Index out of range");if(Y<0)throw RangeError("sourceEnd out of bounds");if(Y>this.length)Y=this.length;if(B.length-U>>0,G=G===void 0?this.length:G>>>0,!B)B=0;let Q;if(typeof B==="number")for(Q=U;Q=Y+4;G-=3)U=`_${B.slice(G-3,G)}${U}`;return`${B.slice(0,G)}${U}`}function i5(B,U,G){if(S2(U,"offset"),B[U]===void 0||B[U+G]===void 0)n2(U,B.length-(G+1))}function v6(B,U,G,Y,Q,K){if(B>G||B3)if(U===0||U===BigInt(0))J=`>= 0${Z} and < 2${Z} ** ${(K+1)*8}${Z}`;else J=`>= -(2${Z} ** ${(K+1)*8-1}${Z}) and < 2 ** ${(K+1)*8-1}${Z}`;else J=`>= ${U}${Z} and <= ${G}${Z}`;throw new n1("value",J,B)}i5(Y,Q,K)}function S2(B,U){if(typeof B!=="number")throw new S5(U,"number",B)}function n2(B,U,G){if(Math.floor(B)!==B)throw S2(B,G),new n1(G||"offset","an integer",B);if(U<0)throw new $5;throw new n1(G||"offset",`>= ${G?1:0} and <= ${U}`,B)}var n5=/[^+/0-9A-Za-z-_]/g;function s5(B){if(B=B.split("=")[0],B=B.trim().replace(n5,""),B.length<2)return"";while(B.length%4!==0)B=B+"=";return B}function t1(B,U){U=U||1/0;let G,Y=B.length,Q=null,K=[];for(let Z=0;Z55295&&G<57344){if(!Q){if(G>56319){if((U-=3)>-1)K.push(239,191,189);continue}else if(Z+1===Y){if((U-=3)>-1)K.push(239,191,189);continue}Q=G;continue}if(G<56320){if((U-=3)>-1)K.push(239,191,189);Q=G;continue}G=(Q-55296<<10|G-56320)+65536}else if(Q){if((U-=3)>-1)K.push(239,191,189)}if(Q=null,G<128){if((U-=1)<0)break;K.push(G)}else if(G<2048){if((U-=2)<0)break;K.push(G>>6|192,G&63|128)}else if(G<65536){if((U-=3)<0)break;K.push(G>>12|224,G>>6&63|128,G&63|128)}else if(G<1114112){if((U-=4)<0)break;K.push(G>>18|240,G>>12&63|128,G>>6&63|128,G&63|128)}else throw Error("Invalid code point")}return K}function o5(B){let U=[];for(let G=0;G>8,Q=G%256,K.push(Q),K.push(Y)}return K}function y6(B){return T5(s5(B))}function A1(B,U,G,Y){let Q;for(Q=0;Q=U.length||Q>=B.length)break;U[Q+G]=B[Q]}return Q}function a0(B,U){return B instanceof U||B!=null&&B.constructor!=null&&B.constructor.name!=null&&B.constructor.name===U.name}var e5=function(){let B=Array(256);for(let U=0;U<16;++U){let G=U*16;for(let Y=0;Y<16;++Y)B[G+Y]="0123456789abcdef"[U]+"0123456789abcdef"[Y]}return B}();function I2(B){return typeof BigInt>"u"?BU:B}function BU(){throw Error("BigInt not supported")}function G8(B){return()=>{throw Error(B+" is not implemented for node:buffer browser polyfill")}}var V7=G8("resolveObjectURL"),q7=G8("isUtf8");var M7=G8("transcode");var G7=P5(h6(),1);var R6={};N5(R6,{unsignedDecimalNumber:()=>q1,universalMeasureValue:()=>M1,uniqueUuid:()=>eB,uniqueNumericIdCreator:()=>I1,uniqueId:()=>O1,uCharHexNumber:()=>H8,twipsMeasureValue:()=>E0,standardizeData:()=>A4,signedTwipsMeasureValue:()=>t0,signedHpsMeasureValue:()=>VG,shortHexNumber:()=>SB,sectionPageSizeDefaults:()=>k1,sectionMarginDefaults:()=>F2,positiveUniversalMeasureValue:()=>u8,pointMeasureValue:()=>gB,percentageValue:()=>vB,patchDocument:()=>tK,patchDetector:()=>B7,measurementOrPercentValue:()=>d8,longHexNumber:()=>KG,hpsMeasureValue:()=>bB,hexColorValue:()=>C2,hashedId:()=>W8,encodeUtf8:()=>U1,eighthPointMeasureValue:()=>yB,docPropertiesUniqueNumericIdGen:()=>oB,decimalNumber:()=>D0,dateTimeValue:()=>fB,createWrapTopAndBottom:()=>F4,createWrapTight:()=>O4,createWrapSquare:()=>I4,createWrapNone:()=>w8,createVerticalPosition:()=>J4,createVerticalAlign:()=>B6,createUnderline:()=>cB,createTransformation:()=>i8,createTableWidthElement:()=>J1,createTableRowHeight:()=>W9,createTableLook:()=>H9,createTableLayout:()=>O9,createTableFloatProperties:()=>I9,createTabStopItem:()=>b4,createTabStop:()=>v4,createStringElement:()=>f2,createSpacing:()=>S4,createSimplePos:()=>G4,createShading:()=>X1,createSectionType:()=>C9,createRunFonts:()=>T1,createParagraphStyle:()=>x2,createPageSize:()=>T9,createPageNumberType:()=>E9,createPageMargin:()=>z9,createOutlineLevel:()=>_4,createMathSuperScriptProperties:()=>p4,createMathSuperScriptElement:()=>a2,createMathSubSuperScriptProperties:()=>i4,createMathSubScriptProperties:()=>r4,createMathSubScriptElement:()=>l2,createMathPreSubSuperScriptProperties:()=>n4,createMathNAryProperties:()=>t8,createMathLimitLocation:()=>a4,createMathBase:()=>y0,createMathAccentCharacter:()=>l4,createLineNumberType:()=>j9,createIndent:()=>hB,createHorizontalPosition:()=>Q4,createHeaderFooterReference:()=>C1,createFrameProperties:()=>u4,createEmphasisMark:()=>p8,createDotEmphasisMark:()=>wG,createDocumentGrid:()=>A9,createColumns:()=>w9,createBorderElement:()=>A0,createBodyProperties:()=>K4,createAlignment:()=>c8,convertToXmlComponent:()=>h1,convertMillimetersToTwip:()=>dG,convertInchesToTwip:()=>u0,concreteNumUniqueNumericIdGen:()=>sB,commentIdToParaId:()=>N4,bookmarkUniqueNumericIdGen:()=>tB,abstractNumUniqueNumericIdGen:()=>nB,YearShort:()=>oY,YearLong:()=>BZ,XmlComponent:()=>t,XmlAttributeComponent:()=>F0,WpsShapeRun:()=>SY,WpgGroupRun:()=>bY,WidthType:()=>b1,WORKAROUND4:()=>oZ,WORKAROUND3:()=>JG,WORKAROUND2:()=>jJ,VerticalPositionRelativeFrom:()=>U4,VerticalPositionAlign:()=>XG,VerticalMergeType:()=>U6,VerticalMergeRevisionType:()=>HQ,VerticalMerge:()=>N8,VerticalAnchor:()=>cG,VerticalAlignTable:()=>K9,VerticalAlignSection:()=>V9,VerticalAlign:()=>WQ,UnderlineType:()=>r8,ThematicBreak:()=>_B,Textbox:()=>DK,TextWrappingType:()=>e2,TextWrappingSide:()=>L4,TextRun:()=>Q1,TextEffect:()=>CG,TextDirection:()=>NQ,TableRowPropertiesChange:()=>P9,TableRowProperties:()=>Q6,TableRow:()=>fQ,TableProperties:()=>Z6,TableOfContents:()=>RK,TableLayoutType:()=>SQ,TableCellBorders:()=>M9,TableCell:()=>G6,TableBorders:()=>Y6,TableAnchorType:()=>TQ,Table:()=>yQ,TabStopType:()=>j8,TabStopPosition:()=>HZ,Tab:()=>D4,TDirection:()=>R9,SymbolRun:()=>aB,Styles:()=>$1,StyleLevel:()=>LK,StyleForParagraph:()=>p2,StyleForCharacter:()=>$2,StringValueElement:()=>M2,StringEnumValueElement:()=>qG,StringContainer:()=>O2,SpaceType:()=>x0,SoftHyphen:()=>iY,SimpleMailMergeField:()=>fY,SimpleField:()=>n8,ShadingType:()=>HG,SequentialIdentifier:()=>yY,Separator:()=>YZ,SectionType:()=>GJ,SectionPropertiesChange:()=>k9,SectionProperties:()=>J6,RunPropertiesDefaults:()=>a9,RunPropertiesChange:()=>lB,RunProperties:()=>U2,Run:()=>T0,RelativeVerticalPosition:()=>CQ,RelativeHorizontalPosition:()=>DQ,PrettifyType:()=>G5,PositionalTabRelativeTo:()=>qZ,PositionalTabLeader:()=>MZ,PositionalTabAlignment:()=>VZ,PositionalTab:()=>RZ,PatchType:()=>D8,ParagraphRunProperties:()=>mB,ParagraphPropertiesDefaults:()=>l9,ParagraphPropertiesChange:()=>d4,ParagraphProperties:()=>X2,Paragraph:()=>d0,PageTextDirectionType:()=>BJ,PageTextDirection:()=>D9,PageReference:()=>CZ,PageOrientation:()=>y1,PageNumberSeparator:()=>eQ,PageNumberElement:()=>QZ,PageNumber:()=>H2,PageBreakBefore:()=>$4,PageBreak:()=>LZ,PageBorders:()=>N9,PageBorderZOrder:()=>tQ,PageBorderOffsetFrom:()=>oQ,PageBorderDisplay:()=>sQ,Packer:()=>Y5,OverlapType:()=>kQ,OnOffElement:()=>M0,Numbering:()=>d9,NumberedItemReferenceFormat:()=>zZ,NumberedItemReference:()=>TZ,NumberValueElement:()=>_2,NumberProperties:()=>D1,NumberFormat:()=>RG,NoBreakHyphen:()=>rY,NextAttributeComponent:()=>k8,MonthShort:()=>sY,MonthLong:()=>eY,Media:()=>K6,MathSuperScript:()=>rZ,MathSum:()=>mZ,MathSubSuperScript:()=>nZ,MathSubScript:()=>iZ,MathSquareBrackets:()=>QQ,MathRun:()=>hZ,MathRoundBrackets:()=>ZQ,MathRadicalProperties:()=>o4,MathRadical:()=>BQ,MathPreSubSuperScript:()=>sZ,MathNumerator:()=>m4,MathLimitUpper:()=>aZ,MathLimitLower:()=>pZ,MathLimit:()=>e8,MathIntegral:()=>lZ,MathFunctionProperties:()=>e4,MathFunctionName:()=>t4,MathFunction:()=>UQ,MathFraction:()=>uZ,MathDenominator:()=>c4,MathDegree:()=>s4,MathCurlyBrackets:()=>JQ,MathAngledBrackets:()=>KQ,Math:()=>xZ,LineRuleType:()=>k2,LineNumberRestartFormat:()=>nQ,LevelSuffix:()=>DJ,LevelOverride:()=>u9,LevelFormat:()=>i0,LevelForOverride:()=>$J,LevelBase:()=>V6,Level:()=>h9,LeaderType:()=>FZ,LastRenderedPageBreak:()=>KZ,InternalHyperlink:()=>y4,InsertedTextRun:()=>XQ,InsertedTableRow:()=>U9,InsertedTableCell:()=>Y9,InitializableXmlComponent:()=>h8,ImportedXmlComponent:()=>kB,ImportedRootElementAttributes:()=>$B,ImageRun:()=>$Y,IgnoreIfEmptyXmlComponent:()=>R2,HyperlinkType:()=>AZ,HpsMeasureElement:()=>E1,HorizontalPositionRelativeFrom:()=>B4,HorizontalPositionAlign:()=>MG,HighlightColor:()=>kG,HeightRule:()=>gQ,HeadingLevel:()=>OZ,HeaderWrapper:()=>_9,HeaderFooterType:()=>z8,HeaderFooterReferenceType:()=>D2,Header:()=>IK,GridSpan:()=>X9,FrameWrap:()=>fZ,FrameAnchorType:()=>gZ,FootnoteReferenceRun:()=>FK,FootnoteReferenceElement:()=>GZ,FootnoteReference:()=>o9,FooterWrapper:()=>f9,Footer:()=>OK,FootNotes:()=>x9,FootNoteReferenceRunAttributes:()=>s9,FileChild:()=>F1,File:()=>VK,ExternalHyperlink:()=>o8,Endnotes:()=>g9,EndnoteReferenceRunAttributes:()=>t9,EndnoteReferenceRun:()=>HK,EndnoteReference:()=>T4,EndnoteIdReference:()=>e9,EmptyElement:()=>S0,EmphasisMarkType:()=>a8,EMPTY_OBJECT:()=>KB,DropCapType:()=>yZ,Drawing:()=>c1,DocumentGridType:()=>iQ,DocumentDefaults:()=>p9,DocumentBackgroundAttributes:()=>S9,DocumentBackground:()=>b9,DocumentAttributes:()=>H1,DocumentAttributeNamespaces:()=>v1,Document:()=>VK,DeletedTextRun:()=>OQ,DeletedTableRow:()=>G9,DeletedTableCell:()=>Z9,DayShort:()=>nY,DayLong:()=>tY,ContinuationSeparator:()=>ZZ,ConcreteNumbering:()=>T8,ConcreteHyperlink:()=>m2,CommentsExtended:()=>E4,Comments:()=>z4,CommentReference:()=>mY,CommentRangeStart:()=>dY,CommentRangeEnd:()=>cY,Comment:()=>A8,ColumnBreak:()=>IZ,Column:()=>ZJ,CheckBoxUtil:()=>B5,CheckBoxSymbolElement:()=>S1,CheckBox:()=>WK,CharacterSet:()=>kZ,CellMergeAttributes:()=>Q9,CellMerge:()=>J9,CarriageReturn:()=>JZ,BuilderElement:()=>X0,BorderStyle:()=>d1,Border:()=>xB,BookmarkStart:()=>f4,BookmarkEnd:()=>x4,Bookmark:()=>g4,Body:()=>$9,BaseXmlComponent:()=>Y1,Attributes:()=>C0,AnnotationReference:()=>UZ,AlignmentType:()=>c0,AbstractNumbering:()=>E8});var{create:YU,defineProperty:QB,getOwnPropertyDescriptor:ZU,getOwnPropertyNames:QU,getPrototypeOf:JU}=Object,KU=Object.prototype.hasOwnProperty,JB=(B,U)=>()=>(B&&(U=B(B=0)),U),R0=(B,U)=>()=>(U||(B((U={exports:{}}).exports,U),B=null),U.exports),VU=(B,U,G,Y)=>{if(U&&typeof U==="object"||typeof U==="function"){for(var Q=QU(U),K=0,Z=Q.length,J;KU[M]).bind(null,J),enumerable:!(Y=ZU(U,J))||Y.enumerable})}return B},C8=(B,U,G)=>(G=B!=null?YU(JU(B)):{},VU(U||!B||!B.__esModule?QB(G,"default",{value:B,enumerable:!0}):G,B)),N1=((B)=>__require)(function(B){return __require.apply(this,arguments)});function G1(B){return G1=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(U){return typeof U}:function(U){return U&&typeof Symbol=="function"&&U.constructor===Symbol&&U!==Symbol.prototype?"symbol":typeof U},G1(B)}function qU(B,U){if(G1(B)!="object"||!B)return B;var G=B[Symbol.toPrimitive];if(G!==void 0){var Y=G.call(B,U||"default");if(G1(Y)!="object")return Y;throw TypeError("@@toPrimitive must return a primitive value.")}return(U==="string"?String:Number)(B)}function MU(B){var U=qU(B,"string");return G1(U)=="symbol"?U:U+""}function e(B,U,G){return(U=MU(U))in B?Object.defineProperty(B,U,{value:G,enumerable:!0,configurable:!0,writable:!0}):B[U]=G,B}var Y1=class{constructor(B){e(this,"rootKey",void 0),this.rootKey=B}},KB=Object.seal({}),t=class extends Y1{constructor(B){super(B);e(this,"root",void 0),this.root=[]}prepForXml(B){var U;B.stack.push(this);let G=this.root.map((Y)=>{if(Y instanceof Y1)return Y.prepForXml(B);return Y}).filter((Y)=>Y!==void 0);return B.stack.pop(),{[this.rootKey]:G.length?G.length===1&&((U=G[0])===null||U===void 0?void 0:U._attr)?G[0]:G:KB}}addChildElement(B){return this.root.push(B),this}},R2=class extends t{constructor(B,U){super(B);e(this,"includeIfEmpty",void 0),this.includeIfEmpty=U}prepForXml(B){let U=super.prepForXml(B);if(this.includeIfEmpty)return U;if(U&&(typeof U[this.rootKey]!=="object"||Object.keys(U[this.rootKey]).length))return U}};function u6(B,U){var G=Object.keys(B);if(Object.getOwnPropertySymbols){var Y=Object.getOwnPropertySymbols(B);U&&(Y=Y.filter(function(Q){return Object.getOwnPropertyDescriptor(B,Q).enumerable})),G.push.apply(G,Y)}return G}function L0(B){for(var U=1;U{if(Y!==void 0){let Q=this.xmlKeys&&this.xmlKeys[G]||G;U[Q]=Y}}),{_attr:U}}},k8=class extends Y1{constructor(B){super("_attr");e(this,"root",void 0),this.root=B}prepForXml(B){return{_attr:Object.values(this.root).filter(({value:U})=>U!==void 0).reduce((U,{key:G,value:Y})=>L0(L0({},U),{},{[G]:Y}),{})}}},C0=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val",color:"w:color",fill:"w:fill",space:"w:space",sz:"w:sz",type:"w:type",rsidR:"w:rsidR",rsidRPr:"w:rsidRPr",rsidSect:"w:rsidSect",w:"w:w",h:"w:h",top:"w:top",right:"w:right",bottom:"w:bottom",left:"w:left",header:"w:header",footer:"w:footer",gutter:"w:gutter",linePitch:"w:linePitch",pos:"w:pos"})}},$8=R0((B,U)=>{var G=typeof Reflect==="object"?Reflect:null,Y=G&&typeof G.apply==="function"?G.apply:function($,x,N){return Function.prototype.apply.call($,x,N)},Q;if(G&&typeof G.ownKeys==="function")Q=G.ownKeys;else if(Object.getOwnPropertySymbols)Q=function($){return Object.getOwnPropertyNames($).concat(Object.getOwnPropertySymbols($))};else Q=function($){return Object.getOwnPropertyNames($)};function K(X){if(console&&console.warn)console.warn(X)}var Z=Number.isNaN||function($){return $!==$};function J(){J.init.call(this)}U.exports=J,U.exports.once=v,J.EventEmitter=J,J.prototype._events=void 0,J.prototype._eventsCount=0,J.prototype._maxListeners=void 0;var M=10;function W(X){if(typeof X!=="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof X)}Object.defineProperty(J,"defaultMaxListeners",{enumerable:!0,get:function(){return M},set:function(X){if(typeof X!=="number"||X<0||Z(X))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+X+".");M=X}}),J.init=function(){if(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)this._events=Object.create(null),this._eventsCount=0;this._maxListeners=this._maxListeners||void 0},J.prototype.setMaxListeners=function($){if(typeof $!=="number"||$<0||Z($))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+$+".");return this._maxListeners=$,this};function I(X){if(X._maxListeners===void 0)return J.defaultMaxListeners;return X._maxListeners}J.prototype.getMaxListeners=function(){return I(this)},J.prototype.emit=function($){var x=[];for(var N=1;N0)b=x[0];if(b instanceof Error)throw b;var c=Error("Unhandled error."+(b?" ("+b.message+")":""));throw c.context=b,c}var T=U0[$];if(T===void 0)return!1;if(typeof T==="function")Y(T,this,x);else{var m=T.length,B0=E(T,m);for(var N=0;N0&&b.length>a&&!b.warned){b.warned=!0;var c=Error("Possible EventEmitter memory leak detected. "+b.length+" "+String($)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=X,c.type=$,c.count=b.length,K(c)}}return X}J.prototype.addListener=function($,x){return F(this,$,x,!1)},J.prototype.on=J.prototype.addListener,J.prototype.prependListener=function($,x){return F(this,$,x,!0)};function D(){if(!this.fired){if(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function w(X,$,x){var N={fired:!1,wrapFn:void 0,target:X,type:$,listener:x},a=D.bind(N);return a.listener=x,N.wrapFn=a,a}J.prototype.once=function($,x){return W(x),this.on($,w(this,$,x)),this},J.prototype.prependOnceListener=function($,x){return W(x),this.prependListener($,w(this,$,x)),this},J.prototype.removeListener=function($,x){var N,a,U0,b,c;if(W(x),a=this._events,a===void 0)return this;if(N=a[$],N===void 0)return this;if(N===x||N.listener===x){if(--this._eventsCount===0)this._events=Object.create(null);else if(delete a[$],a.removeListener)this.emit("removeListener",$,N.listener||x)}else if(typeof N!=="function"){U0=-1;for(b=N.length-1;b>=0;b--)if(N[b]===x||N[b].listener===x){c=N[b].listener,U0=b;break}if(U0<0)return this;if(U0===0)N.shift();else C(N,U0);if(N.length===1)a[$]=N[0];if(a.removeListener!==void 0)this.emit("removeListener",$,c||x)}return this},J.prototype.off=J.prototype.removeListener,J.prototype.removeAllListeners=function($){var x,N=this._events,a;if(N===void 0)return this;if(N.removeListener===void 0){if(arguments.length===0)this._events=Object.create(null),this._eventsCount=0;else if(N[$]!==void 0)if(--this._eventsCount===0)this._events=Object.create(null);else delete N[$];return this}if(arguments.length===0){var U0=Object.keys(N),b;for(a=0;a=0;a--)this.removeListener($,x[a]);return this};function P(X,$,x){var N=X._events;if(N===void 0)return[];var a=N[$];if(a===void 0)return[];if(typeof a==="function")return x?[a.listener||a]:[a];return x?j(a):E(a,a.length)}J.prototype.listeners=function($){return P(this,$,!0)},J.prototype.rawListeners=function($){return P(this,$,!1)},J.listenerCount=function(X,$){if(typeof X.listenerCount==="function")return X.listenerCount($);else return A.call(X,$)},J.prototype.listenerCount=A;function A(X){var $=this._events;if($!==void 0){var x=$[X];if(typeof x==="function")return 1;else if(x!==void 0)return x.length}return 0}J.prototype.eventNames=function(){return this._eventsCount>0?Q(this._events):[]};function E(X,$){var x=Array($);for(var N=0;N<$;++N)x[N]=X[N];return x}function C(X,$){for(;$+1{if(typeof Object.create==="function")U.exports=function(Y,Q){if(Q)Y.super_=Q,Y.prototype=Object.create(Q.prototype,{constructor:{value:Y,enumerable:!1,writable:!0,configurable:!0}})};else U.exports=function(Y,Q){if(Q){Y.super_=Q;var K=function(){};K.prototype=Q.prototype,Y.prototype=new K,Y.prototype.constructor=Y}}}),v0,d2=JB(()=>{v0=globalThis||self});function XU(B){return B&&B.__esModule&&Object.prototype.hasOwnProperty.call(B,"default")?B.default:B}function I8(){throw Error("setTimeout has not been defined")}function O8(){throw Error("clearTimeout has not been defined")}function VB(B){if(n0===setTimeout)return setTimeout(B,0);if((n0===I8||!n0)&&setTimeout)return n0=setTimeout,setTimeout(B,0);try{return n0(B,0)}catch(U){try{return n0.call(null,B,0)}catch(G){return n0.call(this,B,0)}}}function RU(B){if(s0===clearTimeout)return clearTimeout(B);if((s0===O8||!s0)&&clearTimeout)return s0=clearTimeout,clearTimeout(B);try{return s0(B)}catch(U){try{return s0.call(null,B)}catch(G){return s0.call(this,B)}}}function LU(){if(!T2||!E2)return;if(T2=!1,E2.length)o0=E2.concat(o0);else B1=-1;if(o0.length)qB()}function qB(){if(T2)return;var B=VB(LU);T2=!0;var U=o0.length;while(U){E2=o0,o0=[];while(++B1{Q8={exports:{}},j0=Q8.exports={},function(){try{if(typeof setTimeout==="function")n0=setTimeout;else n0=I8}catch(B){n0=I8}try{if(typeof clearTimeout==="function")s0=clearTimeout;else s0=O8}catch(B){s0=O8}}(),o0=[],T2=!1,B1=-1,j0.nextTick=function(B){var U=Array(arguments.length-1);if(arguments.length>1)for(var G=1;G{U.exports=$8().EventEmitter}),IU=R0((B)=>{B.byteLength=M,B.toByteArray=I,B.fromByteArray=w;var U=[],G=[],Y=typeof Uint8Array<"u"?Uint8Array:Array,Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var K=0,Z=Q.length;K0)throw Error("Invalid string. Length must be a multiple of 4");var E=P.indexOf("=");if(E===-1)E=A;var C=E===A?0:4-E%4;return[E,C]}function M(P){var A=J(P),E=A[0],C=A[1];return(E+C)*3/4-C}function W(P,A,E){return(A+E)*3/4-E}function I(P){var A,E=J(P),C=E[0],j=E[1],v=new Y(W(P,C,j)),S=0,H=j>0?C-4:C,X;for(X=0;X>16&255,v[S++]=A>>8&255,v[S++]=A&255;if(j===2)A=G[P.charCodeAt(X)]<<2|G[P.charCodeAt(X+1)]>>4,v[S++]=A&255;if(j===1)A=G[P.charCodeAt(X)]<<10|G[P.charCodeAt(X+1)]<<4|G[P.charCodeAt(X+2)]>>2,v[S++]=A>>8&255,v[S++]=A&255;return v}function F(P){return U[P>>18&63]+U[P>>12&63]+U[P>>6&63]+U[P&63]}function D(P,A,E){var C,j=[];for(var v=A;vH?H:S+v));if(C===1)A=P[E-1],j.push(U[A>>2]+U[A<<4&63]+"==");else if(C===2)A=(P[E-2]<<8)+P[E-1],j.push(U[A>>10]+U[A>>4&63]+U[A<<2&63]+"=");return j.join("")}}),OU=R0((B)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */B.read=function(U,G,Y,Q,K){var Z,J,M=K*8-Q-1,W=(1<>1,F=-7,D=Y?K-1:0,w=Y?-1:1,P=U[G+D];D+=w,Z=P&(1<<-F)-1,P>>=-F,F+=M;for(;F>0;Z=Z*256+U[G+D],D+=w,F-=8);J=Z&(1<<-F)-1,Z>>=-F,F+=Q;for(;F>0;J=J*256+U[G+D],D+=w,F-=8);if(Z===0)Z=1-I;else if(Z===W)return J?NaN:(P?-1:1)*(1/0);else J=J+Math.pow(2,Q),Z=Z-I;return(P?-1:1)*J*Math.pow(2,Z-Q)},B.write=function(U,G,Y,Q,K,Z){var J,M,W,I=Z*8-K-1,F=(1<>1,w=K===23?Math.pow(2,-24)-Math.pow(2,-77):0,P=Q?0:Z-1,A=Q?1:-1,E=G<0||G===0&&1/G<0?1:0;if(G=Math.abs(G),isNaN(G)||G===1/0)M=isNaN(G)?1:0,J=F;else{if(J=Math.floor(Math.log(G)/Math.LN2),G*(W=Math.pow(2,-J))<1)J--,W*=2;if(J+D>=1)G+=w/W;else G+=w*Math.pow(2,1-D);if(G*W>=2)J++,W/=2;if(J+D>=F)M=0,J=F;else if(J+D>=1)M=(G*W-1)*Math.pow(2,K),J=J+D;else M=G*Math.pow(2,D-1)*Math.pow(2,K),J=0}for(;K>=8;U[Y+P]=M&255,P+=A,M/=256,K-=8);J=J<0;U[Y+P]=J&255,P+=A,J/=256,I-=8);U[Y+P-A]|=E*128}});/*! -* The buffer module from node.js, for the browser. -* -* @author Feross Aboukhadijeh -* @license MIT -*/var g1=R0((B)=>{var U=IU(),G=OU(),Y=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;B.Buffer=J,B.SlowBuffer=j,B.INSPECT_MAX_BYTES=50;var Q=2147483647;if(B.kMaxLength=Q,J.TYPED_ARRAY_SUPPORT=K(),!J.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function K(){try{var k=new Uint8Array(1),V={foo:function(){return 42}};return Object.setPrototypeOf(V,Uint8Array.prototype),Object.setPrototypeOf(k,V),k.foo()===42}catch(q){return!1}}Object.defineProperty(J.prototype,"parent",{enumerable:!0,get:function(){if(!J.isBuffer(this))return;return this.buffer}}),Object.defineProperty(J.prototype,"offset",{enumerable:!0,get:function(){if(!J.isBuffer(this))return;return this.byteOffset}});function Z(k){if(k>Q)throw RangeError('The value "'+k+'" is invalid for option "size"');var V=new Uint8Array(k);return Object.setPrototypeOf(V,J.prototype),V}function J(k,V,q){if(typeof k==="number"){if(typeof V==="string")throw TypeError('The "string" argument must be of type string. Received type number');return F(k)}return M(k,V,q)}J.poolSize=8192;function M(k,V,q){if(typeof k==="string")return D(k,V);if(ArrayBuffer.isView(k))return P(k);if(k==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k);if(f(k,ArrayBuffer)||k&&f(k.buffer,ArrayBuffer))return A(k,V,q);if(typeof SharedArrayBuffer<"u"&&(f(k,SharedArrayBuffer)||k&&f(k.buffer,SharedArrayBuffer)))return A(k,V,q);if(typeof k==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var O=k.valueOf&&k.valueOf();if(O!=null&&O!==k)return J.from(O,V,q);var _=E(k);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof k[Symbol.toPrimitive]==="function")return J.from(k[Symbol.toPrimitive]("string"),V,q);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k)}J.from=function(k,V,q){return M(k,V,q)},Object.setPrototypeOf(J.prototype,Uint8Array.prototype),Object.setPrototypeOf(J,Uint8Array);function W(k){if(typeof k!=="number")throw TypeError('"size" argument must be of type number');else if(k<0)throw RangeError('The value "'+k+'" is invalid for option "size"')}function I(k,V,q){if(W(k),k<=0)return Z(k);if(V!==void 0)return typeof q==="string"?Z(k).fill(V,q):Z(k).fill(V);return Z(k)}J.alloc=function(k,V,q){return I(k,V,q)};function F(k){return W(k),Z(k<0?0:C(k)|0)}J.allocUnsafe=function(k){return F(k)},J.allocUnsafeSlow=function(k){return F(k)};function D(k,V){if(typeof V!=="string"||V==="")V="utf8";if(!J.isEncoding(V))throw TypeError("Unknown encoding: "+V);var q=v(k,V)|0,O=Z(q),_=O.write(k,V);if(_!==q)O=O.slice(0,_);return O}function w(k){var V=k.length<0?0:C(k.length)|0,q=Z(V);for(var O=0;O=Q)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Q.toString(16)+" bytes");return k|0}function j(k){if(+k!=k)k=0;return J.alloc(+k)}J.isBuffer=function(V){return V!=null&&V._isBuffer===!0&&V!==J.prototype},J.compare=function(V,q){if(f(V,Uint8Array))V=J.from(V,V.offset,V.byteLength);if(f(q,Uint8Array))q=J.from(q,q.offset,q.byteLength);if(!J.isBuffer(V)||!J.isBuffer(q))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(V===q)return 0;var O=V.length,_=q.length;for(var l=0,d=Math.min(O,_);l_.length)J.from(d).copy(_,l);else Uint8Array.prototype.set.call(_,d,l);else if(!J.isBuffer(d))throw TypeError('"list" argument must be an Array of Buffers');else d.copy(_,l);l+=d.length}return _};function v(k,V){if(J.isBuffer(k))return k.length;if(ArrayBuffer.isView(k)||f(k,ArrayBuffer))return k.byteLength;if(typeof k!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof k);var q=k.length,O=arguments.length>2&&arguments[2]===!0;if(!O&&q===0)return 0;var _=!1;for(;;)switch(V){case"ascii":case"latin1":case"binary":return q;case"utf8":case"utf-8":return L(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q*2;case"hex":return q>>>1;case"base64":return Z0(k).length;default:if(_)return O?-1:L(k).length;V=(""+V).toLowerCase(),_=!0}}J.byteLength=v;function S(k,V,q){var O=!1;if(V===void 0||V<0)V=0;if(V>this.length)return"";if(q===void 0||q>this.length)q=this.length;if(q<=0)return"";if(q>>>=0,V>>>=0,q<=V)return"";if(!k)k="utf8";while(!0)switch(k){case"hex":return s(this,V,q);case"utf8":case"utf-8":return T(this,V,q);case"ascii":return i(this,V,q);case"latin1":case"binary":return V0(this,V,q);case"base64":return c(this,V,q);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G0(this,V,q);default:if(O)throw TypeError("Unknown encoding: "+k);k=(k+"").toLowerCase(),O=!0}}J.prototype._isBuffer=!0;function H(k,V,q){var O=k[V];k[V]=k[q],k[q]=O}if(J.prototype.swap16=function(){var V=this.length;if(V%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var q=0;qq)V+=" ... ";return""},Y)J.prototype[Y]=J.prototype.inspect;J.prototype.compare=function(V,q,O,_,l){if(f(V,Uint8Array))V=J.from(V,V.offset,V.byteLength);if(!J.isBuffer(V))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof V);if(q===void 0)q=0;if(O===void 0)O=V?V.length:0;if(_===void 0)_=0;if(l===void 0)l=this.length;if(q<0||O>V.length||_<0||l>this.length)throw RangeError("out of range index");if(_>=l&&q>=O)return 0;if(_>=l)return-1;if(q>=O)return 1;if(q>>>=0,O>>>=0,_>>>=0,l>>>=0,this===V)return 0;var d=l-_,Q0=O-q,q0=Math.min(d,Q0),K0=this.slice(_,l),I0=V.slice(q,O);for(var H0=0;H02147483647)q=2147483647;else if(q<-2147483648)q=-2147483648;if(q=+q,R(q))q=_?0:k.length-1;if(q<0)q=k.length+q;if(q>=k.length)if(_)return-1;else q=k.length-1;else if(q<0)if(_)q=0;else return-1;if(typeof V==="string")V=J.from(V,O);if(J.isBuffer(V)){if(V.length===0)return-1;return $(k,V,q,O,_)}else if(typeof V==="number"){if(V=V&255,typeof Uint8Array.prototype.indexOf==="function")if(_)return Uint8Array.prototype.indexOf.call(k,V,q);else return Uint8Array.prototype.lastIndexOf.call(k,V,q);return $(k,[V],q,O,_)}throw TypeError("val must be string, number or Buffer")}function $(k,V,q,O,_){var l=1,d=k.length,Q0=V.length;if(O!==void 0){if(O=String(O).toLowerCase(),O==="ucs2"||O==="ucs-2"||O==="utf16le"||O==="utf-16le"){if(k.length<2||V.length<2)return-1;l=2,d/=2,Q0/=2,q/=2}}function q0(k0,L2){if(l===1)return k0[L2];else return k0.readUInt16BE(L2*l)}var K0;if(_){var I0=-1;for(K0=q;K0d)q=d-Q0;for(K0=q;K0>=0;K0--){var H0=!0;for(var W0=0;W0_)O=_;var l=V.length;if(O>l/2)O=l/2;for(var d=0;d>>0,isFinite(O)){if(O=O>>>0,_===void 0)_="utf8"}else _=O,O=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var l=this.length-q;if(O===void 0||O>l)O=l;if(V.length>0&&(O<0||q<0)||q>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!_)_="utf8";var d=!1;for(;;)switch(_){case"hex":return x(this,V,q,O);case"utf8":case"utf-8":return N(this,V,q,O);case"ascii":case"latin1":case"binary":return a(this,V,q,O);case"base64":return U0(this,V,q,O);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b(this,V,q,O);default:if(d)throw TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),d=!0}},J.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function c(k,V,q){if(V===0&&q===k.length)return U.fromByteArray(k);else return U.fromByteArray(k.slice(V,q))}function T(k,V,q){q=Math.min(k.length,q);var O=[],_=V;while(_239?4:l>223?3:l>191?2:1;if(_+Q0<=q){var q0,K0,I0,H0;switch(Q0){case 1:if(l<128)d=l;break;case 2:if(q0=k[_+1],(q0&192)===128){if(H0=(l&31)<<6|q0&63,H0>127)d=H0}break;case 3:if(q0=k[_+1],K0=k[_+2],(q0&192)===128&&(K0&192)===128){if(H0=(l&15)<<12|(q0&63)<<6|K0&63,H0>2047&&(H0<55296||H0>57343))d=H0}break;case 4:if(q0=k[_+1],K0=k[_+2],I0=k[_+3],(q0&192)===128&&(K0&192)===128&&(I0&192)===128){if(H0=(l&15)<<18|(q0&63)<<12|(K0&63)<<6|I0&63,H0>65535&&H0<1114112)d=H0}}}if(d===null)d=65533,Q0=1;else if(d>65535)d-=65536,O.push(d>>>10&1023|55296),d=56320|d&1023;O.push(d),_+=Q0}return B0(O)}var m=4096;function B0(k){var V=k.length;if(V<=m)return String.fromCharCode.apply(String,k);var q="",O=0;while(OO)q=O;var _="";for(var l=V;lO)V=O;if(q<0){if(q+=O,q<0)q=0}else if(q>O)q=O;if(qq)throw RangeError("Trying to access beyond buffer length")}J.prototype.readUintLE=J.prototype.readUIntLE=function(V,q,O){if(V=V>>>0,q=q>>>0,!O)r(V,q,this.length);var _=this[V],l=1,d=0;while(++d>>0,q=q>>>0,!O)r(V,q,this.length);var _=this[V+--q],l=1;while(q>0&&(l*=256))_+=this[V+--q]*l;return _},J.prototype.readUint8=J.prototype.readUInt8=function(V,q){if(V=V>>>0,!q)r(V,1,this.length);return this[V]},J.prototype.readUint16LE=J.prototype.readUInt16LE=function(V,q){if(V=V>>>0,!q)r(V,2,this.length);return this[V]|this[V+1]<<8},J.prototype.readUint16BE=J.prototype.readUInt16BE=function(V,q){if(V=V>>>0,!q)r(V,2,this.length);return this[V]<<8|this[V+1]},J.prototype.readUint32LE=J.prototype.readUInt32LE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return(this[V]|this[V+1]<<8|this[V+2]<<16)+this[V+3]*16777216},J.prototype.readUint32BE=J.prototype.readUInt32BE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return this[V]*16777216+(this[V+1]<<16|this[V+2]<<8|this[V+3])},J.prototype.readIntLE=function(V,q,O){if(V=V>>>0,q=q>>>0,!O)r(V,q,this.length);var _=this[V],l=1,d=0;while(++d=l)_-=Math.pow(2,8*q);return _},J.prototype.readIntBE=function(V,q,O){if(V=V>>>0,q=q>>>0,!O)r(V,q,this.length);var _=q,l=1,d=this[V+--_];while(_>0&&(l*=256))d+=this[V+--_]*l;if(l*=128,d>=l)d-=Math.pow(2,8*q);return d},J.prototype.readInt8=function(V,q){if(V=V>>>0,!q)r(V,1,this.length);if(!(this[V]&128))return this[V];return(255-this[V]+1)*-1},J.prototype.readInt16LE=function(V,q){if(V=V>>>0,!q)r(V,2,this.length);var O=this[V]|this[V+1]<<8;return O&32768?O|4294901760:O},J.prototype.readInt16BE=function(V,q){if(V=V>>>0,!q)r(V,2,this.length);var O=this[V+1]|this[V]<<8;return O&32768?O|4294901760:O},J.prototype.readInt32LE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return this[V]|this[V+1]<<8|this[V+2]<<16|this[V+3]<<24},J.prototype.readInt32BE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return this[V]<<24|this[V+1]<<16|this[V+2]<<8|this[V+3]},J.prototype.readFloatLE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return G.read(this,V,!0,23,4)},J.prototype.readFloatBE=function(V,q){if(V=V>>>0,!q)r(V,4,this.length);return G.read(this,V,!1,23,4)},J.prototype.readDoubleLE=function(V,q){if(V=V>>>0,!q)r(V,8,this.length);return G.read(this,V,!0,52,8)},J.prototype.readDoubleBE=function(V,q){if(V=V>>>0,!q)r(V,8,this.length);return G.read(this,V,!1,52,8)};function y(k,V,q,O,_,l){if(!J.isBuffer(k))throw TypeError('"buffer" argument must be a Buffer instance');if(V>_||Vk.length)throw RangeError("Index out of range")}J.prototype.writeUintLE=J.prototype.writeUIntLE=function(V,q,O,_){if(V=+V,q=q>>>0,O=O>>>0,!_){var l=Math.pow(2,8*O)-1;y(this,V,q,O,l,0)}var d=1,Q0=0;this[q]=V&255;while(++Q0>>0,O=O>>>0,!_){var l=Math.pow(2,8*O)-1;y(this,V,q,O,l,0)}var d=O-1,Q0=1;this[q+d]=V&255;while(--d>=0&&(Q0*=256))this[q+d]=V/Q0&255;return q+O},J.prototype.writeUint8=J.prototype.writeUInt8=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,1,255,0);return this[q]=V&255,q+1},J.prototype.writeUint16LE=J.prototype.writeUInt16LE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,2,65535,0);return this[q]=V&255,this[q+1]=V>>>8,q+2},J.prototype.writeUint16BE=J.prototype.writeUInt16BE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,2,65535,0);return this[q]=V>>>8,this[q+1]=V&255,q+2},J.prototype.writeUint32LE=J.prototype.writeUInt32LE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,4,4294967295,0);return this[q+3]=V>>>24,this[q+2]=V>>>16,this[q+1]=V>>>8,this[q]=V&255,q+4},J.prototype.writeUint32BE=J.prototype.writeUInt32BE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,4,4294967295,0);return this[q]=V>>>24,this[q+1]=V>>>16,this[q+2]=V>>>8,this[q+3]=V&255,q+4},J.prototype.writeIntLE=function(V,q,O,_){if(V=+V,q=q>>>0,!_){var l=Math.pow(2,8*O-1);y(this,V,q,O,l-1,-l)}var d=0,Q0=1,q0=0;this[q]=V&255;while(++d>0)-q0&255}return q+O},J.prototype.writeIntBE=function(V,q,O,_){if(V=+V,q=q>>>0,!_){var l=Math.pow(2,8*O-1);y(this,V,q,O,l-1,-l)}var d=O-1,Q0=1,q0=0;this[q+d]=V&255;while(--d>=0&&(Q0*=256)){if(V<0&&q0===0&&this[q+d+1]!==0)q0=1;this[q+d]=(V/Q0>>0)-q0&255}return q+O},J.prototype.writeInt8=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,1,127,-128);if(V<0)V=255+V+1;return this[q]=V&255,q+1},J.prototype.writeInt16LE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,2,32767,-32768);return this[q]=V&255,this[q+1]=V>>>8,q+2},J.prototype.writeInt16BE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,2,32767,-32768);return this[q]=V>>>8,this[q+1]=V&255,q+2},J.prototype.writeInt32LE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,4,2147483647,-2147483648);return this[q]=V&255,this[q+1]=V>>>8,this[q+2]=V>>>16,this[q+3]=V>>>24,q+4},J.prototype.writeInt32BE=function(V,q,O){if(V=+V,q=q>>>0,!O)y(this,V,q,4,2147483647,-2147483648);if(V<0)V=4294967295+V+1;return this[q]=V>>>24,this[q+1]=V>>>16,this[q+2]=V>>>8,this[q+3]=V&255,q+4};function n(k,V,q,O,_,l){if(q+O>k.length)throw RangeError("Index out of range");if(q<0)throw RangeError("Index out of range")}function o(k,V,q,O,_){if(V=+V,q=q>>>0,!_)n(k,V,q,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return G.write(k,V,q,O,23,4),q+4}J.prototype.writeFloatLE=function(V,q,O){return o(this,V,q,!0,O)},J.prototype.writeFloatBE=function(V,q,O){return o(this,V,q,!1,O)};function Y0(k,V,q,O,_){if(V=+V,q=q>>>0,!_)n(k,V,q,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return G.write(k,V,q,O,52,8),q+8}J.prototype.writeDoubleLE=function(V,q,O){return Y0(this,V,q,!0,O)},J.prototype.writeDoubleBE=function(V,q,O){return Y0(this,V,q,!1,O)},J.prototype.copy=function(V,q,O,_){if(!J.isBuffer(V))throw TypeError("argument should be a Buffer");if(!O)O=0;if(!_&&_!==0)_=this.length;if(q>=V.length)q=V.length;if(!q)q=0;if(_>0&&_=this.length)throw RangeError("Index out of range");if(_<0)throw RangeError("sourceEnd out of bounds");if(_>this.length)_=this.length;if(V.length-q<_-O)_=V.length-q+O;var l=_-O;if(this===V&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(q,O,_);else Uint8Array.prototype.set.call(V,this.subarray(O,_),q);return l},J.prototype.fill=function(V,q,O,_){if(typeof V==="string"){if(typeof q==="string")_=q,q=0,O=this.length;else if(typeof O==="string")_=O,O=this.length;if(_!==void 0&&typeof _!=="string")throw TypeError("encoding must be a string");if(typeof _==="string"&&!J.isEncoding(_))throw TypeError("Unknown encoding: "+_);if(V.length===1){var l=V.charCodeAt(0);if(_==="utf8"&&l<128||_==="latin1")V=l}}else if(typeof V==="number")V=V&255;else if(typeof V==="boolean")V=Number(V);if(q<0||this.length>>0,O=O===void 0?this.length:O>>>0,!V)V=0;var d;if(typeof V==="number")for(d=q;d55295&&q<57344){if(!_){if(q>56319){if((V-=3)>-1)l.push(239,191,189);continue}else if(d+1===O){if((V-=3)>-1)l.push(239,191,189);continue}_=q;continue}if(q<56320){if((V-=3)>-1)l.push(239,191,189);_=q;continue}q=(_-55296<<10|q-56320)+65536}else if(_){if((V-=3)>-1)l.push(239,191,189)}if(_=null,q<128){if((V-=1)<0)break;l.push(q)}else if(q<2048){if((V-=2)<0)break;l.push(q>>6|192,q&63|128)}else if(q<65536){if((V-=3)<0)break;l.push(q>>12|224,q>>6&63|128,q&63|128)}else if(q<1114112){if((V-=4)<0)break;l.push(q>>18|240,q>>12&63|128,q>>6&63|128,q&63|128)}else throw Error("Invalid code point")}return l}function u(k){var V=[];for(var q=0;q>8,_=q%256,l.push(_),l.push(O)}return l}function Z0(k){return U.toByteArray(z(k))}function g(k,V,q,O){for(var _=0;_=V.length||_>=k.length)break;V[_+q]=k[_]}return _}function f(k,V){return k instanceof V||k!=null&&k.constructor!=null&&k.constructor.name!=null&&k.constructor.name===V.name}function R(k){return k!==k}var p=function(){var k="0123456789abcdef",V=Array(256);for(var q=0;q<16;++q){var O=q*16;for(var _=0;_<16;++_)V[O+_]=k[q]+k[_]}return V}()}),XB=R0((B,U)=>{U.exports=function(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function")return!1;if(typeof Symbol.iterator==="symbol")return!0;var Y={},Q=Symbol("test"),K=Object(Q);if(typeof Q==="string")return!1;if(Object.prototype.toString.call(Q)!=="[object Symbol]")return!1;if(Object.prototype.toString.call(K)!=="[object Symbol]")return!1;var Z=42;Y[Q]=Z;for(var J in Y)return!1;if(typeof Object.keys==="function"&&Object.keys(Y).length!==0)return!1;if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(Y).length!==0)return!1;var M=Object.getOwnPropertySymbols(Y);if(M.length!==1||M[0]!==Q)return!1;if(!Object.prototype.propertyIsEnumerable.call(Y,Q))return!1;if(typeof Object.getOwnPropertyDescriptor==="function"){var W=Object.getOwnPropertyDescriptor(Y,Q);if(W.value!==Z||W.enumerable!==!0)return!1}return!0}}),S8=R0((B,U)=>{var G=XB();U.exports=function(){return G()&&!!Symbol.toStringTag}}),RB=R0((B,U)=>{U.exports=Object}),FU=R0((B,U)=>{U.exports=Error}),HU=R0((B,U)=>{U.exports=EvalError}),WU=R0((B,U)=>{U.exports=RangeError}),PU=R0((B,U)=>{U.exports=ReferenceError}),LB=R0((B,U)=>{U.exports=SyntaxError}),f1=R0((B,U)=>{U.exports=TypeError}),wU=R0((B,U)=>{U.exports=URIError}),AU=R0((B,U)=>{U.exports=Math.abs}),jU=R0((B,U)=>{U.exports=Math.floor}),NU=R0((B,U)=>{U.exports=Math.max}),zU=R0((B,U)=>{U.exports=Math.min}),EU=R0((B,U)=>{U.exports=Math.pow}),TU=R0((B,U)=>{U.exports=Math.round}),DU=R0((B,U)=>{U.exports=Number.isNaN||function(Y){return Y!==Y}}),CU=R0((B,U)=>{var G=DU();U.exports=function(Q){if(G(Q)||Q===0)return Q;return Q<0?-1:1}}),kU=R0((B,U)=>{U.exports=Object.getOwnPropertyDescriptor}),K1=R0((B,U)=>{var G=kU();if(G)try{G([],"length")}catch(Y){G=null}U.exports=G}),x1=R0((B,U)=>{var G=Object.defineProperty||!1;if(G)try{G({},"a",{value:1})}catch(Y){G=!1}U.exports=G}),$U=R0((B,U)=>{var G=typeof Symbol<"u"&&Symbol,Y=XB();U.exports=function(){if(typeof G!=="function")return!1;if(typeof Symbol!=="function")return!1;if(typeof G("foo")!=="symbol")return!1;if(typeof Symbol("bar")!=="symbol")return!1;return Y()}}),IB=R0((B,U)=>{U.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null}),OB=R0((B,U)=>{U.exports=RB().getPrototypeOf||null}),SU=R0((B,U)=>{var G="Function.prototype.bind called on incompatible ",Y=Object.prototype.toString,Q=Math.max,K="[object Function]",Z=function(I,F){var D=[];for(var w=0;w{var G=SU();U.exports=Function.prototype.bind||G}),b8=R0((B,U)=>{U.exports=Function.prototype.call}),v8=R0((B,U)=>{U.exports=Function.prototype.apply}),bU=R0((B,U)=>{U.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply}),FB=R0((B,U)=>{var G=V1(),Y=v8(),Q=b8();U.exports=bU()||G.call(Q,Y)}),y8=R0((B,U)=>{var G=V1(),Y=f1(),Q=b8(),K=FB();U.exports=function(J){if(J.length<1||typeof J[0]!=="function")throw new Y("a function is required");return K(G,Q,J)}}),vU=R0((B,U)=>{var G=y8(),Y=K1(),Q;try{Q=[].__proto__===Array.prototype}catch(M){if(!M||typeof M!=="object"||!("code"in M)||M.code!=="ERR_PROTO_ACCESS")throw M}var K=!!Q&&Y&&Y(Object.prototype,"__proto__"),Z=Object,J=Z.getPrototypeOf;U.exports=K&&typeof K.get==="function"?G([K.get]):typeof J==="function"?function(W){return J(W==null?W:Z(W))}:!1}),HB=R0((B,U)=>{var G=IB(),Y=OB(),Q=vU();U.exports=G?function(Z){return G(Z)}:Y?function(Z){if(!Z||typeof Z!=="object"&&typeof Z!=="function")throw TypeError("getProto: not an object");return Y(Z)}:Q?function(Z){return Q(Z)}:null}),yU=R0((B,U)=>{var G=Function.prototype.call,Y=Object.prototype.hasOwnProperty;U.exports=V1().call(G,Y)}),WB=R0((B,U)=>{var G,Y=RB(),Q=FU(),K=HU(),Z=WU(),J=PU(),M=LB(),W=f1(),I=wU(),F=AU(),D=jU(),w=NU(),P=zU(),A=EU(),E=TU(),C=CU(),j=Function,v=function(h){try{return j('"use strict"; return ('+h+").constructor;")()}catch(Z0){}},S=K1(),H=x1(),X=function(){throw new W},$=S?function(){try{return arguments.callee,X}catch(h){try{return S(arguments,"callee").get}catch(Z0){return X}}}():X,x=$U()(),N=HB(),a=OB(),U0=IB(),b=v8(),c=b8(),T={},m=typeof Uint8Array>"u"||!N?G:N(Uint8Array),B0={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?G:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?G:ArrayBuffer,"%ArrayIteratorPrototype%":x&&N?N([][Symbol.iterator]()):G,"%AsyncFromSyncIteratorPrototype%":G,"%AsyncFunction%":T,"%AsyncGenerator%":T,"%AsyncGeneratorFunction%":T,"%AsyncIteratorPrototype%":T,"%Atomics%":typeof Atomics>"u"?G:Atomics,"%BigInt%":typeof BigInt>"u"?G:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?G:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?G:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?G:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Q,"%eval%":eval,"%EvalError%":K,"%Float16Array%":typeof Float16Array>"u"?G:Float16Array,"%Float32Array%":typeof Float32Array>"u"?G:Float32Array,"%Float64Array%":typeof Float64Array>"u"?G:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?G:FinalizationRegistry,"%Function%":j,"%GeneratorFunction%":T,"%Int8Array%":typeof Int8Array>"u"?G:Int8Array,"%Int16Array%":typeof Int16Array>"u"?G:Int16Array,"%Int32Array%":typeof Int32Array>"u"?G:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":x&&N?N(N([][Symbol.iterator]())):G,"%JSON%":typeof JSON==="object"?JSON:G,"%Map%":typeof Map>"u"?G:Map,"%MapIteratorPrototype%":typeof Map>"u"||!x||!N?G:N(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Y,"%Object.getOwnPropertyDescriptor%":S,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?G:Promise,"%Proxy%":typeof Proxy>"u"?G:Proxy,"%RangeError%":Z,"%ReferenceError%":J,"%Reflect%":typeof Reflect>"u"?G:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?G:Set,"%SetIteratorPrototype%":typeof Set>"u"||!x||!N?G:N(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?G:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":x&&N?N(""[Symbol.iterator]()):G,"%Symbol%":x?Symbol:G,"%SyntaxError%":M,"%ThrowTypeError%":$,"%TypedArray%":m,"%TypeError%":W,"%Uint8Array%":typeof Uint8Array>"u"?G:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?G:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?G:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?G:Uint32Array,"%URIError%":I,"%WeakMap%":typeof WeakMap>"u"?G:WeakMap,"%WeakRef%":typeof WeakRef>"u"?G:WeakRef,"%WeakSet%":typeof WeakSet>"u"?G:WeakSet,"%Function.prototype.call%":c,"%Function.prototype.apply%":b,"%Object.defineProperty%":H,"%Object.getPrototypeOf%":a,"%Math.abs%":F,"%Math.floor%":D,"%Math.max%":w,"%Math.min%":P,"%Math.pow%":A,"%Math.round%":E,"%Math.sign%":C,"%Reflect.getPrototypeOf%":U0};if(N)try{null.error}catch(h){B0["%Error.prototype%"]=N(N(h))}var i=function h(Z0){var g;if(Z0==="%AsyncFunction%")g=v("async function () {}");else if(Z0==="%GeneratorFunction%")g=v("function* () {}");else if(Z0==="%AsyncGeneratorFunction%")g=v("async function* () {}");else if(Z0==="%AsyncGenerator%"){var f=h("%AsyncGeneratorFunction%");if(f)g=f.prototype}else if(Z0==="%AsyncIteratorPrototype%"){var R=h("%AsyncGenerator%");if(R&&N)g=N(R.prototype)}return B0[Z0]=g,g},V0={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},s=V1(),G0=yU(),r=s.call(c,Array.prototype.concat),y=s.call(b,Array.prototype.splice),n=s.call(c,String.prototype.replace),o=s.call(c,String.prototype.slice),Y0=s.call(c,RegExp.prototype.exec),O0=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,z=/\\(\\)?/g,L=function(Z0){var g=o(Z0,0,1),f=o(Z0,-1);if(g==="%"&&f!=="%")throw new M("invalid intrinsic syntax, expected closing `%`");else if(f==="%"&&g!=="%")throw new M("invalid intrinsic syntax, expected opening `%`");var R=[];return n(Z0,O0,function(p,k,V,q){R[R.length]=V?n(q,z,"$1"):k||p}),R},u=function(Z0,g){var f=Z0,R;if(G0(V0,f))R=V0[f],f="%"+R[0]+"%";if(G0(B0,f)){var p=B0[f];if(p===T)p=i(f);if(typeof p>"u"&&!g)throw new W("intrinsic "+Z0+" exists, but is not available. Please file an issue!");return{alias:R,name:f,value:p}}throw new M("intrinsic "+Z0+" does not exist!")};U.exports=function(Z0,g){if(typeof Z0!=="string"||Z0.length===0)throw new W("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof g!=="boolean")throw new W('"allowMissing" argument must be a boolean');if(Y0(/^%?[^%]*%?$/,Z0)===null)throw new M("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var f=L(Z0),R=f.length>0?f[0]:"",p=u("%"+R+"%",g),k=p.name,V=p.value,q=!1,O=p.alias;if(O)R=O[0],y(f,r([0,1],O));for(var _=1,l=!0;_=f.length){var K0=S(V,d);if(l=!!K0,l&&"get"in K0&&!("originalValue"in K0.get))V=K0.get;else V=V[d]}else l=G0(V,d),V=V[d];if(l&&!q)B0[k]=V}}return V}}),PB=R0((B,U)=>{var G=WB(),Y=y8(),Q=Y([G("%String.prototype.indexOf%")]);U.exports=function(Z,J){var M=G(Z,!!J);if(typeof M==="function"&&Q(Z,".prototype.")>-1)return Y([M]);return M}}),gU=R0((B,U)=>{var G=S8()(),Y=PB()("Object.prototype.toString"),Q=function(M){if(G&&M&&typeof M==="object"&&Symbol.toStringTag in M)return!1;return Y(M)==="[object Arguments]"},K=function(M){if(Q(M))return!0;return M!==null&&typeof M==="object"&&"length"in M&&typeof M.length==="number"&&M.length>=0&&Y(M)!=="[object Array]"&&"callee"in M&&Y(M.callee)==="[object Function]"},Z=function(){return Q(arguments)}();Q.isLegacyArguments=K,U.exports=Z?Q:K}),fU=R0((B,U)=>{var G=Object.prototype.toString,Y=Function.prototype.toString,Q=/^\s*(?:function)?\*/,K=S8()(),Z=Object.getPrototypeOf,J=function(){if(!K)return!1;try{return Function("return function*() {}")()}catch(W){}},M;U.exports=function(I){if(typeof I!=="function")return!1;if(Q.test(Y.call(I)))return!0;if(!K)return G.call(I)==="[object GeneratorFunction]";if(!Z)return!1;if(typeof M>"u"){var F=J();M=F?Z(F):!1}return Z(I)===M}}),xU=R0((B,U)=>{var G=Function.prototype.toString,Y=typeof Reflect==="object"&&Reflect!==null&&Reflect.apply,Q,K;if(typeof Y==="function"&&typeof Object.defineProperty==="function")try{Q=Object.defineProperty({},"length",{get:function(){throw K}}),K={},Y(function(){throw 42},null,Q)}catch(S){if(S!==K)Y=null}else Y=null;var Z=/^\s*class\b/,J=function(H){try{var X=G.call(H);return Z.test(X)}catch($){return!1}},M=function(H){try{if(J(H))return!1;return G.call(H),!0}catch(X){return!1}},W=Object.prototype.toString,I="[object Object]",F="[object Function]",D="[object GeneratorFunction]",w="[object HTMLAllCollection]",P="[object HTML document.all class]",A="[object HTMLCollection]",E=typeof Symbol==="function"&&!!Symbol.toStringTag,C=!(0 in[,]),j=function(){return!1};if(typeof document==="object"){var v=document.all;if(W.call(v)===W.call(document.all))j=function(H){if((C||!H)&&(typeof H>"u"||typeof H==="object"))try{var X=W.call(H);return(X===w||X===P||X===A||X===I)&&H("")==null}catch($){}return!1}}U.exports=Y?function(H){if(j(H))return!0;if(!H)return!1;if(typeof H!=="function"&&typeof H!=="object")return!1;try{Y(H,null,Q)}catch(X){if(X!==K)return!1}return!J(H)&&M(H)}:function(H){if(j(H))return!0;if(!H)return!1;if(typeof H!=="function"&&typeof H!=="object")return!1;if(E)return M(H);if(J(H))return!1;var X=W.call(H);if(X!==F&&X!==D&&!/^\[object HTML/.test(X))return!1;return M(H)}}),_U=R0((B,U)=>{var G=xU(),Y=Object.prototype.toString,Q=Object.prototype.hasOwnProperty,K=function(I,F,D){for(var w=0,P=I.length;w=3)w=D;if(M(I))K(I,F,w);else if(typeof I==="string")Z(I,F,w);else J(I,F,w)}}),hU=R0((B,U)=>{U.exports=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]}),uU=R0((B,U)=>{d2();var G=hU(),Y=typeof globalThis>"u"?v0:globalThis;U.exports=function(){var K=[];for(var Z=0;Z{var G=x1(),Y=LB(),Q=f1(),K=K1();U.exports=function(J,M,W){if(!J||typeof J!=="object"&&typeof J!=="function")throw new Q("`obj` must be an object or a function`");if(typeof M!=="string"&&typeof M!=="symbol")throw new Q("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=="boolean"&&arguments[3]!==null)throw new Q("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=="boolean"&&arguments[4]!==null)throw new Q("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=="boolean"&&arguments[5]!==null)throw new Q("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=="boolean")throw new Q("`loose`, if provided, must be a boolean");var I=arguments.length>3?arguments[3]:null,F=arguments.length>4?arguments[4]:null,D=arguments.length>5?arguments[5]:null,w=arguments.length>6?arguments[6]:!1,P=!!K&&K(J,M);if(G)G(J,M,{configurable:D===null&&P?P.configurable:!D,enumerable:I===null&&P?P.enumerable:!I,value:W,writable:F===null&&P?P.writable:!F});else if(w||!I&&!F&&!D)J[M]=W;else throw new Y("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}}),cU=R0((B,U)=>{var G=x1(),Y=function(){return!!G};Y.hasArrayLengthDefineBug=function(){if(!G)return null;try{return G([],"length",{value:1}).length!==1}catch(K){return!0}},U.exports=Y}),mU=R0((B,U)=>{var G=WB(),Y=dU(),Q=cU()(),K=K1(),Z=f1(),J=G("%Math.floor%");U.exports=function(W,I){if(typeof W!=="function")throw new Z("`fn` is not a function");if(typeof I!=="number"||I<0||I>4294967295||J(I)!==I)throw new Z("`length` must be a positive 32-bit integer");var F=arguments.length>2&&!!arguments[2],D=!0,w=!0;if("length"in W&&K){var P=K(W,"length");if(P&&!P.configurable)D=!1;if(P&&!P.writable)w=!1}if(D||w||!F)if(Q)Y(W,"length",I,!0,!0);else Y(W,"length",I);return W}}),lU=R0((B,U)=>{var G=V1(),Y=v8(),Q=FB();U.exports=function(){return Q(G,Y,arguments)}}),aU=R0((B,U)=>{var G=mU(),Y=x1(),Q=y8(),K=lU();if(U.exports=function(J){var M=Q(arguments),W=J.length-(arguments.length-1);return G(M,1+(W>0?W:0),!0)},Y)Y(U.exports,"apply",{value:K});else U.exports.apply=K}),wB=R0((B,U)=>{d2();var G=_U(),Y=uU(),Q=aU(),K=PB(),Z=K1(),J=HB(),M=K("Object.prototype.toString"),W=S8()(),I=typeof globalThis>"u"?v0:globalThis,F=Y(),D=K("String.prototype.slice"),w=K("Array.prototype.indexOf",!0)||function(j,v){for(var S=0;S-1)return v;if(v!=="Object")return!1;return E(j)}if(!Z)return null;return A(j)}}),pU=R0((B,U)=>{var G=wB();U.exports=function(Q){return!!G(Q)}}),rU=R0((B)=>{var U=gU(),G=fU(),Y=wB(),Q=pU();function K(O){return O.call.bind(O)}var Z=typeof BigInt<"u",J=typeof Symbol<"u",M=K(Object.prototype.toString),W=K(Number.prototype.valueOf),I=K(String.prototype.valueOf),F=K(Boolean.prototype.valueOf);if(Z)var D=K(BigInt.prototype.valueOf);if(J)var w=K(Symbol.prototype.valueOf);function P(O,_){if(typeof O!=="object")return!1;try{return _(O),!0}catch(l){return!1}}B.isArgumentsObject=U,B.isGeneratorFunction=G,B.isTypedArray=Q;function A(O){return typeof Promise<"u"&&O instanceof Promise||O!==null&&typeof O==="object"&&typeof O.then==="function"&&typeof O.catch==="function"}B.isPromise=A;function E(O){if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView)return ArrayBuffer.isView(O);return Q(O)||n(O)}B.isArrayBufferView=E;function C(O){return Y(O)==="Uint8Array"}B.isUint8Array=C;function j(O){return Y(O)==="Uint8ClampedArray"}B.isUint8ClampedArray=j;function v(O){return Y(O)==="Uint16Array"}B.isUint16Array=v;function S(O){return Y(O)==="Uint32Array"}B.isUint32Array=S;function H(O){return Y(O)==="Int8Array"}B.isInt8Array=H;function X(O){return Y(O)==="Int16Array"}B.isInt16Array=X;function $(O){return Y(O)==="Int32Array"}B.isInt32Array=$;function x(O){return Y(O)==="Float32Array"}B.isFloat32Array=x;function N(O){return Y(O)==="Float64Array"}B.isFloat64Array=N;function a(O){return Y(O)==="BigInt64Array"}B.isBigInt64Array=a;function U0(O){return Y(O)==="BigUint64Array"}B.isBigUint64Array=U0;function b(O){return M(O)==="[object Map]"}b.working=typeof Map<"u"&&b(new Map);function c(O){if(typeof Map>"u")return!1;return b.working?b(O):O instanceof Map}B.isMap=c;function T(O){return M(O)==="[object Set]"}T.working=typeof Set<"u"&&T(new Set);function m(O){if(typeof Set>"u")return!1;return T.working?T(O):O instanceof Set}B.isSet=m;function B0(O){return M(O)==="[object WeakMap]"}B0.working=typeof WeakMap<"u"&&B0(new WeakMap);function i(O){if(typeof WeakMap>"u")return!1;return B0.working?B0(O):O instanceof WeakMap}B.isWeakMap=i;function V0(O){return M(O)==="[object WeakSet]"}V0.working=typeof WeakSet<"u"&&V0(new WeakSet);function s(O){return V0(O)}B.isWeakSet=s;function G0(O){return M(O)==="[object ArrayBuffer]"}G0.working=typeof ArrayBuffer<"u"&&G0(new ArrayBuffer);function r(O){if(typeof ArrayBuffer>"u")return!1;return G0.working?G0(O):O instanceof ArrayBuffer}B.isArrayBuffer=r;function y(O){return M(O)==="[object DataView]"}y.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&y(new DataView(new ArrayBuffer(1),0,1));function n(O){if(typeof DataView>"u")return!1;return y.working?y(O):O instanceof DataView}B.isDataView=n;var o=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Y0(O){return M(O)==="[object SharedArrayBuffer]"}function O0(O){if(typeof o>"u")return!1;if(typeof Y0.working>"u")Y0.working=Y0(new o);return Y0.working?Y0(O):O instanceof o}B.isSharedArrayBuffer=O0;function z(O){return M(O)==="[object AsyncFunction]"}B.isAsyncFunction=z;function L(O){return M(O)==="[object Map Iterator]"}B.isMapIterator=L;function u(O){return M(O)==="[object Set Iterator]"}B.isSetIterator=u;function h(O){return M(O)==="[object Generator]"}B.isGeneratorObject=h;function Z0(O){return M(O)==="[object WebAssembly.Module]"}B.isWebAssemblyCompiledModule=Z0;function g(O){return P(O,W)}B.isNumberObject=g;function f(O){return P(O,I)}B.isStringObject=f;function R(O){return P(O,F)}B.isBooleanObject=R;function p(O){return Z&&P(O,D)}B.isBigIntObject=p;function k(O){return J&&P(O,w)}B.isSymbolObject=k;function V(O){return g(O)||f(O)||R(O)||p(O)||k(O)}B.isBoxedPrimitive=V;function q(O){return typeof Uint8Array<"u"&&(r(O)||O0(O))}B.isAnyArrayBuffer=q,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(O){Object.defineProperty(B,O,{enumerable:!1,value:function(){throw Error(O+" is not supported in userland")}})})}),iU=R0((B,U)=>{U.exports=function(Y){return Y&&typeof Y==="object"&&typeof Y.copy==="function"&&typeof Y.fill==="function"&&typeof Y.readUInt8==="function"}}),AB=R0((B)=>{P2();var U=Object.getOwnPropertyDescriptors||function(n){var o=Object.keys(n),Y0={};for(var O0=0;O0=O0)return u;switch(u){case"%s":return String(Y0[o++]);case"%d":return Number(Y0[o++]);case"%j":try{return JSON.stringify(Y0[o++])}catch(h){return"[Circular]"}default:return u}});for(var L=Y0[o];o"u")return function(){return B.deprecate(y,n).apply(this,arguments)};var o=!1;function Y0(){if(!o){if(P0.throwDeprecation)throw Error(n);else if(P0.traceDeprecation)console.trace(n);else console.error(n);o=!0}return y.apply(this,arguments)}return Y0};var Y={},Q=/^$/;if(P0.env.NODE_DEBUG){var K=P0.env.NODE_DEBUG;K=K.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),Q=new RegExp("^"+K+"$","i")}B.debuglog=function(y){if(y=y.toUpperCase(),!Y[y])if(Q.test(y)){var n=P0.pid;Y[y]=function(){var o=B.format.apply(B,arguments);console.error("%s %d: %s",y,n,o)}}else Y[y]=function(){};return Y[y]};function Z(y,n){var o={seen:[],stylize:M};if(arguments.length>=3)o.depth=arguments[2];if(arguments.length>=4)o.colors=arguments[3];if(C(n))o.showHidden=n;else if(n)B._extend(o,n);if($(o.showHidden))o.showHidden=!1;if($(o.depth))o.depth=2;if($(o.colors))o.colors=!1;if($(o.customInspect))o.customInspect=!0;if(o.colors)o.stylize=J;return I(o,y,o.depth)}B.inspect=Z,Z.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},Z.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function J(y,n){var o=Z.styles[n];if(o)return"\x1B["+Z.colors[o][0]+"m"+y+"\x1B["+Z.colors[o][1]+"m";else return y}function M(y,n){return y}function W(y){var n={};return y.forEach(function(o,Y0){n[o]=!0}),n}function I(y,n,o){if(y.customInspect&&n&&b(n.inspect)&&n.inspect!==B.inspect&&!(n.constructor&&n.constructor.prototype===n)){var Y0=n.inspect(o,y);if(!H(Y0))Y0=I(y,Y0,o);return Y0}var O0=F(y,n);if(O0)return O0;var z=Object.keys(n),L=W(z);if(y.showHidden)z=Object.getOwnPropertyNames(n);if(U0(n)&&(z.indexOf("message")>=0||z.indexOf("description")>=0))return D(n);if(z.length===0){if(b(n)){var u=n.name?": "+n.name:"";return y.stylize("[Function"+u+"]","special")}if(x(n))return y.stylize(RegExp.prototype.toString.call(n),"regexp");if(a(n))return y.stylize(Date.prototype.toString.call(n),"date");if(U0(n))return D(n)}var h="",Z0=!1,g=["{","}"];if(E(n))Z0=!0,g=["[","]"];if(b(n))h=" [Function"+(n.name?": "+n.name:"")+"]";if(x(n))h=" "+RegExp.prototype.toString.call(n);if(a(n))h=" "+Date.prototype.toUTCString.call(n);if(U0(n))h=" "+D(n);if(z.length===0&&(!Z0||n.length==0))return g[0]+h+g[1];if(o<0)if(x(n))return y.stylize(RegExp.prototype.toString.call(n),"regexp");else return y.stylize("[Object]","special");y.seen.push(n);var f;if(Z0)f=w(y,n,o,L,z);else f=z.map(function(R){return P(y,n,o,L,R,Z0)});return y.seen.pop(),A(f,h,g)}function F(y,n){if($(n))return y.stylize("undefined","undefined");if(H(n)){var o="'"+JSON.stringify(n).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return y.stylize(o,"string")}if(S(n))return y.stylize(""+n,"number");if(C(n))return y.stylize(""+n,"boolean");if(j(n))return y.stylize("null","null")}function D(y){return"["+Error.prototype.toString.call(y)+"]"}function w(y,n,o,Y0,O0){var z=[];for(var L=0,u=n.length;L-1)if(z)u=u.split(` -`).map(function(Z0){return" "+Z0}).join(` -`).slice(2);else u=` -`+u.split(` -`).map(function(Z0){return" "+Z0}).join(` -`)}else u=y.stylize("[Circular]","special");if($(L)){if(z&&O0.match(/^\d+$/))return u;if(L=JSON.stringify(""+O0),L.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/))L=L.slice(1,-1),L=y.stylize(L,"name");else L=L.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),L=y.stylize(L,"string")}return L+": "+u}function A(y,n,o){var Y0=0;if(y.reduce(function(O0,z){if(Y0++,z.indexOf(` -`)>=0)Y0++;return O0+z.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return o[0]+(n===""?"":n+` - `)+" "+y.join(`, - `)+" "+o[1];return o[0]+n+" "+y.join(", ")+" "+o[1]}B.types=rU();function E(y){return Array.isArray(y)}B.isArray=E;function C(y){return typeof y==="boolean"}B.isBoolean=C;function j(y){return y===null}B.isNull=j;function v(y){return y==null}B.isNullOrUndefined=v;function S(y){return typeof y==="number"}B.isNumber=S;function H(y){return typeof y==="string"}B.isString=H;function X(y){return typeof y==="symbol"}B.isSymbol=X;function $(y){return y===void 0}B.isUndefined=$;function x(y){return N(y)&&T(y)==="[object RegExp]"}B.isRegExp=x,B.types.isRegExp=x;function N(y){return typeof y==="object"&&y!==null}B.isObject=N;function a(y){return N(y)&&T(y)==="[object Date]"}B.isDate=a,B.types.isDate=a;function U0(y){return N(y)&&(T(y)==="[object Error]"||y instanceof Error)}B.isError=U0,B.types.isNativeError=U0;function b(y){return typeof y==="function"}B.isFunction=b;function c(y){return y===null||typeof y==="boolean"||typeof y==="number"||typeof y==="string"||typeof y==="symbol"||typeof y>"u"}B.isPrimitive=c,B.isBuffer=iU();function T(y){return Object.prototype.toString.call(y)}function m(y){return y<10?"0"+y.toString(10):y.toString(10)}var B0=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function i(){var y=new Date,n=[m(y.getHours()),m(y.getMinutes()),m(y.getSeconds())].join(":");return[y.getDate(),B0[y.getMonth()],n].join(" ")}B.log=function(){console.log("%s - %s",i(),B.format.apply(B,arguments))},B.inherits=W2(),B._extend=function(y,n){if(!n||!N(n))return y;var o=Object.keys(n),Y0=o.length;while(Y0--)y[o[Y0]]=n[o[Y0]];return y};function V0(y,n){return Object.prototype.hasOwnProperty.call(y,n)}var s=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;B.promisify=function(n){if(typeof n!=="function")throw TypeError('The "original" argument must be of type Function');if(s&&n[s]){var o=n[s];if(typeof o!=="function")throw TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(o,s,{value:o,enumerable:!1,writable:!1,configurable:!0}),o}function o(){var Y0,O0,z=new Promise(function(h,Z0){Y0=h,O0=Z0}),L=[];for(var u=0;u{function G(P,A){var E=Object.keys(P);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(P);A&&(C=C.filter(function(j){return Object.getOwnPropertyDescriptor(P,j).enumerable})),E.push.apply(E,C)}return E}function Y(P){for(var A=1;A0)this.tail.next=C;else this.head=C;this.tail=C,++this.length}},{key:"unshift",value:function(E){var C={data:E,next:this.head};if(this.length===0)this.tail=C;this.head=C,++this.length}},{key:"shift",value:function(){if(this.length===0)return;var E=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,E}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(E){if(this.length===0)return"";var C=this.head,j=""+C.data;while(C=C.next)j+=E+C.data;return j}},{key:"concat",value:function(E){if(this.length===0)return I.alloc(0);var C=I.allocUnsafe(E>>>0),j=this.head,v=0;while(j)w(j.data,C,v),v+=j.data.length,j=j.next;return C}},{key:"consume",value:function(E,C){var j;if(ES.length?S.length:E;if(H===S.length)v+=S;else v+=S.slice(0,E);if(E-=H,E===0){if(H===S.length)if(++j,C.next)this.head=C.next;else this.head=this.tail=null;else this.head=C,C.data=S.slice(H);break}++j}return this.length-=j,v}},{key:"_getBuffer",value:function(E){var C=I.allocUnsafe(E),j=this.head,v=1;j.data.copy(C),E-=j.data.length;while(j=j.next){var S=j.data,H=E>S.length?S.length:E;if(S.copy(C,C.length-E,0,H),E-=H,E===0){if(H===S.length)if(++v,j.next)this.head=j.next;else this.head=this.tail=null;else this.head=j,j.data=S.slice(H);break}++v}return this.length-=v,C}},{key:D,value:function(E,C){return F(this,Y(Y({},C),{},{depth:0,customInspect:!1}))}}]),P}()}),jB=R0((B,U)=>{P2();function G(M,W){var I=this,F=this._readableState&&this._readableState.destroyed,D=this._writableState&&this._writableState.destroyed;if(F||D){if(W)W(M);else if(M){if(!this._writableState)P0.nextTick(Z,this,M);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,P0.nextTick(Z,this,M)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy(M||null,function(w){if(!W&&w)if(!I._writableState)P0.nextTick(Y,I,w);else if(!I._writableState.errorEmitted)I._writableState.errorEmitted=!0,P0.nextTick(Y,I,w);else P0.nextTick(Q,I);else if(W)P0.nextTick(Q,I),W(w);else P0.nextTick(Q,I)}),this}function Y(M,W){Z(M,W),Q(M)}function Q(M){if(M._writableState&&!M._writableState.emitClose)return;if(M._readableState&&!M._readableState.emitClose)return;M.emit("close")}function K(){if(this._readableState)this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1;if(this._writableState)this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1}function Z(M,W){M.emit("error",W)}function J(M,W){var{_readableState:I,_writableState:F}=M;if(I&&I.autoDestroy||F&&F.autoDestroy)M.destroy(W);else M.emit("error",W)}U.exports={destroy:G,undestroy:K,errorOrDestroy:J}}),c2=R0((B,U)=>{function G(W,I){W.prototype=Object.create(I.prototype),W.prototype.constructor=W,W.__proto__=I}var Y={};function Q(W,I,F){if(!F)F=Error;function D(P,A,E){if(typeof I==="string")return I;else return I(P,A,E)}var w=function(P){G(A,P);function A(E,C,j){return P.call(this,D(E,C,j))||this}return A}(F);w.prototype.name=F.name,w.prototype.code=W,Y[W]=w}function K(W,I){if(Array.isArray(W)){var F=W.length;if(W=W.map(function(D){return String(D)}),F>2)return"one of ".concat(I," ").concat(W.slice(0,F-1).join(", "),", or ")+W[F-1];else if(F===2)return"one of ".concat(I," ").concat(W[0]," or ").concat(W[1]);else return"of ".concat(I," ").concat(W[0])}else return"of ".concat(I," ").concat(String(W))}function Z(W,I,F){return W.substr(!F||F<0?0:+F,I.length)===I}function J(W,I,F){if(F===void 0||F>W.length)F=W.length;return W.substring(F-I.length,F)===I}function M(W,I,F){if(typeof F!=="number")F=0;if(F+I.length>W.length)return!1;else return W.indexOf(I,F)!==-1}Q("ERR_INVALID_OPT_VALUE",function(W,I){return'The value "'+I+'" is invalid for option "'+W+'"'},TypeError),Q("ERR_INVALID_ARG_TYPE",function(W,I,F){var D;if(typeof I==="string"&&Z(I,"not "))D="must not be",I=I.replace(/^not /,"");else D="must be";var w;if(J(W," argument"))w="The ".concat(W," ").concat(D," ").concat(K(I,"type"));else{var P=M(W,".")?"property":"argument";w='The "'.concat(W,'" ').concat(P," ").concat(D," ").concat(K(I,"type"))}return w+=". Received type ".concat(typeof F),w},TypeError),Q("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Q("ERR_METHOD_NOT_IMPLEMENTED",function(W){return"The "+W+" method is not implemented"}),Q("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Q("ERR_STREAM_DESTROYED",function(W){return"Cannot call "+W+" after a stream was destroyed"}),Q("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Q("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Q("ERR_STREAM_WRITE_AFTER_END","write after end"),Q("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Q("ERR_UNKNOWN_ENCODING",function(W){return"Unknown encoding: "+W},TypeError),Q("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),U.exports.codes=Y}),NB=R0((B,U)=>{var G=c2().codes.ERR_INVALID_OPT_VALUE;function Y(K,Z,J){return K.highWaterMark!=null?K.highWaterMark:Z?K[J]:null}function Q(K,Z,J,M){var W=Y(Z,M,J);if(W!=null){if(!(isFinite(W)&&Math.floor(W)===W)||W<0)throw new G(M?J:"highWaterMark",W);return Math.floor(W)}return K.objectMode?16:16384}U.exports={getHighWaterMark:Q}}),sU=R0((B,U)=>{d2(),U.exports=G;function G(Q,K){if(Y("noDeprecation"))return Q;var Z=!1;function J(){if(!Z){if(Y("throwDeprecation"))throw Error(K);else if(Y("traceDeprecation"))console.trace(K);else console.warn(K);Z=!0}return Q.apply(this,arguments)}return J}function Y(Q){try{if(!v0.localStorage)return!1}catch(Z){return!1}var K=v0.localStorage[Q];if(K==null)return!1;return String(K).toLowerCase()==="true"}}),zB=R0((B,U)=>{d2(),P2(),U.exports=N;function G(z){var L=this;this.next=null,this.entry=null,this.finish=function(){O0(L,z)}}var Y;N.WritableState=$;var Q={deprecate:sU()},K=MB(),Z=g1().Buffer,J=(typeof v0<"u"?v0:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function M(z){return Z.from(z)}function W(z){return Z.isBuffer(z)||z instanceof J}var I=jB(),F=NB().getHighWaterMark,D=c2().codes,w=D.ERR_INVALID_ARG_TYPE,P=D.ERR_METHOD_NOT_IMPLEMENTED,A=D.ERR_MULTIPLE_CALLBACK,E=D.ERR_STREAM_CANNOT_PIPE,C=D.ERR_STREAM_DESTROYED,j=D.ERR_STREAM_NULL_VALUES,v=D.ERR_STREAM_WRITE_AFTER_END,S=D.ERR_UNKNOWN_ENCODING,H=I.errorOrDestroy;W2()(N,K);function X(){}function $(z,L,u){if(Y=Y||u2(),z=z||{},typeof u!=="boolean")u=L instanceof Y;if(this.objectMode=!!z.objectMode,u)this.objectMode=this.objectMode||!!z.writableObjectMode;this.highWaterMark=F(this,z,"writableHighWaterMark",u),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=z.decodeStrings===!1;this.decodeStrings=!h,this.defaultEncoding=z.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Z0){i(L,Z0)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=z.emitClose!==!1,this.autoDestroy=!!z.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new G(this)}$.prototype.getBuffer=function(){var L=this.bufferedRequest,u=[];while(L)u.push(L),L=L.next;return u},function(){try{Object.defineProperty($.prototype,"buffer",{get:Q.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(z){}}();var x;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function")x=Function.prototype[Symbol.hasInstance],Object.defineProperty(N,Symbol.hasInstance,{value:function(L){if(x.call(this,L))return!0;if(this!==N)return!1;return L&&L._writableState instanceof $}});else x=function(L){return L instanceof this};function N(z){Y=Y||u2();var L=this instanceof Y;if(!L&&!x.call(N,this))return new N(z);if(this._writableState=new $(z,this,L),this.writable=!0,z){if(typeof z.write==="function")this._write=z.write;if(typeof z.writev==="function")this._writev=z.writev;if(typeof z.destroy==="function")this._destroy=z.destroy;if(typeof z.final==="function")this._final=z.final}K.call(this)}N.prototype.pipe=function(){H(this,new E)};function a(z,L){var u=new v;H(z,u),P0.nextTick(L,u)}function U0(z,L,u,h){var Z0;if(u===null)Z0=new j;else if(typeof u!=="string"&&!L.objectMode)Z0=new w("chunk",["string","Buffer"],u);if(Z0)return H(z,Z0),P0.nextTick(h,Z0),!1;return!0}N.prototype.write=function(z,L,u){var h=this._writableState,Z0=!1,g=!h.objectMode&&W(z);if(g&&!Z.isBuffer(z))z=M(z);if(typeof L==="function")u=L,L=null;if(g)L="buffer";else if(!L)L=h.defaultEncoding;if(typeof u!=="function")u=X;if(h.ending)a(this,u);else if(g||U0(this,h,z,u))h.pendingcb++,Z0=c(this,h,g,z,L,u);return Z0},N.prototype.cork=function(){this._writableState.corked++},N.prototype.uncork=function(){var z=this._writableState;if(z.corked){if(z.corked--,!z.writing&&!z.corked&&!z.bufferProcessing&&z.bufferedRequest)G0(this,z)}},N.prototype.setDefaultEncoding=function(L){if(typeof L==="string")L=L.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((L+"").toLowerCase())>-1))throw new S(L);return this._writableState.defaultEncoding=L,this},Object.defineProperty(N.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function b(z,L,u){if(!z.objectMode&&z.decodeStrings!==!1&&typeof L==="string")L=Z.from(L,u);return L}Object.defineProperty(N.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function c(z,L,u,h,Z0,g){if(!u){var f=b(L,h,Z0);if(h!==f)u=!0,Z0="buffer",h=f}var R=L.objectMode?1:h.length;L.length+=R;var p=L.length{P2();var G=Object.keys||function(F){var D=[];for(var w in F)D.push(w);return D};U.exports=M;var Y=EB(),Q=zB();W2()(M,Y);var K=G(Q.prototype);for(var Z=0;Z{var G=g1(),Y=G.Buffer;function Q(Z,J){for(var M in Z)J[M]=Z[M]}if(Y.from&&Y.alloc&&Y.allocUnsafe&&Y.allocUnsafeSlow)U.exports=G;else Q(G,B),B.Buffer=K;function K(Z,J,M){return Y(Z,J,M)}Q(Y,K),K.from=function(Z,J,M){if(typeof Z==="number")throw TypeError("Argument must not be a number");return Y(Z,J,M)},K.alloc=function(Z,J,M){if(typeof Z!=="number")throw TypeError("Argument must be a number");var W=Y(Z);if(J!==void 0)if(typeof M==="string")W.fill(J,M);else W.fill(J);else W.fill(0);return W},K.allocUnsafe=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return Y(Z)},K.allocUnsafeSlow=function(Z){if(typeof Z!=="number")throw TypeError("Argument must be a number");return G.SlowBuffer(Z)}}),F8=R0((B)=>{var U=oU().Buffer,G=U.isEncoding||function(j){switch(j=""+j,j&&j.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Y(j){if(!j)return"utf8";var v;while(!0)switch(j){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return j;default:if(v)return;j=(""+j).toLowerCase(),v=!0}}function Q(j){var v=Y(j);if(typeof v!=="string"&&(U.isEncoding===G||!G(j)))throw Error("Unknown encoding: "+j);return v||j}B.StringDecoder=K;function K(j){this.encoding=Q(j);var v;switch(this.encoding){case"utf16le":this.text=D,this.end=w,v=4;break;case"utf8":this.fillLast=W,v=4;break;case"base64":this.text=P,this.end=A,v=3;break;default:this.write=E,this.end=C;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=U.allocUnsafe(v)}K.prototype.write=function(j){if(j.length===0)return"";var v,S;if(this.lastNeed){if(v=this.fillLast(j),v===void 0)return"";S=this.lastNeed,this.lastNeed=0}else S=0;if(S>5===6)return 2;else if(j>>4===14)return 3;else if(j>>3===30)return 4;return j>>6===2?-1:-2}function J(j,v,S){var H=v.length-1;if(H=0){if(X>0)j.lastNeed=X-1;return X}if(--H=0){if(X>0)j.lastNeed=X-2;return X}if(--H=0){if(X>0)if(X===2)X=0;else j.lastNeed=X-3;return X}return 0}function M(j,v,S){if((v[0]&192)!==128)return j.lastNeed=0,"�";if(j.lastNeed>1&&v.length>1){if((v[1]&192)!==128)return j.lastNeed=1,"�";if(j.lastNeed>2&&v.length>2){if((v[2]&192)!==128)return j.lastNeed=2,"�"}}}function W(j){var v=this.lastTotal-this.lastNeed,S=M(this,j,v);if(S!==void 0)return S;if(this.lastNeed<=j.length)return j.copy(this.lastChar,v,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);j.copy(this.lastChar,v,0,j.length),this.lastNeed-=j.length}function I(j,v){var S=J(this,j,v);if(!this.lastNeed)return j.toString("utf8",v);this.lastTotal=S;var H=j.length-(S-this.lastNeed);return j.copy(this.lastChar,0,H),j.toString("utf8",v,H)}function F(j){var v=j&&j.length?this.write(j):"";if(this.lastNeed)return v+"�";return v}function D(j,v){if((j.length-v)%2===0){var S=j.toString("utf16le",v);if(S){var H=S.charCodeAt(S.length-1);if(H>=55296&&H<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=j[j.length-2],this.lastChar[1]=j[j.length-1],S.slice(0,-1)}return S}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=j[j.length-1],j.toString("utf16le",v,j.length-1)}function w(j){var v=j&&j.length?this.write(j):"";if(this.lastNeed){var S=this.lastTotal-this.lastNeed;return v+this.lastChar.toString("utf16le",0,S)}return v}function P(j,v){var S=(j.length-v)%3;if(S===0)return j.toString("base64",v);if(this.lastNeed=3-S,this.lastTotal=3,S===1)this.lastChar[0]=j[j.length-1];else this.lastChar[0]=j[j.length-2],this.lastChar[1]=j[j.length-1];return j.toString("base64",v,j.length-S)}function A(j){var v=j&&j.length?this.write(j):"";if(this.lastNeed)return v+this.lastChar.toString("base64",0,3-this.lastNeed);return v}function E(j){return j.toString(this.encoding)}function C(j){return j&&j.length?this.write(j):""}}),g8=R0((B,U)=>{var G=c2().codes.ERR_STREAM_PREMATURE_CLOSE;function Y(J){var M=!1;return function(){if(M)return;M=!0;for(var W=arguments.length,I=Array(W),F=0;F{P2();var G;function Y(S,H,X){if(H=Q(H),H in S)Object.defineProperty(S,H,{value:X,enumerable:!0,configurable:!0,writable:!0});else S[H]=X;return S}function Q(S){var H=K(S,"string");return typeof H==="symbol"?H:String(H)}function K(S,H){if(typeof S!=="object"||S===null)return S;var X=S[Symbol.toPrimitive];if(X!==void 0){var $=X.call(S,H||"default");if(typeof $!=="object")return $;throw TypeError("@@toPrimitive must return a primitive value.")}return(H==="string"?String:Number)(S)}var Z=g8(),J=Symbol("lastResolve"),M=Symbol("lastReject"),W=Symbol("error"),I=Symbol("ended"),F=Symbol("lastPromise"),D=Symbol("handlePromise"),w=Symbol("stream");function P(S,H){return{value:S,done:H}}function A(S){var H=S[J];if(H!==null){var X=S[w].read();if(X!==null)S[F]=null,S[J]=null,S[M]=null,H(P(X,!1))}}function E(S){P0.nextTick(A,S)}function C(S,H){return function(X,$){S.then(function(){if(H[I]){X(P(void 0,!0));return}H[D](X,$)},$)}}var j=Object.getPrototypeOf(function(){}),v=Object.setPrototypeOf((G={get stream(){return this[w]},next:function(){var H=this,X=this[W];if(X!==null)return Promise.reject(X);if(this[I])return Promise.resolve(P(void 0,!0));if(this[w].destroyed)return new Promise(function(a,U0){P0.nextTick(function(){if(H[W])U0(H[W]);else a(P(void 0,!0))})});var $=this[F],x;if($)x=new Promise(C($,this));else{var N=this[w].read();if(N!==null)return Promise.resolve(P(N,!1));x=new Promise(this[D])}return this[F]=x,x}},Y(G,Symbol.asyncIterator,function(){return this}),Y(G,"return",function(){var H=this;return new Promise(function(X,$){H[w].destroy(null,function(x){if(x){$(x);return}X(P(void 0,!0))})})}),G),j);U.exports=function(H){var X,$=Object.create(v,(X={},Y(X,w,{value:H,writable:!0}),Y(X,J,{value:null,writable:!0}),Y(X,M,{value:null,writable:!0}),Y(X,W,{value:null,writable:!0}),Y(X,I,{value:H._readableState.endEmitted,writable:!0}),Y(X,D,{value:function(N,a){var U0=$[w].read();if(U0)$[F]=null,$[J]=null,$[M]=null,N(P(U0,!1));else $[J]=N,$[M]=a},writable:!0}),X));return $[F]=null,Z(H,function(x){if(x&&x.code!=="ERR_STREAM_PREMATURE_CLOSE"){var N=$[M];if(N!==null)$[F]=null,$[J]=null,$[M]=null,N(x);$[W]=x;return}var a=$[J];if(a!==null)$[F]=null,$[J]=null,$[M]=null,a(P(void 0,!0));$[I]=!0}),H.on("readable",E.bind(null,$)),$}}),eU=R0((B,U)=>{U.exports=function(){throw Error("Readable.from is not available in the browser")}}),EB=R0((B,U)=>{d2(),P2(),U.exports=a;var G;a.ReadableState=N,$8().EventEmitter;var Y=function(f,R){return f.listeners(R).length},Q=MB(),K=g1().Buffer,Z=(typeof v0<"u"?v0:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function J(g){return K.from(g)}function M(g){return K.isBuffer(g)||g instanceof Z}var W=AB(),I;if(W&&W.debuglog)I=W.debuglog("stream");else I=function(){};var F=nU(),D=jB(),w=NB().getHighWaterMark,P=c2().codes,A=P.ERR_INVALID_ARG_TYPE,E=P.ERR_STREAM_PUSH_AFTER_EOF,C=P.ERR_METHOD_NOT_IMPLEMENTED,j=P.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,v,S,H;W2()(a,Q);var X=D.errorOrDestroy,$=["error","close","destroy","pause","resume"];function x(g,f,R){if(typeof g.prependListener==="function")return g.prependListener(f,R);if(!g._events||!g._events[f])g.on(f,R);else if(Array.isArray(g._events[f]))g._events[f].unshift(R);else g._events[f]=[R,g._events[f]]}function N(g,f,R){if(G=G||u2(),g=g||{},typeof R!=="boolean")R=f instanceof G;if(this.objectMode=!!g.objectMode,R)this.objectMode=this.objectMode||!!g.readableObjectMode;if(this.highWaterMark=w(this,g,"readableHighWaterMark",R),this.buffer=new F,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=g.emitClose!==!1,this.autoDestroy=!!g.autoDestroy,this.destroyed=!1,this.defaultEncoding=g.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,g.encoding){if(!v)v=F8().StringDecoder;this.decoder=new v(g.encoding),this.encoding=g.encoding}}function a(g){if(G=G||u2(),!(this instanceof a))return new a(g);var f=this instanceof G;if(this._readableState=new N(g,this,f),this.readable=!0,g){if(typeof g.read==="function")this._read=g.read;if(typeof g.destroy==="function")this._destroy=g.destroy}Q.call(this)}Object.defineProperty(a.prototype,"destroyed",{enumerable:!1,get:function(){if(this._readableState===void 0)return!1;return this._readableState.destroyed},set:function(f){if(!this._readableState)return;this._readableState.destroyed=f}}),a.prototype.destroy=D.destroy,a.prototype._undestroy=D.undestroy,a.prototype._destroy=function(g,f){f(g)},a.prototype.push=function(g,f){var R=this._readableState,p;if(!R.objectMode){if(typeof g==="string"){if(f=f||R.defaultEncoding,f!==R.encoding)g=K.from(g,f),f="";p=!0}}else p=!0;return U0(this,g,f,!1,p)},a.prototype.unshift=function(g){return U0(this,g,null,!0,!1)};function U0(g,f,R,p,k){I("readableAddChunk",f);var V=g._readableState;if(f===null)V.reading=!1,i(g,V);else{var q;if(!k)q=c(V,f);if(q)X(g,q);else if(V.objectMode||f&&f.length>0){if(typeof f!=="string"&&!V.objectMode&&Object.getPrototypeOf(f)!==K.prototype)f=J(f);if(p)if(V.endEmitted)X(g,new j);else b(g,V,f,!0);else if(V.ended)X(g,new E);else if(V.destroyed)return!1;else if(V.reading=!1,V.decoder&&!R)if(f=V.decoder.write(f),V.objectMode||f.length!==0)b(g,V,f,!1);else G0(g,V);else b(g,V,f,!1)}else if(!p)V.reading=!1,G0(g,V)}return!V.ended&&(V.length=T)g=T;else g--,g|=g>>>1,g|=g>>>2,g|=g>>>4,g|=g>>>8,g|=g>>>16,g++;return g}function B0(g,f){if(g<=0||f.length===0&&f.ended)return 0;if(f.objectMode)return 1;if(g!==g)if(f.flowing&&f.length)return f.buffer.head.data.length;else return f.length;if(g>f.highWaterMark)f.highWaterMark=m(g);if(g<=f.length)return g;if(!f.ended)return f.needReadable=!0,0;return f.length}a.prototype.read=function(g){I("read",g),g=parseInt(g,10);var f=this._readableState,R=g;if(g!==0)f.emittedReadable=!1;if(g===0&&f.needReadable&&((f.highWaterMark!==0?f.length>=f.highWaterMark:f.length>0)||f.ended)){if(I("read: emitReadable",f.length,f.ended),f.length===0&&f.ended)u(this);else V0(this);return null}if(g=B0(g,f),g===0&&f.ended){if(f.length===0)u(this);return null}var p=f.needReadable;if(I("need readable",p),f.length===0||f.length-g0)k=L(g,f);else k=null;if(k===null)f.needReadable=f.length<=f.highWaterMark,g=0;else f.length-=g,f.awaitDrain=0;if(f.length===0){if(!f.ended)f.needReadable=!0;if(R!==g&&f.ended)u(this)}if(k!==null)this.emit("data",k);return k};function i(g,f){if(I("onEofChunk"),f.ended)return;if(f.decoder){var R=f.decoder.end();if(R&&R.length)f.buffer.push(R),f.length+=f.objectMode?1:R.length}if(f.ended=!0,f.sync)V0(g);else if(f.needReadable=!1,!f.emittedReadable)f.emittedReadable=!0,s(g)}function V0(g){var f=g._readableState;if(I("emitReadable",f.needReadable,f.emittedReadable),f.needReadable=!1,!f.emittedReadable)I("emitReadable",f.flowing),f.emittedReadable=!0,P0.nextTick(s,g)}function s(g){var f=g._readableState;if(I("emitReadable_",f.destroyed,f.length,f.ended),!f.destroyed&&(f.length||f.ended))g.emit("readable"),f.emittedReadable=!1;f.needReadable=!f.flowing&&!f.ended&&f.length<=f.highWaterMark,z(g)}function G0(g,f){if(!f.readingMore)f.readingMore=!0,P0.nextTick(r,g,f)}function r(g,f){while(!f.reading&&!f.ended&&(f.length1&&Z0(p.pipes,g)!==-1)&&!_)I("false write response, pause",p.awaitDrain),p.awaitDrain++;R.pause()}}function Q0(H0){if(I("onerror",H0),I0(),g.removeListener("error",Q0),Y(g,"error")===0)X(g,H0)}x(g,"error",Q0);function q0(){g.removeListener("finish",K0),I0()}g.once("close",q0);function K0(){I("onfinish"),g.removeListener("close",q0),I0()}g.once("finish",K0);function I0(){I("unpipe"),R.unpipe(g)}if(g.emit("pipe",R),!p.flowing)I("pipe resume"),R.resume();return g};function y(g){return function(){var R=g._readableState;if(I("pipeOnDrain",R.awaitDrain),R.awaitDrain)R.awaitDrain--;if(R.awaitDrain===0&&Y(g,"data"))R.flowing=!0,z(g)}}a.prototype.unpipe=function(g){var f=this._readableState,R={hasUnpiped:!1};if(f.pipesCount===0)return this;if(f.pipesCount===1){if(g&&g!==f.pipes)return this;if(!g)g=f.pipes;if(f.pipes=null,f.pipesCount=0,f.flowing=!1,g)g.emit("unpipe",this,R);return this}if(!g){var{pipes:p,pipesCount:k}=f;f.pipes=null,f.pipesCount=0,f.flowing=!1;for(var V=0;V0,p.flowing!==!1)this.resume()}else if(g==="readable"){if(!p.endEmitted&&!p.readableListening){if(p.readableListening=p.needReadable=!0,p.flowing=!1,p.emittedReadable=!1,I("on readable",p.length,p.reading),p.length)V0(this);else if(!p.reading)P0.nextTick(o,this)}}return R},a.prototype.addListener=a.prototype.on,a.prototype.removeListener=function(g,f){var R=Q.prototype.removeListener.call(this,g,f);if(g==="readable")P0.nextTick(n,this);return R},a.prototype.removeAllListeners=function(g){var f=Q.prototype.removeAllListeners.apply(this,arguments);if(g==="readable"||g===void 0)P0.nextTick(n,this);return f};function n(g){var f=g._readableState;if(f.readableListening=g.listenerCount("readable")>0,f.resumeScheduled&&!f.paused)f.flowing=!0;else if(g.listenerCount("data")>0)g.resume()}function o(g){I("readable nexttick read 0"),g.read(0)}a.prototype.resume=function(){var g=this._readableState;if(!g.flowing)I("resume"),g.flowing=!g.readableListening,Y0(this,g);return g.paused=!1,this};function Y0(g,f){if(!f.resumeScheduled)f.resumeScheduled=!0,P0.nextTick(O0,g,f)}function O0(g,f){if(I("resume",f.reading),!f.reading)g.read(0);if(f.resumeScheduled=!1,g.emit("resume"),z(g),f.flowing&&!f.reading)g.read(0)}a.prototype.pause=function(){if(I("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)I("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState.paused=!0,this};function z(g){var f=g._readableState;I("flow",f.flowing);while(f.flowing&&g.read()!==null);}if(a.prototype.wrap=function(g){var f=this,R=this._readableState,p=!1;g.on("end",function(){if(I("wrapped end"),R.decoder&&!R.ended){var q=R.decoder.end();if(q&&q.length)f.push(q)}f.push(null)}),g.on("data",function(q){if(I("wrapped data"),R.decoder)q=R.decoder.write(q);if(R.objectMode&&(q===null||q===void 0))return;else if(!R.objectMode&&(!q||!q.length))return;if(!f.push(q))p=!0,g.pause()});for(var k in g)if(this[k]===void 0&&typeof g[k]==="function")this[k]=function(O){return function(){return g[O].apply(g,arguments)}}(k);for(var V=0;V<$.length;V++)g.on($[V],this.emit.bind(this,$[V]));return this._read=function(q){if(I("wrapped _read",q),p)p=!1,g.resume()},this},typeof Symbol==="function")a.prototype[Symbol.asyncIterator]=function(){if(S===void 0)S=tU();return S(this)};Object.defineProperty(a.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(a.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(a.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(f){if(this._readableState)this._readableState.flowing=f}}),a._fromList=L,Object.defineProperty(a.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function L(g,f){if(f.length===0)return null;var R;if(f.objectMode)R=f.buffer.shift();else if(!g||g>=f.length){if(f.decoder)R=f.buffer.join("");else if(f.buffer.length===1)R=f.buffer.first();else R=f.buffer.concat(f.length);f.buffer.clear()}else R=f.buffer.consume(g,f.decoder);return R}function u(g){var f=g._readableState;if(I("endReadable",f.endEmitted),!f.endEmitted)f.ended=!0,P0.nextTick(h,f,g)}function h(g,f){if(I("endReadableNT",g.endEmitted,g.length),!g.endEmitted&&g.length===0){if(g.endEmitted=!0,f.readable=!1,f.emit("end"),g.autoDestroy){var R=f._writableState;if(!R||R.autoDestroy&&R.finished)f.destroy()}}}if(typeof Symbol==="function")a.from=function(g,f){if(H===void 0)H=eU();return H(a,g,f)};function Z0(g,f){for(var R=0,p=g.length;R{U.exports=W;var G=c2().codes,Y=G.ERR_METHOD_NOT_IMPLEMENTED,Q=G.ERR_MULTIPLE_CALLBACK,K=G.ERR_TRANSFORM_ALREADY_TRANSFORMING,Z=G.ERR_TRANSFORM_WITH_LENGTH_0,J=u2();W2()(W,J);function M(D,w){var P=this._transformState;P.transforming=!1;var A=P.writecb;if(A===null)return this.emit("error",new Q);if(P.writechunk=null,P.writecb=null,w!=null)this.push(w);A(D);var E=this._readableState;if(E.reading=!1,E.needReadable||E.length{U.exports=Y;var G=TB();W2()(Y,G);function Y(Q){if(!(this instanceof Y))return new Y(Q);G.call(this,Q)}Y.prototype._transform=function(Q,K,Z){Z(null,Q)}}),UG=R0((B,U)=>{var G;function Y(P){var A=!1;return function(){if(A)return;A=!0,P.apply(void 0,arguments)}}var Q=c2().codes,K=Q.ERR_MISSING_ARGS,Z=Q.ERR_STREAM_DESTROYED;function J(P){if(P)throw P}function M(P){return P.setHeader&&typeof P.abort==="function"}function W(P,A,E,C){C=Y(C);var j=!1;if(P.on("close",function(){j=!0}),G===void 0)G=g8();G(P,{readable:A,writable:E},function(S){if(S)return C(S);j=!0,C()});var v=!1;return function(S){if(j)return;if(v)return;if(v=!0,M(P))return P.abort();if(typeof P.destroy==="function")return P.destroy();C(S||new Z("pipe"))}}function I(P){P()}function F(P,A){return P.pipe(A)}function D(P){if(!P.length)return J;if(typeof P[P.length-1]!=="function")return J;return P.pop()}function w(){for(var P=arguments.length,A=Array(P),E=0;E0,function($){if(!j)j=$;if($)v.forEach(I);if(X)return;v.forEach(I),C(j)})});return A.reduce(F)}U.exports=w}),f8=R0((B,U)=>{U.exports=Y;var G=$8().EventEmitter;W2()(Y,G),Y.Readable=EB(),Y.Writable=zB(),Y.Duplex=u2(),Y.Transform=TB(),Y.PassThrough=BG(),Y.finished=g8(),Y.pipeline=UG(),Y.Stream=Y;function Y(){G.call(this)}Y.prototype.pipe=function(Q,K){var Z=this;function J(P){if(Q.writable){if(Q.write(P)===!1&&Z.pause)Z.pause()}}Z.on("data",J);function M(){if(Z.readable&&Z.resume)Z.resume()}if(Q.on("drain",M),!Q._isStdio&&(!K||K.end!==!1))Z.on("end",I),Z.on("close",F);var W=!1;function I(){if(W)return;W=!0,Q.end()}function F(){if(W)return;if(W=!0,typeof Q.destroy==="function")Q.destroy()}function D(P){if(w(),G.listenerCount(this,"error")===0)throw P}Z.on("error",D),Q.on("error",D);function w(){Z.removeListener("data",J),Q.removeListener("drain",M),Z.removeListener("end",I),Z.removeListener("close",F),Z.removeListener("error",D),Q.removeListener("error",D),Z.removeListener("end",w),Z.removeListener("close",w),Q.removeListener("close",w)}return Z.on("end",w),Z.on("close",w),Q.on("close",w),Q.emit("pipe",Z),Q}}),GG=R0((B)=>{(function(U){U.parser=function(z,L){return new Y(z,L)},U.SAXParser=Y,U.SAXStream=I,U.createStream=W,U.MAX_BUFFER_LENGTH=65536;var G=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];U.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function Y(z,L){if(!(this instanceof Y))return new Y(z,L);var u=this;if(K(u),u.q=u.c="",u.bufferCheckPosition=U.MAX_BUFFER_LENGTH,u.opt=L||{},u.opt.lowercase=u.opt.lowercase||u.opt.lowercasetags,u.looseCase=u.opt.lowercase?"toLowerCase":"toUpperCase",u.tags=[],u.closed=u.closedRoot=u.sawRoot=!1,u.tag=u.error=null,u.strict=!!z,u.noscript=!!(z||u.opt.noscript),u.state=N.BEGIN,u.strictEntities=u.opt.strictEntities,u.ENTITIES=u.strictEntities?Object.create(U.XML_ENTITIES):Object.create(U.ENTITIES),u.attribList=[],u.opt.xmlns)u.ns=Object.create(A);if(u.trackPosition=u.opt.position!==!1,u.trackPosition)u.position=u.line=u.column=0;U0(u,"onready")}if(!Object.create)Object.create=function(z){function L(){}return L.prototype=z,new L};if(!Object.keys)Object.keys=function(z){var L=[];for(var u in z)if(z.hasOwnProperty(u))L.push(u);return L};function Q(z){var L=Math.max(U.MAX_BUFFER_LENGTH,10),u=0;for(var h=0,Z0=G.length;hL)switch(G[h]){case"textNode":c(z);break;case"cdata":b(z,"oncdata",z.cdata),z.cdata="";break;case"script":b(z,"onscript",z.script),z.script="";break;default:m(z,"Max buffer length exceeded: "+G[h])}u=Math.max(u,g)}z.bufferCheckPosition=U.MAX_BUFFER_LENGTH-u+z.position}function K(z){for(var L=0,u=G.length;L"||S(z)}function $(z,L){return z.test(L)}function x(z,L){return!$(z,L)}var N=0;U.STATE={BEGIN:N++,BEGIN_WHITESPACE:N++,TEXT:N++,TEXT_ENTITY:N++,OPEN_WAKA:N++,SGML_DECL:N++,SGML_DECL_QUOTED:N++,DOCTYPE:N++,DOCTYPE_QUOTED:N++,DOCTYPE_DTD:N++,DOCTYPE_DTD_QUOTED:N++,COMMENT_STARTING:N++,COMMENT:N++,COMMENT_ENDING:N++,COMMENT_ENDED:N++,CDATA:N++,CDATA_ENDING:N++,CDATA_ENDING_2:N++,PROC_INST:N++,PROC_INST_BODY:N++,PROC_INST_ENDING:N++,OPEN_TAG:N++,OPEN_TAG_SLASH:N++,ATTRIB:N++,ATTRIB_NAME:N++,ATTRIB_NAME_SAW_WHITE:N++,ATTRIB_VALUE:N++,ATTRIB_VALUE_QUOTED:N++,ATTRIB_VALUE_CLOSED:N++,ATTRIB_VALUE_UNQUOTED:N++,ATTRIB_VALUE_ENTITY_Q:N++,ATTRIB_VALUE_ENTITY_U:N++,CLOSE_TAG:N++,CLOSE_TAG_SAW_WHITE:N++,SCRIPT:N++,SCRIPT_ENDING:N++},U.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},U.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(U.ENTITIES).forEach(function(z){var L=U.ENTITIES[z],u=typeof L==="number"?String.fromCharCode(L):L;U.ENTITIES[z]=u});for(var a in U.STATE)U.STATE[U.STATE[a]]=a;N=U.STATE;function U0(z,L,u){z[L]&&z[L](u)}function b(z,L,u){if(z.textNode)c(z);U0(z,L,u)}function c(z){if(z.textNode=T(z.opt,z.textNode),z.textNode)U0(z,"ontext",z.textNode);z.textNode=""}function T(z,L){if(z.trim)L=L.trim();if(z.normalize)L=L.replace(/\s+/g," ");return L}function m(z,L){if(c(z),z.trackPosition)L+=` -Line: `+z.line+` -Column: `+z.column+` -Char: `+z.c;return L=Error(L),z.error=L,U0(z,"onerror",L),z}function B0(z){if(z.sawRoot&&!z.closedRoot)i(z,"Unclosed root tag");if(z.state!==N.BEGIN&&z.state!==N.BEGIN_WHITESPACE&&z.state!==N.TEXT)m(z,"Unexpected end");return c(z),z.c="",z.closed=!0,U0(z,"onend"),Y.call(z,z.strict,z.opt),z}function i(z,L){if(typeof z!=="object"||!(z instanceof Y))throw Error("bad call to strictFail");if(z.strict)m(z,L)}function V0(z){if(!z.strict)z.tagName=z.tagName[z.looseCase]();var L=z.tags[z.tags.length-1]||z,u=z.tag={name:z.tagName,attributes:{}};if(z.opt.xmlns)u.ns=L.ns;z.attribList.length=0,b(z,"onopentagstart",u)}function s(z,L){var u=z.indexOf(":")<0?["",z]:z.split(":"),h=u[0],Z0=u[1];if(L&&z==="xmlns")h="xmlns",Z0="";return{prefix:h,local:Z0}}function G0(z){if(!z.strict)z.attribName=z.attribName[z.looseCase]();if(z.attribList.indexOf(z.attribName)!==-1||z.tag.attributes.hasOwnProperty(z.attribName)){z.attribName=z.attribValue="";return}if(z.opt.xmlns){var L=s(z.attribName,!0),u=L.prefix,h=L.local;if(u==="xmlns")if(h==="xml"&&z.attribValue!==w)i(z,"xml: prefix must be bound to "+w+` -Actual: `+z.attribValue);else if(h==="xmlns"&&z.attribValue!==P)i(z,"xmlns: prefix must be bound to "+P+` -Actual: `+z.attribValue);else{var Z0=z.tag,g=z.tags[z.tags.length-1]||z;if(Z0.ns===g.ns)Z0.ns=Object.create(g.ns);Z0.ns[h]=z.attribValue}z.attribList.push([z.attribName,z.attribValue])}else z.tag.attributes[z.attribName]=z.attribValue,b(z,"onattribute",{name:z.attribName,value:z.attribValue});z.attribName=z.attribValue=""}function r(z,L){if(z.opt.xmlns){var u=z.tag,h=s(z.tagName);if(u.prefix=h.prefix,u.local=h.local,u.uri=u.ns[h.prefix]||"",u.prefix&&!u.uri)i(z,"Unbound namespace prefix: "+JSON.stringify(z.tagName)),u.uri=h.prefix;var Z0=z.tags[z.tags.length-1]||z;if(u.ns&&Z0.ns!==u.ns)Object.keys(u.ns).forEach(function(d){b(z,"onopennamespace",{prefix:d,uri:u.ns[d]})});for(var g=0,f=z.attribList.length;g",z.tagName="",z.state=N.SCRIPT;return}b(z,"onscript",z.script),z.script=""}var L=z.tags.length,u=z.tagName;if(!z.strict)u=u[z.looseCase]();var h=u;while(L--)if(z.tags[L].name!==h)i(z,"Unexpected close tag");else break;if(L<0){i(z,"Unmatched closing tag: "+z.tagName),z.textNode+="",z.state=N.TEXT;return}z.tagName=u;var Z0=z.tags.length;while(Z0-- >L){var g=z.tag=z.tags.pop();z.tagName=z.tag.name,b(z,"onclosetag",z.tagName);var f={};for(var R in g.ns)f[R]=g.ns[R];var p=z.tags[z.tags.length-1]||z;if(z.opt.xmlns&&g.ns!==p.ns)Object.keys(g.ns).forEach(function(k){var V=g.ns[k];b(z,"onclosenamespace",{prefix:k,uri:V})})}if(L===0)z.closedRoot=!0;z.tagName=z.attribValue=z.attribName="",z.attribList.length=0,z.state=N.TEXT}function n(z){var L=z.entity,u=L.toLowerCase(),h,Z0="";if(z.ENTITIES[L])return z.ENTITIES[L];if(z.ENTITIES[u])return z.ENTITIES[u];if(L=u,L.charAt(0)==="#")if(L.charAt(1)==="x")L=L.slice(2),h=parseInt(L,16),Z0=h.toString(16);else L=L.slice(1),h=parseInt(L,10),Z0=h.toString(10);if(L=L.replace(/^0+/,""),isNaN(h)||Z0.toLowerCase()!==L)return i(z,"Invalid character entity"),"&"+z.entity+";";return String.fromCodePoint(h)}function o(z,L){if(L==="<")z.state=N.OPEN_WAKA,z.startTagPosition=z.position;else if(!S(L))i(z,"Non-whitespace before first tag."),z.textNode=L,z.state=N.TEXT}function Y0(z,L){var u="";if(L")b(L,"onsgmldeclaration",L.sgmlDecl),L.sgmlDecl="",L.state=N.TEXT;else if(H(h))L.state=N.SGML_DECL_QUOTED,L.sgmlDecl+=h;else L.sgmlDecl+=h;continue;case N.SGML_DECL_QUOTED:if(h===L.q)L.state=N.SGML_DECL,L.q="";L.sgmlDecl+=h;continue;case N.DOCTYPE:if(h===">")L.state=N.TEXT,b(L,"ondoctype",L.doctype),L.doctype=!0;else if(L.doctype+=h,h==="[")L.state=N.DOCTYPE_DTD;else if(H(h))L.state=N.DOCTYPE_QUOTED,L.q=h;continue;case N.DOCTYPE_QUOTED:if(L.doctype+=h,h===L.q)L.q="",L.state=N.DOCTYPE;continue;case N.DOCTYPE_DTD:if(L.doctype+=h,h==="]")L.state=N.DOCTYPE;else if(H(h))L.state=N.DOCTYPE_DTD_QUOTED,L.q=h;continue;case N.DOCTYPE_DTD_QUOTED:if(L.doctype+=h,h===L.q)L.state=N.DOCTYPE_DTD,L.q="";continue;case N.COMMENT:if(h==="-")L.state=N.COMMENT_ENDING;else L.comment+=h;continue;case N.COMMENT_ENDING:if(h==="-"){if(L.state=N.COMMENT_ENDED,L.comment=T(L.opt,L.comment),L.comment)b(L,"oncomment",L.comment);L.comment=""}else L.comment+="-"+h,L.state=N.COMMENT;continue;case N.COMMENT_ENDED:if(h!==">")i(L,"Malformed comment"),L.comment+="--"+h,L.state=N.COMMENT;else L.state=N.TEXT;continue;case N.CDATA:if(h==="]")L.state=N.CDATA_ENDING;else L.cdata+=h;continue;case N.CDATA_ENDING:if(h==="]")L.state=N.CDATA_ENDING_2;else L.cdata+="]"+h,L.state=N.CDATA;continue;case N.CDATA_ENDING_2:if(h===">"){if(L.cdata)b(L,"oncdata",L.cdata);b(L,"onclosecdata"),L.cdata="",L.state=N.TEXT}else if(h==="]")L.cdata+="]";else L.cdata+="]]"+h,L.state=N.CDATA;continue;case N.PROC_INST:if(h==="?")L.state=N.PROC_INST_ENDING;else if(S(h))L.state=N.PROC_INST_BODY;else L.procInstName+=h;continue;case N.PROC_INST_BODY:if(!L.procInstBody&&S(h))continue;else if(h==="?")L.state=N.PROC_INST_ENDING;else L.procInstBody+=h;continue;case N.PROC_INST_ENDING:if(h===">")b(L,"onprocessinginstruction",{name:L.procInstName,body:L.procInstBody}),L.procInstName=L.procInstBody="",L.state=N.TEXT;else L.procInstBody+="?"+h,L.state=N.PROC_INST_BODY;continue;case N.OPEN_TAG:if($(C,h))L.tagName+=h;else if(V0(L),h===">")r(L);else if(h==="/")L.state=N.OPEN_TAG_SLASH;else{if(!S(h))i(L,"Invalid character in tag name");L.state=N.ATTRIB}continue;case N.OPEN_TAG_SLASH:if(h===">")r(L,!0),y(L);else i(L,"Forward-slash in opening tag not followed by >"),L.state=N.ATTRIB;continue;case N.ATTRIB:if(S(h))continue;else if(h===">")r(L);else if(h==="/")L.state=N.OPEN_TAG_SLASH;else if($(E,h))L.attribName=h,L.attribValue="",L.state=N.ATTRIB_NAME;else i(L,"Invalid attribute name");continue;case N.ATTRIB_NAME:if(h==="=")L.state=N.ATTRIB_VALUE;else if(h===">")i(L,"Attribute without value"),L.attribValue=L.attribName,G0(L),r(L);else if(S(h))L.state=N.ATTRIB_NAME_SAW_WHITE;else if($(C,h))L.attribName+=h;else i(L,"Invalid attribute name");continue;case N.ATTRIB_NAME_SAW_WHITE:if(h==="=")L.state=N.ATTRIB_VALUE;else if(S(h))continue;else if(i(L,"Attribute without value"),L.tag.attributes[L.attribName]="",L.attribValue="",b(L,"onattribute",{name:L.attribName,value:""}),L.attribName="",h===">")r(L);else if($(E,h))L.attribName=h,L.state=N.ATTRIB_NAME;else i(L,"Invalid attribute name"),L.state=N.ATTRIB;continue;case N.ATTRIB_VALUE:if(S(h))continue;else if(H(h))L.q=h,L.state=N.ATTRIB_VALUE_QUOTED;else i(L,"Unquoted attribute value"),L.state=N.ATTRIB_VALUE_UNQUOTED,L.attribValue=h;continue;case N.ATTRIB_VALUE_QUOTED:if(h!==L.q){if(h==="&")L.state=N.ATTRIB_VALUE_ENTITY_Q;else L.attribValue+=h;continue}G0(L),L.q="",L.state=N.ATTRIB_VALUE_CLOSED;continue;case N.ATTRIB_VALUE_CLOSED:if(S(h))L.state=N.ATTRIB;else if(h===">")r(L);else if(h==="/")L.state=N.OPEN_TAG_SLASH;else if($(E,h))i(L,"No whitespace between attributes"),L.attribName=h,L.attribValue="",L.state=N.ATTRIB_NAME;else i(L,"Invalid attribute name");continue;case N.ATTRIB_VALUE_UNQUOTED:if(!X(h)){if(h==="&")L.state=N.ATTRIB_VALUE_ENTITY_U;else L.attribValue+=h;continue}if(G0(L),h===">")r(L);else L.state=N.ATTRIB;continue;case N.CLOSE_TAG:if(!L.tagName)if(S(h))continue;else if(x(E,h))if(L.script)L.script+="")y(L);else if($(C,h))L.tagName+=h;else if(L.script)L.script+="")y(L);else i(L,"Invalid characters in closing tag");continue;case N.TEXT_ENTITY:case N.ATTRIB_VALUE_ENTITY_Q:case N.ATTRIB_VALUE_ENTITY_U:var f,R;switch(L.state){case N.TEXT_ENTITY:f=N.TEXT,R="textNode";break;case N.ATTRIB_VALUE_ENTITY_Q:f=N.ATTRIB_VALUE_QUOTED,R="attribValue";break;case N.ATTRIB_VALUE_ENTITY_U:f=N.ATTRIB_VALUE_UNQUOTED,R="attribValue";break}if(h===";")L[R]+=n(L),L.entity="",L.state=f;else if($(L.entity.length?v:j,h))L.entity+=h;else i(L,"Invalid character in entity name"),L[R]+="&"+L.entity+h,L.entity="",L.state=f;continue;default:throw Error(L,"Unknown state: "+L.state)}}if(L.position>=L.bufferCheckPosition)Q(L);return L}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */if(!String.fromCodePoint)(function(){var z=String.fromCharCode,L=Math.floor,u=function(){var h=16384,Z0=[],g,f,R=-1,p=arguments.length;if(!p)return"";var k="";while(++R1114111||L(V)!==V)throw RangeError("Invalid code point: "+V);if(V<=65535)Z0.push(V);else V-=65536,g=(V>>10)+55296,f=V%1024+56320,Z0.push(g,f);if(R+1===p||Z0.length>h)k+=z.apply(null,Z0),Z0.length=0}return k};if(Object.defineProperty)Object.defineProperty(String,"fromCodePoint",{value:u,configurable:!0,writable:!0});else String.fromCodePoint=u})()})(typeof B>"u"?B.sax={}:B)}),x8=R0((B,U)=>{U.exports={isArray:function(G){if(Array.isArray)return Array.isArray(G);return Object.prototype.toString.call(G)==="[object Array]"}}}),_8=R0((B,U)=>{var G=x8().isArray;U.exports={copyOptions:function(Y){var Q,K={};for(Q in Y)if(Y.hasOwnProperty(Q))K[Q]=Y[Q];return K},ensureFlagExists:function(Y,Q){if(!(Y in Q)||typeof Q[Y]!=="boolean")Q[Y]=!1},ensureSpacesExists:function(Y){if(!("spaces"in Y)||typeof Y.spaces!=="number"&&typeof Y.spaces!=="string")Y.spaces=0},ensureAlwaysArrayExists:function(Y){if(!("alwaysArray"in Y)||typeof Y.alwaysArray!=="boolean"&&!G(Y.alwaysArray))Y.alwaysArray=!1},ensureKeyExists:function(Y,Q){if(!(Y+"Key"in Q)||typeof Q[Y+"Key"]!=="string")Q[Y+"Key"]=Q.compact?"_"+Y:Y},checkFnExists:function(Y,Q){return Y+"Fn"in Q}}}),DB=R0((B,U)=>{var G=GG(),Y={on:function(){},parse:function(){}},Q=_8(),K=x8().isArray,Z,J=!0,M;function W(H){return Z=Q.copyOptions(H),Q.ensureFlagExists("ignoreDeclaration",Z),Q.ensureFlagExists("ignoreInstruction",Z),Q.ensureFlagExists("ignoreAttributes",Z),Q.ensureFlagExists("ignoreText",Z),Q.ensureFlagExists("ignoreComment",Z),Q.ensureFlagExists("ignoreCdata",Z),Q.ensureFlagExists("ignoreDoctype",Z),Q.ensureFlagExists("compact",Z),Q.ensureFlagExists("alwaysChildren",Z),Q.ensureFlagExists("addParent",Z),Q.ensureFlagExists("trim",Z),Q.ensureFlagExists("nativeType",Z),Q.ensureFlagExists("nativeTypeAttributes",Z),Q.ensureFlagExists("sanitize",Z),Q.ensureFlagExists("instructionHasAttributes",Z),Q.ensureFlagExists("captureSpacesBetweenElements",Z),Q.ensureAlwaysArrayExists(Z),Q.ensureKeyExists("declaration",Z),Q.ensureKeyExists("instruction",Z),Q.ensureKeyExists("attributes",Z),Q.ensureKeyExists("text",Z),Q.ensureKeyExists("comment",Z),Q.ensureKeyExists("cdata",Z),Q.ensureKeyExists("doctype",Z),Q.ensureKeyExists("type",Z),Q.ensureKeyExists("name",Z),Q.ensureKeyExists("elements",Z),Q.ensureKeyExists("parent",Z),Q.checkFnExists("doctype",Z),Q.checkFnExists("instruction",Z),Q.checkFnExists("cdata",Z),Q.checkFnExists("comment",Z),Q.checkFnExists("text",Z),Q.checkFnExists("instructionName",Z),Q.checkFnExists("elementName",Z),Q.checkFnExists("attributeName",Z),Q.checkFnExists("attributeValue",Z),Q.checkFnExists("attributes",Z),Z}function I(H){var X=Number(H);if(!isNaN(X))return X;var $=H.toLowerCase();if($==="true")return!0;else if($==="false")return!1;return H}function F(H,X){var $;if(Z.compact){if(!M[Z[H+"Key"]]&&(K(Z.alwaysArray)?Z.alwaysArray.indexOf(Z[H+"Key"])!==-1:Z.alwaysArray))M[Z[H+"Key"]]=[];if(M[Z[H+"Key"]]&&!K(M[Z[H+"Key"]]))M[Z[H+"Key"]]=[M[Z[H+"Key"]]];if(H+"Fn"in Z&&typeof X==="string")X=Z[H+"Fn"](X,M);if(H==="instruction"&&(("instructionFn"in Z)||("instructionNameFn"in Z))){for($ in X)if(X.hasOwnProperty($))if("instructionFn"in Z)X[$]=Z.instructionFn(X[$],$,M);else{var x=X[$];delete X[$],X[Z.instructionNameFn($,x,M)]=x}}if(K(M[Z[H+"Key"]]))M[Z[H+"Key"]].push(X);else M[Z[H+"Key"]]=X}else{if(!M[Z.elementsKey])M[Z.elementsKey]=[];var N={};if(N[Z.typeKey]=H,H==="instruction"){for($ in X)if(X.hasOwnProperty($))break;if(N[Z.nameKey]="instructionNameFn"in Z?Z.instructionNameFn($,X,M):$,Z.instructionHasAttributes){if(N[Z.attributesKey]=X[$][Z.attributesKey],"instructionFn"in Z)N[Z.attributesKey]=Z.instructionFn(N[Z.attributesKey],$,M)}else{if("instructionFn"in Z)X[$]=Z.instructionFn(X[$],$,M);N[Z.instructionKey]=X[$]}}else{if(H+"Fn"in Z)X=Z[H+"Fn"](X,M);N[Z[H+"Key"]]=X}if(Z.addParent)N[Z.parentKey]=M;M[Z.elementsKey].push(N)}}function D(H){if("attributesFn"in Z&&H)H=Z.attributesFn(H,M);if((Z.trim||("attributeValueFn"in Z)||("attributeNameFn"in Z)||Z.nativeTypeAttributes)&&H){var X;for(X in H)if(H.hasOwnProperty(X)){if(Z.trim)H[X]=H[X].trim();if(Z.nativeTypeAttributes)H[X]=I(H[X]);if("attributeValueFn"in Z)H[X]=Z.attributeValueFn(H[X],X,M);if("attributeNameFn"in Z){var $=H[X];delete H[X],H[Z.attributeNameFn(X,H[X],M)]=$}}}return H}function w(H){var X={};if(H.body&&(H.name.toLowerCase()==="xml"||Z.instructionHasAttributes)){var $=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g,x;while((x=$.exec(H.body))!==null)X[x[1]]=x[2]||x[3]||x[4];X=D(X)}if(H.name.toLowerCase()==="xml"){if(Z.ignoreDeclaration)return;if(M[Z.declarationKey]={},Object.keys(X).length)M[Z.declarationKey][Z.attributesKey]=X;if(Z.addParent)M[Z.declarationKey][Z.parentKey]=M}else{if(Z.ignoreInstruction)return;if(Z.trim)H.body=H.body.trim();var N={};if(Z.instructionHasAttributes&&Object.keys(X).length)N[H.name]={},N[H.name][Z.attributesKey]=X;else N[H.name]=H.body;F("instruction",N)}}function P(H,X){var $;if(typeof H==="object")X=H.attributes,H=H.name;if(X=D(X),"elementNameFn"in Z)H=Z.elementNameFn(H,M);if(Z.compact){if($={},!Z.ignoreAttributes&&X&&Object.keys(X).length){$[Z.attributesKey]={};var x;for(x in X)if(X.hasOwnProperty(x))$[Z.attributesKey][x]=X[x]}if(!(H in M)&&(K(Z.alwaysArray)?Z.alwaysArray.indexOf(H)!==-1:Z.alwaysArray))M[H]=[];if(M[H]&&!K(M[H]))M[H]=[M[H]];if(K(M[H]))M[H].push($);else M[H]=$}else{if(!M[Z.elementsKey])M[Z.elementsKey]=[];if($={},$[Z.typeKey]="element",$[Z.nameKey]=H,!Z.ignoreAttributes&&X&&Object.keys(X).length)$[Z.attributesKey]=X;if(Z.alwaysChildren)$[Z.elementsKey]=[];M[Z.elementsKey].push($)}$[Z.parentKey]=M,M=$}function A(H){if(Z.ignoreText)return;if(!H.trim()&&!Z.captureSpacesBetweenElements)return;if(Z.trim)H=H.trim();if(Z.nativeType)H=I(H);if(Z.sanitize)H=H.replace(/&/g,"&").replace(//g,">");F("text",H)}function E(H){if(Z.ignoreComment)return;if(Z.trim)H=H.trim();F("comment",H)}function C(H){var X=M[Z.parentKey];if(!Z.addParent)delete M[Z.parentKey];M=X}function j(H){if(Z.ignoreCdata)return;if(Z.trim)H=H.trim();F("cdata",H)}function v(H){if(Z.ignoreDoctype)return;if(H=H.replace(/^ /,""),Z.trim)H=H.trim();F("doctype",H)}function S(H){H.note=H}U.exports=function(H,X){var $=J?G.parser(!0,{}):$=new Y.Parser("UTF-8"),x={};if(M=x,Z=W(X),J)$.opt={strictEntities:!0},$.onopentag=P,$.ontext=A,$.oncomment=E,$.onclosetag=C,$.onerror=S,$.oncdata=j,$.ondoctype=v,$.onprocessinginstruction=w;else $.on("startElement",P),$.on("text",A),$.on("comment",E),$.on("endElement",C),$.on("error",S);if(J)$.write(H).close();else if(!$.parse(H))throw Error("XML parsing error: "+$.getError());if(x[Z.elementsKey]){var N=x[Z.elementsKey];delete x[Z.elementsKey],x[Z.elementsKey]=N,delete x.text}return x}}),YG=R0((B,U)=>{var G=_8(),Y=DB();function Q(K){var Z=G.copyOptions(K);return G.ensureSpacesExists(Z),Z}U.exports=function(K,Z){var J=Q(Z),M=Y(K,J),W,I="compact"in J&&J.compact?"_parent":"parent";if("addParent"in J&&J.addParent)W=JSON.stringify(M,function(F,D){return F===I?"_":D},J.spaces);else W=JSON.stringify(M,null,J.spaces);return W.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}}),CB=R0((B,U)=>{var G=_8(),Y=x8().isArray,Q,K;function Z(H){var X=G.copyOptions(H);if(G.ensureFlagExists("ignoreDeclaration",X),G.ensureFlagExists("ignoreInstruction",X),G.ensureFlagExists("ignoreAttributes",X),G.ensureFlagExists("ignoreText",X),G.ensureFlagExists("ignoreComment",X),G.ensureFlagExists("ignoreCdata",X),G.ensureFlagExists("ignoreDoctype",X),G.ensureFlagExists("compact",X),G.ensureFlagExists("indentText",X),G.ensureFlagExists("indentCdata",X),G.ensureFlagExists("indentAttributes",X),G.ensureFlagExists("indentInstruction",X),G.ensureFlagExists("fullTagEmptyElement",X),G.ensureFlagExists("noQuotesForNativeAttributes",X),G.ensureSpacesExists(X),typeof X.spaces==="number")X.spaces=Array(X.spaces+1).join(" ");return G.ensureKeyExists("declaration",X),G.ensureKeyExists("instruction",X),G.ensureKeyExists("attributes",X),G.ensureKeyExists("text",X),G.ensureKeyExists("comment",X),G.ensureKeyExists("cdata",X),G.ensureKeyExists("doctype",X),G.ensureKeyExists("type",X),G.ensureKeyExists("name",X),G.ensureKeyExists("elements",X),G.checkFnExists("doctype",X),G.checkFnExists("instruction",X),G.checkFnExists("cdata",X),G.checkFnExists("comment",X),G.checkFnExists("text",X),G.checkFnExists("instructionName",X),G.checkFnExists("elementName",X),G.checkFnExists("attributeName",X),G.checkFnExists("attributeValue",X),G.checkFnExists("attributes",X),G.checkFnExists("fullTagEmptyElement",X),X}function J(H,X,$){return(!$&&H.spaces?` -`:"")+Array(X+1).join(H.spaces)}function M(H,X,$){if(X.ignoreAttributes)return"";if("attributesFn"in X)H=X.attributesFn(H,K,Q);var x,N,a,U0,b=[];for(x in H)if(H.hasOwnProperty(x)&&H[x]!==null&&H[x]!==void 0)U0=X.noQuotesForNativeAttributes&&typeof H[x]!=="string"?"":'"',N=""+H[x],N=N.replace(/"/g,"""),a="attributeNameFn"in X?X.attributeNameFn(x,N,K,Q):x,b.push(X.spaces&&X.indentAttributes?J(X,$+1,!1):" "),b.push(a+"="+U0+("attributeValueFn"in X?X.attributeValueFn(N,x,K,Q):N)+U0);if(H&&Object.keys(H).length&&X.spaces&&X.indentAttributes)b.push(J(X,$,!1));return b.join("")}function W(H,X,$){return Q=H,K="xml",X.ignoreDeclaration?"":""}function I(H,X,$){if(X.ignoreInstruction)return"";var x;for(x in H)if(H.hasOwnProperty(x))break;var N="instructionNameFn"in X?X.instructionNameFn(x,H[x],K,Q):x;if(typeof H[x]==="object")return Q=H,K=N,"";else{var a=H[x]?H[x]:"";if("instructionFn"in X)a=X.instructionFn(a,x,K,Q);return""}}function F(H,X){return X.ignoreComment?"":""}function D(H,X){return X.ignoreCdata?"":"","]]]]>"))+"]]>"}function w(H,X){return X.ignoreDoctype?"":""}function P(H,X){if(X.ignoreText)return"";return H=""+H,H=H.replace(/&/g,"&"),H=H.replace(/&/g,"&").replace(//g,">"),"textFn"in X?X.textFn(H,K,Q):H}function A(H,X){var $;if(H.elements&&H.elements.length)for($=0;$"),H[X.elementsKey]&&H[X.elementsKey].length)x.push(C(H[X.elementsKey],X,$+1)),Q=H,K=H.name;x.push(X.spaces&&A(H,X)?` -`+Array($+1).join(X.spaces):""),x.push("")}else x.push("/>");return x.join("")}function C(H,X,$,x){return H.reduce(function(N,a){var U0=J(X,$,x&&!N);switch(a.type){case"element":return N+U0+E(a,X,$);case"comment":return N+U0+F(a[X.commentKey],X);case"doctype":return N+U0+w(a[X.doctypeKey],X);case"cdata":return N+(X.indentCdata?U0:"")+D(a[X.cdataKey],X);case"text":return N+(X.indentText?U0:"")+P(a[X.textKey],X);case"instruction":var b={};return b[a[X.nameKey]]=a[X.attributesKey]?a:a[X.instructionKey],N+(X.indentInstruction?U0:"")+I(b,X,$)}},"")}function j(H,X,$){var x;for(x in H)if(H.hasOwnProperty(x))switch(x){case X.parentKey:case X.attributesKey:break;case X.textKey:if(X.indentText||$)return!0;break;case X.cdataKey:if(X.indentCdata||$)return!0;break;case X.instructionKey:if(X.indentInstruction||$)return!0;break;case X.doctypeKey:case X.commentKey:return!0;default:return!0}return!1}function v(H,X,$,x,N){Q=H,K=X;var a="elementNameFn"in $?$.elementNameFn(X,H):X;if(typeof H>"u"||H===null||H==="")return"fullTagEmptyElementFn"in $&&$.fullTagEmptyElementFn(X,H)||$.fullTagEmptyElement?"<"+a+">":"<"+a+"/>";var U0=[];if(X){if(U0.push("<"+a),typeof H!=="object")return U0.push(">"+P(H,$)+""),U0.join("");if(H[$.attributesKey])U0.push(M(H[$.attributesKey],$,x));var b=j(H,$,!0)||H[$.attributesKey]&&H[$.attributesKey]["xml:space"]==="preserve";if(!b)if("fullTagEmptyElementFn"in $)b=$.fullTagEmptyElementFn(X,H);else b=$.fullTagEmptyElement;if(b)U0.push(">");else return U0.push("/>"),U0.join("")}if(U0.push(S(H,$,x+1,!1)),Q=H,K=X,X)U0.push((N?J($,x,!1):"")+"");return U0.join("")}function S(H,X,$,x){var N,a,U0,b=[];for(a in H)if(H.hasOwnProperty(a)){U0=Y(H[a])?H[a]:[H[a]];for(N=0;N{var G=CB();U.exports=function(Y,Q){if(Y instanceof Buffer)Y=Y.toString();var K=null;if(typeof Y==="string")try{K=JSON.parse(Y)}catch(Z){throw Error("The JSON structure is invalid")}else K=Y;return G(K,Q)}}),_1=R0((B,U)=>{U.exports={xml2js:DB(),xml2json:YG(),js2xml:CB(),json2xml:ZG()}})(),h1=(B)=>{switch(B.type){case void 0:case"element":let U=new kB(B.name,B.attributes),G=B.elements||[];for(let Y of G){let Q=h1(Y);if(Q!==void 0)U.push(Q)}return U;case"text":return B.text;default:return}},QG=class extends F0{},kB=class extends t{static fromXmlString(B){return h1((0,_1.xml2js)(B,{compact:!1}))}constructor(B,U){super(B);if(U)this.root.push(new QG(U))}push(B){this.root.push(B)}},$B=class extends t{constructor(B){super("");e(this,"_attr",void 0),this._attr=B}prepForXml(B){return{_attr:this._attr}}},JG="",h8=class extends t{constructor(B,U){super(B);if(U)this.root=U.root}},D0=(B)=>{if(isNaN(B))throw Error(`Invalid value '${B}' specified. Must be an integer.`);return Math.floor(B)},q1=(B)=>{let U=D0(B);if(U<0)throw Error(`Invalid value '${B}' specified. Must be a positive integer.`);return U},u1=(B,U)=>{let G=U*2;if(B.length!==G||isNaN(Number(`0x${B}`)))throw Error(`Invalid hex value '${B}'. Expected ${G} digit hex value`);return B},KG=(B)=>u1(B,4),SB=(B)=>u1(B,2),H8=(B)=>u1(B,1),M1=(B)=>{let U=B.slice(-2),G=B.substring(0,B.length-2);return`${Number(G)}${U}`},u8=(B)=>{let U=M1(B);if(parseFloat(U)<0)throw Error(`Invalid value '${U}' specified. Expected a positive number.`);return U},C2=(B)=>{if(B==="auto")return B;return u1(B.charAt(0)==="#"?B.substring(1):B,3)},t0=(B)=>typeof B==="string"?M1(B):D0(B),bB=(B)=>typeof B==="string"?u8(B):q1(B),VG=(B)=>typeof B==="string"?M1(B):D0(B),E0=(B)=>typeof B==="string"?u8(B):q1(B),vB=(B)=>{let U=B.substring(0,B.length-1);return`${Number(U)}%`},d8=(B)=>{if(typeof B==="number")return D0(B);if(B.slice(-1)==="%")return vB(B);return M1(B)},yB=q1,gB=q1,fB=(B)=>B.toISOString(),M0=class extends t{constructor(B,U=!0){super(B);if(U!==!0)this.root.push(new C0({val:U}))}},E1=class extends t{constructor(B,U){super(B);this.root.push(new C0({val:bB(U)}))}},S0=class extends t{},M2=class extends t{constructor(B,U){super(B);this.root.push(new C0({val:U}))}},f2=(B,U)=>new X0({name:B,attributes:{value:{key:"w:val",value:U}}}),_2=class extends t{constructor(B,U){super(B);this.root.push(new C0({val:U}))}},qG=class extends t{constructor(B,U){super(B);this.root.push(new C0({val:U}))}},O2=class extends t{constructor(B,U){super(B);this.root.push(U)}},X0=class extends t{constructor({name:B,attributes:U,children:G}){super(B);if(U)this.root.push(new k8(U));if(G)this.root.push(...G)}},c0={START:"start",CENTER:"center",END:"end",BOTH:"both",MEDIUM_KASHIDA:"mediumKashida",DISTRIBUTE:"distribute",NUM_TAB:"numTab",HIGH_KASHIDA:"highKashida",LOW_KASHIDA:"lowKashida",THAI_DISTRIBUTE:"thaiDistribute",LEFT:"left",RIGHT:"right",JUSTIFIED:"both"},c8=(B)=>new X0({name:"w:jc",attributes:{val:{key:"w:val",value:B}}}),A0=(B,{color:U,size:G,space:Y,style:Q})=>new X0({name:B,attributes:{style:{key:"w:val",value:Q},color:{key:"w:color",value:U===void 0?void 0:C2(U)},size:{key:"w:sz",value:G===void 0?void 0:yB(G)},space:{key:"w:space",value:Y===void 0?void 0:gB(Y)}}}),d1={SINGLE:"single",DASH_DOT_STROKED:"dashDotStroked",DASHED:"dashed",DASH_SMALL_GAP:"dashSmallGap",DOT_DASH:"dotDash",DOT_DOT_DASH:"dotDotDash",DOTTED:"dotted",DOUBLE:"double",DOUBLE_WAVE:"doubleWave",INSET:"inset",NIL:"nil",NONE:"none",OUTSET:"outset",THICK:"thick",THICK_THIN_LARGE_GAP:"thickThinLargeGap",THICK_THIN_MEDIUM_GAP:"thickThinMediumGap",THICK_THIN_SMALL_GAP:"thickThinSmallGap",THIN_THICK_LARGE_GAP:"thinThickLargeGap",THIN_THICK_MEDIUM_GAP:"thinThickMediumGap",THIN_THICK_SMALL_GAP:"thinThickSmallGap",THIN_THICK_THIN_LARGE_GAP:"thinThickThinLargeGap",THIN_THICK_THIN_MEDIUM_GAP:"thinThickThinMediumGap",THIN_THICK_THIN_SMALL_GAP:"thinThickThinSmallGap",THREE_D_EMBOSS:"threeDEmboss",THREE_D_ENGRAVE:"threeDEngrave",TRIPLE:"triple",WAVE:"wave"},xB=class extends R2{constructor(B){super("w:pBdr");if(B.top)this.root.push(A0("w:top",B.top));if(B.bottom)this.root.push(A0("w:bottom",B.bottom));if(B.left)this.root.push(A0("w:left",B.left));if(B.right)this.root.push(A0("w:right",B.right));if(B.between)this.root.push(A0("w:between",B.between))}},_B=class extends t{constructor(){super("w:pBdr");let B=A0("w:bottom",{color:"auto",space:1,style:d1.SINGLE,size:6});this.root.push(B)}},hB=({start:B,end:U,left:G,right:Y,hanging:Q,firstLine:K,firstLineChars:Z})=>new X0({name:"w:ind",attributes:{start:{key:"w:start",value:B===void 0?void 0:t0(B)},end:{key:"w:end",value:U===void 0?void 0:t0(U)},left:{key:"w:left",value:G===void 0?void 0:t0(G)},right:{key:"w:right",value:Y===void 0?void 0:t0(Y)},hanging:{key:"w:hanging",value:Q===void 0?void 0:E0(Q)},firstLine:{key:"w:firstLine",value:K===void 0?void 0:E0(K)},firstLineChars:{key:"w:firstLineChars",value:Z===void 0?void 0:D0(Z)}}}),uB=()=>new X0({name:"w:br"}),m8={BEGIN:"begin",END:"end",SEPARATE:"separate"},l8=(B,U)=>new X0({name:"w:fldChar",attributes:{type:{key:"w:fldCharType",value:B},dirty:{key:"w:dirty",value:U}}}),e0=(B)=>l8(m8.BEGIN,B),q2=(B)=>l8(m8.SEPARATE,B),B2=(B)=>l8(m8.END,B),MG={CENTER:"center",INSIDE:"inside",LEFT:"left",OUTSIDE:"outside",RIGHT:"right"},XG={BOTTOM:"bottom",CENTER:"center",INSIDE:"inside",OUTSIDE:"outside",TOP:"top"},RG={DECIMAL:"decimal",UPPER_ROMAN:"upperRoman",LOWER_ROMAN:"lowerRoman",UPPER_LETTER:"upperLetter",LOWER_LETTER:"lowerLetter",ORDINAL:"ordinal",CARDINAL_TEXT:"cardinalText",ORDINAL_TEXT:"ordinalText",HEX:"hex",CHICAGO:"chicago",IDEOGRAPH_DIGITAL:"ideographDigital",JAPANESE_COUNTING:"japaneseCounting",AIUEO:"aiueo",IROHA:"iroha",DECIMAL_FULL_WIDTH:"decimalFullWidth",DECIMAL_HALF_WIDTH:"decimalHalfWidth",JAPANESE_LEGAL:"japaneseLegal",JAPANESE_DIGITAL_TEN_THOUSAND:"japaneseDigitalTenThousand",DECIMAL_ENCLOSED_CIRCLE:"decimalEnclosedCircle",DECIMAL_FULL_WIDTH_2:"decimalFullWidth2",AIUEO_FULL_WIDTH:"aiueoFullWidth",IROHA_FULL_WIDTH:"irohaFullWidth",DECIMAL_ZERO:"decimalZero",BULLET:"bullet",GANADA:"ganada",CHOSUNG:"chosung",DECIMAL_ENCLOSED_FULL_STOP:"decimalEnclosedFullstop",DECIMAL_ENCLOSED_PAREN:"decimalEnclosedParen",DECIMAL_ENCLOSED_CIRCLE_CHINESE:"decimalEnclosedCircleChinese",IDEOGRAPH_ENCLOSED_CIRCLE:"ideographEnclosedCircle",IDEOGRAPH_TRADITIONAL:"ideographTraditional",IDEOGRAPH_ZODIAC:"ideographZodiac",IDEOGRAPH_ZODIAC_TRADITIONAL:"ideographZodiacTraditional",TAIWANESE_COUNTING:"taiwaneseCounting",IDEOGRAPH_LEGAL_TRADITIONAL:"ideographLegalTraditional",TAIWANESE_COUNTING_THOUSAND:"taiwaneseCountingThousand",TAIWANESE_DIGITAL:"taiwaneseDigital",CHINESE_COUNTING:"chineseCounting",CHINESE_LEGAL_SIMPLIFIED:"chineseLegalSimplified",CHINESE_COUNTING_TEN_THOUSAND:"chineseCountingThousand",KOREAN_DIGITAL:"koreanDigital",KOREAN_COUNTING:"koreanCounting",KOREAN_LEGAL:"koreanLegal",KOREAN_DIGITAL_2:"koreanDigital2",VIETNAMESE_COUNTING:"vietnameseCounting",RUSSIAN_LOWER:"russianLower",RUSSIAN_UPPER:"russianUpper",NONE:"none",NUMBER_IN_DASH:"numberInDash",HEBREW_1:"hebrew1",HEBREW_2:"hebrew2",ARABIC_ALPHA:"arabicAlpha",ARABIC_ABJAD:"arabicAbjad",HINDI_VOWELS:"hindiVowels",HINDI_CONSONANTS:"hindiConsonants",HINDI_NUMBERS:"hindiNumbers",HINDI_COUNTING:"hindiCounting",THAI_LETTERS:"thaiLetters",THAI_NUMBERS:"thaiNumbers",THAI_COUNTING:"thaiCounting",BAHT_TEXT:"bahtText",DOLLAR_TEXT:"dollarText"},x0={DEFAULT:"default",PRESERVE:"preserve"},_0=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{space:"xml:space"})}},LG=class extends t{constructor(){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("PAGE")}},IG=class extends t{constructor(){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("NUMPAGES")}},OG=class extends t{constructor(){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("SECTIONPAGES")}},FG=class extends t{constructor(){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("SECTION")}},X1=({fill:B,color:U,type:G})=>new X0({name:"w:shd",attributes:{fill:{key:"w:fill",value:B===void 0?void 0:C2(B)},color:{key:"w:color",value:U===void 0?void 0:C2(U)},type:{key:"w:val",value:G}}}),HG={CLEAR:"clear",DIAGONAL_CROSS:"diagCross",DIAGONAL_STRIPE:"diagStripe",HORIZONTAL_CROSS:"horzCross",HORIZONTAL_STRIPE:"horzStripe",NIL:"nil",PERCENT_5:"pct5",PERCENT_10:"pct10",PERCENT_12:"pct12",PERCENT_15:"pct15",PERCENT_20:"pct20",PERCENT_25:"pct25",PERCENT_30:"pct30",PERCENT_35:"pct35",PERCENT_37:"pct37",PERCENT_40:"pct40",PERCENT_45:"pct45",PERCENT_50:"pct50",PERCENT_55:"pct55",PERCENT_60:"pct60",PERCENT_62:"pct62",PERCENT_65:"pct65",PERCENT_70:"pct70",PERCENT_75:"pct75",PERCENT_80:"pct80",PERCENT_85:"pct85",PERCENT_87:"pct87",PERCENT_90:"pct90",PERCENT_95:"pct95",REVERSE_DIAGONAL_STRIPE:"reverseDiagStripe",SOLID:"solid",THIN_DIAGONAL_CROSS:"thinDiagCross",THIN_DIAGONAL_STRIPE:"thinDiagStripe",THIN_HORIZONTAL_CROSS:"thinHorzCross",THIN_REVERSE_DIAGONAL_STRIPE:"thinReverseDiagStripe",THIN_VERTICAL_STRIPE:"thinVertStripe",VERTICAL_STRIPE:"vertStripe"},b0=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id",author:"w:author",date:"w:date"})}},WG=class extends t{constructor(B){super("w:del");this.root.push(new b0({id:B.id,author:B.author,date:B.date}))}},PG=class extends t{constructor(B){super("w:ins");this.root.push(new b0({id:B.id,author:B.author,date:B.date}))}},a8={DOT:"dot"},p8=(B=a8.DOT)=>new X0({name:"w:em",attributes:{val:{key:"w:val",value:B}}}),wG=()=>p8(a8.DOT),AG=class extends t{constructor(B){super("w:spacing");this.root.push(new C0({val:t0(B)}))}},jG=class extends t{constructor(B){super("w:color");this.root.push(new C0({val:C2(B)}))}},NG=class extends t{constructor(B){super("w:highlight");this.root.push(new C0({val:B}))}},zG=class extends t{constructor(B){super("w:highlightCs");this.root.push(new C0({val:B}))}},EG=(B)=>new X0({name:"w:lang",attributes:{value:{key:"w:val",value:B.value},eastAsia:{key:"w:eastAsia",value:B.eastAsia},bidirectional:{key:"w:bidi",value:B.bidirectional}}}),T1=(B,U)=>{if(typeof B==="string"){let Y=B;return new X0({name:"w:rFonts",attributes:{ascii:{key:"w:ascii",value:Y},cs:{key:"w:cs",value:Y},eastAsia:{key:"w:eastAsia",value:Y},hAnsi:{key:"w:hAnsi",value:Y},hint:{key:"w:hint",value:U}}})}let G=B;return new X0({name:"w:rFonts",attributes:{ascii:{key:"w:ascii",value:G.ascii},cs:{key:"w:cs",value:G.cs},eastAsia:{key:"w:eastAsia",value:G.eastAsia},hAnsi:{key:"w:hAnsi",value:G.hAnsi},hint:{key:"w:hint",value:G.hint}}})},dB=(B)=>new X0({name:"w:vertAlign",attributes:{val:{key:"w:val",value:B}}}),TG=()=>dB("superscript"),DG=()=>dB("subscript"),r8={SINGLE:"single",WORDS:"words",DOUBLE:"double",THICK:"thick",DOTTED:"dotted",DOTTEDHEAVY:"dottedHeavy",DASH:"dash",DASHEDHEAVY:"dashedHeavy",DASHLONG:"dashLong",DASHLONGHEAVY:"dashLongHeavy",DOTDASH:"dotDash",DASHDOTHEAVY:"dashDotHeavy",DOTDOTDASH:"dotDotDash",DASHDOTDOTHEAVY:"dashDotDotHeavy",WAVE:"wave",WAVYHEAVY:"wavyHeavy",WAVYDOUBLE:"wavyDouble",NONE:"none"},cB=(B=r8.SINGLE,U)=>new X0({name:"w:u",attributes:{val:{key:"w:val",value:B},color:{key:"w:color",value:U===void 0?void 0:C2(U)}}}),CG={BLINK_BACKGROUND:"blinkBackground",LIGHTS:"lights",ANTS_BLACK:"antsBlack",ANTS_RED:"antsRed",SHIMMER:"shimmer",SPARKLE:"sparkle",NONE:"none"},kG={BLACK:"black",BLUE:"blue",CYAN:"cyan",DARK_BLUE:"darkBlue",DARK_CYAN:"darkCyan",DARK_GRAY:"darkGray",DARK_GREEN:"darkGreen",DARK_MAGENTA:"darkMagenta",DARK_RED:"darkRed",DARK_YELLOW:"darkYellow",GREEN:"green",LIGHT_GRAY:"lightGray",MAGENTA:"magenta",NONE:"none",RED:"red",WHITE:"white",YELLOW:"yellow"},U2=class extends R2{constructor(B){super("w:rPr");if(!B)return;if(B.style)this.push(new M2("w:rStyle",B.style));if(B.font)if(typeof B.font==="string")this.push(T1(B.font));else if("name"in B.font)this.push(T1(B.font.name,B.font.hint));else this.push(T1(B.font));if(B.bold!==void 0)this.push(new M0("w:b",B.bold));if(B.boldComplexScript===void 0&&B.bold!==void 0||B.boldComplexScript){var U;this.push(new M0("w:bCs",(U=B.boldComplexScript)!==null&&U!==void 0?U:B.bold))}if(B.italics!==void 0)this.push(new M0("w:i",B.italics));if(B.italicsComplexScript===void 0&&B.italics!==void 0||B.italicsComplexScript){var G;this.push(new M0("w:iCs",(G=B.italicsComplexScript)!==null&&G!==void 0?G:B.italics))}if(B.smallCaps!==void 0)this.push(new M0("w:smallCaps",B.smallCaps));else if(B.allCaps!==void 0)this.push(new M0("w:caps",B.allCaps));if(B.strike!==void 0)this.push(new M0("w:strike",B.strike));if(B.doubleStrike!==void 0)this.push(new M0("w:dstrike",B.doubleStrike));if(B.emboss!==void 0)this.push(new M0("w:emboss",B.emboss));if(B.imprint!==void 0)this.push(new M0("w:imprint",B.imprint));if(B.noProof!==void 0)this.push(new M0("w:noProof",B.noProof));if(B.snapToGrid!==void 0)this.push(new M0("w:snapToGrid",B.snapToGrid));if(B.vanish)this.push(new M0("w:vanish",B.vanish));if(B.color)this.push(new jG(B.color));if(B.characterSpacing)this.push(new AG(B.characterSpacing));if(B.scale!==void 0)this.push(new _2("w:w",B.scale));if(B.kern)this.push(new E1("w:kern",B.kern));if(B.position)this.push(new M2("w:position",B.position));if(B.size!==void 0)this.push(new E1("w:sz",B.size));let Y=B.sizeComplexScript===void 0||B.sizeComplexScript===!0?B.size:B.sizeComplexScript;if(Y)this.push(new E1("w:szCs",Y));if(B.highlight)this.push(new NG(B.highlight));let Q=B.highlightComplexScript===void 0||B.highlightComplexScript===!0?B.highlight:B.highlightComplexScript;if(Q)this.push(new zG(Q));if(B.underline)this.push(cB(B.underline.type,B.underline.color));if(B.effect)this.push(new M2("w:effect",B.effect));if(B.border)this.push(A0("w:bdr",B.border));if(B.shading)this.push(X1(B.shading));if(B.subScript)this.push(DG());if(B.superScript)this.push(TG());if(B.rightToLeft!==void 0)this.push(new M0("w:rtl",B.rightToLeft));if(B.emphasisMark)this.push(p8(B.emphasisMark.type));if(B.language)this.push(EG(B.language));if(B.specVanish)this.push(new M0("w:specVanish",B.vanish));if(B.math)this.push(new M0("w:oMath",B.math));if(B.revision)this.push(new lB(B.revision))}push(B){this.root.push(B)}},mB=class extends U2{constructor(B){super(B);if(B===null||B===void 0?void 0:B.insertion)this.push(new PG(B.insertion));if(B===null||B===void 0?void 0:B.deletion)this.push(new WG(B.deletion))}},lB=class extends t{constructor(B){super("w:rPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.addChildElement(new U2(B))}},Z1=class extends t{constructor(B){super("w:t");if(typeof B==="string")this.root.push(new _0({space:x0.PRESERVE})),this.root.push(B);else{var U;this.root.push(new _0({space:(U=B.space)!==null&&U!==void 0?U:x0.DEFAULT})),this.root.push(B.text)}}},H2={CURRENT:"CURRENT",TOTAL_PAGES:"TOTAL_PAGES",TOTAL_PAGES_IN_SECTION:"TOTAL_PAGES_IN_SECTION",CURRENT_SECTION:"SECTION"},T0=class extends t{constructor(B){super("w:r");if(e(this,"properties",void 0),this.properties=new U2(B),this.root.push(this.properties),B.break)for(let U=0;U{U.exports=G;function G(Y,Q){if(!Y)throw Error(Q||"Assertion failed")}G.equal=function(Q,K,Z){if(Q!=K)throw Error(Z||"Assertion failed: "+Q+" != "+K)}}),G2=R0((B)=>{var U=R1();B.inherits=W2();function G(b,c){if((b.charCodeAt(c)&64512)!==55296)return!1;if(c<0||c+1>=b.length)return!1;return(b.charCodeAt(c+1)&64512)===56320}function Y(b,c){if(Array.isArray(b))return b.slice();if(!b)return[];var T=[];if(typeof b==="string"){if(!c){var m=0;for(var B0=0;B0>6|192,T[m++]=i&63|128;else if(G(b,B0))i=65536+((i&1023)<<10)+(b.charCodeAt(++B0)&1023),T[m++]=i>>18|240,T[m++]=i>>12&63|128,T[m++]=i>>6&63|128,T[m++]=i&63|128;else T[m++]=i>>12|224,T[m++]=i>>6&63|128,T[m++]=i&63|128}}else if(c==="hex"){if(b=b.replace(/[^a-z0-9]+/gi,""),b.length%2!==0)b="0"+b;for(B0=0;B0>>24|b>>>8&65280|b<<8&16711680|(b&255)<<24)>>>0}B.htonl=K;function Z(b,c){var T="";for(var m=0;m>>0}return i}B.join32=W;function I(b,c){var T=Array(b.length*4);for(var m=0,B0=0;m>>24,T[B0+1]=i>>>16&255,T[B0+2]=i>>>8&255,T[B0+3]=i&255;else T[B0+3]=i>>>24,T[B0+2]=i>>>16&255,T[B0+1]=i>>>8&255,T[B0]=i&255}return T}B.split32=I;function F(b,c){return b>>>c|b<<32-c}B.rotr32=F;function D(b,c){return b<>>32-c}B.rotl32=D;function w(b,c){return b+c>>>0}B.sum32=w;function P(b,c,T){return b+c+T>>>0}B.sum32_3=P;function A(b,c,T,m){return b+c+T+m>>>0}B.sum32_4=A;function E(b,c,T,m,B0){return b+c+T+m+B0>>>0}B.sum32_5=E;function C(b,c,T,m){var B0=b[c],i=m+b[c+1]>>>0;b[c]=(i>>0,b[c+1]=i}B.sum64=C;function j(b,c,T,m){return(c+m>>>0>>0}B.sum64_hi=j;function v(b,c,T,m){return c+m>>>0}B.sum64_lo=v;function S(b,c,T,m,B0,i,V0,s){var G0=0,r=c;return r=r+m>>>0,G0+=r>>0,G0+=r>>0,G0+=r>>0}B.sum64_4_hi=S;function H(b,c,T,m,B0,i,V0,s){return c+m+i+s>>>0}B.sum64_4_lo=H;function X(b,c,T,m,B0,i,V0,s,G0,r){var y=0,n=c;return n=n+m>>>0,y+=n>>0,y+=n>>0,y+=n>>0,y+=n>>0}B.sum64_5_hi=X;function $(b,c,T,m,B0,i,V0,s,G0,r){return c+m+i+s+r>>>0}B.sum64_5_lo=$;function x(b,c,T){return(c<<32-T|b>>>T)>>>0}B.rotr64_hi=x;function N(b,c,T){return(b<<32-T|c>>>T)>>>0}B.rotr64_lo=N;function a(b,c,T){return b>>>T}B.shr64_hi=a;function U0(b,c,T){return(b<<32-T|c>>>T)>>>0}B.shr64_lo=U0}),L1=R0((B)=>{var U=G2(),G=R1();function Y(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}B.BlockHash=Y,Y.prototype.update=function(K,Z){if(K=U.toArray(K,Z),!this.pending)this.pending=K;else this.pending=this.pending.concat(K);if(this.pendingTotal+=K.length,this.pending.length>=this._delta8){K=this.pending;var J=K.length%this._delta8;if(this.pending=K.slice(K.length-J,K.length),this.pending.length===0)this.pending=null;K=U.join32(K,0,K.length-J,this.endian);for(var M=0;M>>24&255,M[W++]=K>>>16&255,M[W++]=K>>>8&255,M[W++]=K&255}else{M[W++]=K&255,M[W++]=K>>>8&255,M[W++]=K>>>16&255,M[W++]=K>>>24&255,M[W++]=0,M[W++]=0,M[W++]=0,M[W++]=0;for(I=8;I{var U=G2().rotr32;function G(I,F,D,w){if(I===0)return Y(F,D,w);if(I===1||I===3)return K(F,D,w);if(I===2)return Q(F,D,w)}B.ft_1=G;function Y(I,F,D){return I&F^~I&D}B.ch32=Y;function Q(I,F,D){return I&F^I&D^F&D}B.maj32=Q;function K(I,F,D){return I^F^D}B.p32=K;function Z(I){return U(I,2)^U(I,13)^U(I,22)}B.s0_256=Z;function J(I){return U(I,6)^U(I,11)^U(I,25)}B.s1_256=J;function M(I){return U(I,7)^U(I,18)^I>>>3}B.g0_256=M;function W(I){return U(I,17)^U(I,19)^I>>>10}B.g1_256=W}),SG=R0((B,U)=>{var G=G2(),Y=L1(),Q=pB(),K=G.rotl32,Z=G.sum32,J=G.sum32_5,M=Q.ft_1,W=Y.BlockHash,I=[1518500249,1859775393,2400959708,3395469782];function F(){if(!(this instanceof F))return new F;W.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}G.inherits(F,W),U.exports=F,F.blockSize=512,F.outSize=160,F.hmacStrength=80,F.padLength=64,F.prototype._update=function(w,P){var A=this.W;for(var E=0;E<16;E++)A[E]=w[P+E];for(;E{var G=G2(),Y=L1(),Q=pB(),K=R1(),Z=G.sum32,J=G.sum32_4,M=G.sum32_5,W=Q.ch32,I=Q.maj32,F=Q.s0_256,D=Q.s1_256,w=Q.g0_256,P=Q.g1_256,A=Y.BlockHash,E=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function C(){if(!(this instanceof C))return new C;A.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=E,this.W=Array(64)}G.inherits(C,A),U.exports=C,C.blockSize=512,C.outSize=256,C.hmacStrength=192,C.padLength=64,C.prototype._update=function(v,S){var H=this.W;for(var X=0;X<16;X++)H[X]=v[S+X];for(;X{var G=G2(),Y=rB();function Q(){if(!(this instanceof Q))return new Q;Y.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}G.inherits(Q,Y),U.exports=Q,Q.blockSize=512,Q.outSize=224,Q.hmacStrength=192,Q.padLength=64,Q.prototype._digest=function(Z){if(Z==="hex")return G.toHex32(this.h.slice(0,7),"big");else return G.split32(this.h.slice(0,7),"big")}}),iB=R0((B,U)=>{var G=G2(),Y=L1(),Q=R1(),K=G.rotr64_hi,Z=G.rotr64_lo,J=G.shr64_hi,M=G.shr64_lo,W=G.sum64,I=G.sum64_hi,F=G.sum64_lo,D=G.sum64_4_hi,w=G.sum64_4_lo,P=G.sum64_5_hi,A=G.sum64_5_lo,E=Y.BlockHash,C=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function j(){if(!(this instanceof j))return new j;E.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=C,this.W=Array(160)}G.inherits(j,E),U.exports=j,j.blockSize=1024,j.outSize=512,j.hmacStrength=192,j.padLength=128,j.prototype._prepareBlock=function(B0,i){var V0=this.W;for(var s=0;s<32;s++)V0[s]=B0[i+s];for(;s{var G=G2(),Y=iB();function Q(){if(!(this instanceof Q))return new Q;Y.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}G.inherits(Q,Y),U.exports=Q,Q.blockSize=1024,Q.outSize=384,Q.hmacStrength=192,Q.padLength=128,Q.prototype._digest=function(Z){if(Z==="hex")return G.toHex32(this.h.slice(0,12),"big");else return G.split32(this.h.slice(0,12),"big")}}),yG=R0((B)=>{B.sha1=SG(),B.sha224=bG(),B.sha256=rB(),B.sha384=vG(),B.sha512=iB()}),gG=R0((B)=>{var U=G2(),G=L1(),Y=U.rotl32,Q=U.sum32,K=U.sum32_3,Z=U.sum32_4,J=G.BlockHash;function M(){if(!(this instanceof M))return new M;J.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}U.inherits(M,J),B.ripemd160=M,M.blockSize=512,M.outSize=160,M.hmacStrength=192,M.padLength=64,M.prototype._update=function(C,j){var v=this.h[0],S=this.h[1],H=this.h[2],X=this.h[3],$=this.h[4],x=v,N=S,a=H,U0=X,b=$;for(var c=0;c<80;c++){var T=Q(Y(Z(v,W(c,S,H,X),C[D[c]+j],I(c)),P[c]),$);v=$,$=X,X=Y(H,10),H=S,S=T,T=Q(Y(Z(x,W(79-c,N,a,U0),C[w[c]+j],F(c)),A[c]),b),x=b,b=U0,U0=Y(a,10),a=N,N=T}T=K(this.h[1],H,U0),this.h[1]=K(this.h[2],X,b),this.h[2]=K(this.h[3],$,x),this.h[3]=K(this.h[4],v,N),this.h[4]=K(this.h[0],S,a),this.h[0]=T},M.prototype._digest=function(C){if(C==="hex")return U.toHex32(this.h,"little");else return U.split32(this.h,"little")};function W(E,C,j,v){if(E<=15)return C^j^v;else if(E<=31)return C&j|~C&v;else if(E<=47)return(C|~j)^v;else if(E<=63)return C&v|j&~v;else return C^(j|~v)}function I(E){if(E<=15)return 0;else if(E<=31)return 1518500249;else if(E<=47)return 1859775393;else if(E<=63)return 2400959708;else return 2840853838}function F(E){if(E<=15)return 1352829926;else if(E<=31)return 1548603684;else if(E<=47)return 1836072691;else if(E<=63)return 2053994217;else return 0}var D=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],w=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],P=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],A=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]}),fG=R0((B,U)=>{var G=G2(),Y=R1();function Q(K,Z,J){if(!(this instanceof Q))return new Q(K,Z,J);this.Hash=K,this.blockSize=K.blockSize/8,this.outSize=K.outSize/8,this.inner=null,this.outer=null,this._init(G.toArray(Z,J))}U.exports=Q,Q.prototype._init=function(Z){if(Z.length>this.blockSize)Z=new this.Hash().update(Z).digest();Y(Z.length<=this.blockSize);for(var J=Z.length;J{var U=B;U.utils=G2(),U.common=L1(),U.sha=yG(),U.ripemd=gG(),U.hmac=fG(),U.sha1=U.sha.sha1,U.sha256=U.sha.sha256,U.sha224=U.sha.sha224,U.sha384=U.sha.sha384,U.sha512=U.sha.sha512,U.ripemd160=U.ripemd.ripemd160})(),1),_G="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",hG=(B,U=21)=>{return(G=U)=>{let Y="",Q=G|0;while(Q--)Y+=B[Math.random()*B.length|0];return Y}},uG=(B=21)=>{let U="",G=B|0;while(G--)U+=_G[Math.random()*64|0];return U},dG=(B)=>Math.floor(B/25.4*72*20),u0=(B)=>Math.floor(B*72*20),I1=(B=0)=>{let U=B;return()=>++U},nB=()=>I1(),sB=()=>I1(1),oB=()=>I1(),tB=()=>I1(),O1=()=>uG().toLowerCase(),W8=(B)=>xG.default.sha1().update(B instanceof ArrayBuffer?new Uint8Array(B):B).digest("hex"),s2=(B)=>hG("1234567890abcdef",B)(),eB=()=>`${s2(8)}-${s2(4)}-${s2(4)}-${s2(4)}-${s2(12)}`,U1=(B)=>new Uint8Array(new TextEncoder().encode(B)),B4={CHARACTER:"character",COLUMN:"column",INSIDE_MARGIN:"insideMargin",LEFT_MARGIN:"leftMargin",MARGIN:"margin",OUTSIDE_MARGIN:"outsideMargin",PAGE:"page",RIGHT_MARGIN:"rightMargin"},U4={BOTTOM_MARGIN:"bottomMargin",INSIDE_MARGIN:"insideMargin",LINE:"line",MARGIN:"margin",OUTSIDE_MARGIN:"outsideMargin",PAGE:"page",PARAGRAPH:"paragraph",TOP_MARGIN:"topMargin"},G4=()=>new X0({name:"wp:simplePos",attributes:{x:{key:"x",value:0},y:{key:"y",value:0}}}),Y4=(B)=>new X0({name:"wp:align",children:[B]}),Z4=(B)=>new X0({name:"wp:posOffset",children:[B.toString()]}),Q4=({relative:B,align:U,offset:G})=>new X0({name:"wp:positionH",attributes:{relativeFrom:{key:"relativeFrom",value:B!==null&&B!==void 0?B:B4.PAGE}},children:[(()=>{if(U)return Y4(U);else if(G!==void 0)return Z4(G);else throw Error("There is no configuration provided for floating position (Align or offset)")})()]}),J4=({relative:B,align:U,offset:G})=>new X0({name:"wp:positionV",attributes:{relativeFrom:{key:"relativeFrom",value:B!==null&&B!==void 0?B:U4.PAGE}},children:[(()=>{if(U)return Y4(U);else if(G!==void 0)return Z4(G);else throw Error("There is no configuration provided for floating position (Align or offset)")})()]}),cG=function(B){return B.CENTER="ctr",B.TOP="t",B.BOTTOM="b",B}({}),K4=(B={})=>{var U,G,Y,Q;return new X0({name:"wps:bodyPr",attributes:{lIns:{key:"lIns",value:(U=B.margins)===null||U===void 0?void 0:U.left},rIns:{key:"rIns",value:(G=B.margins)===null||G===void 0?void 0:G.right},tIns:{key:"tIns",value:(Y=B.margins)===null||Y===void 0?void 0:Y.top},bIns:{key:"bIns",value:(Q=B.margins)===null||Q===void 0?void 0:Q.bottom},anchor:{key:"anchor",value:B.verticalAnchor}},children:[...B.noAutoFit?[new M0("a:noAutofit",B.noAutoFit)]:[]]})},mG=(B={txBox:"1"})=>new X0({name:"wps:cNvSpPr",attributes:{txBox:{key:"txBox",value:B.txBox}}}),lG=(B)=>new X0({name:"w:txbxContent",children:[...B]}),aG=(B)=>new X0({name:"wps:txbx",children:[lG(B)]}),pG=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{cx:"cx",cy:"cy"})}},rG=class extends t{constructor(B,U){super("a:ext");e(this,"attributes",void 0),this.attributes=new pG({cx:B,cy:U}),this.root.push(this.attributes)}},iG=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{x:"x",y:"y"})}},nG=class extends t{constructor(B,U){super("a:off");this.root.push(new iG({x:B!==null&&B!==void 0?B:0,y:U!==null&&U!==void 0?U:0}))}},sG=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{flipVertical:"flipV",flipHorizontal:"flipH",rotation:"rot"})}},V4=class extends t{constructor(B){var U,G,Y,Q;super("a:xfrm");e(this,"extents",void 0),e(this,"offset",void 0),this.root.push(new sG({flipVertical:(U=B.flip)===null||U===void 0?void 0:U.vertical,flipHorizontal:(G=B.flip)===null||G===void 0?void 0:G.horizontal,rotation:B.rotation})),this.offset=new nG((Y=B.offset)===null||Y===void 0||(Y=Y.emus)===null||Y===void 0?void 0:Y.x,(Q=B.offset)===null||Q===void 0||(Q=Q.emus)===null||Q===void 0?void 0:Q.y),this.extents=new rG(B.emus.x,B.emus.y),this.root.push(this.offset),this.root.push(this.extents)}},q4=()=>new X0({name:"a:noFill"}),oG=(B)=>new X0({name:"a:srgbClr",attributes:{value:{key:"val",value:B.value}}}),tG=(B)=>new X0({name:"a:schemeClr",attributes:{value:{key:"val",value:B.value}}}),P8=(B)=>new X0({name:"a:solidFill",children:[B.type==="rgb"?oG(B):tG(B)]}),eG=(B)=>new X0({name:"a:ln",attributes:{width:{key:"w",value:B.width},cap:{key:"cap",value:B.cap},compoundLine:{key:"cmpd",value:B.compoundLine},align:{key:"algn",value:B.align}},children:[B.type==="noFill"?q4():B.solidFillType==="rgb"?P8({type:"rgb",value:B.value}):P8({type:"scheme",value:B.value})]}),BY=class extends t{constructor(){super("a:avLst")}},UY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{prst:"prst"})}},GY=class extends t{constructor(){super("a:prstGeom");this.root.push(new UY({prst:"rect"})),this.root.push(new BY)}},YY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{bwMode:"bwMode"})}},M4=class extends t{constructor({element:B,outline:U,solidFill:G,transform:Y}){super(`${B}:spPr`);if(e(this,"form",void 0),this.root.push(new YY({bwMode:"auto"})),this.form=new V4(Y),this.root.push(this.form),this.root.push(new GY),U)this.root.push(q4()),this.root.push(eG(U));if(G)this.root.push(P8(G))}},l6=(B)=>new X0({name:"wps:wsp",children:[mG(B.nonVisualProperties),new M4({element:"wps",transform:B.transformation,outline:B.outline,solidFill:B.solidFill}),aG(B.children),K4(B.bodyProperties)]}),J8=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{uri:"uri"})}},ZY=(B)=>new X0({name:"asvg:svgBlip",attributes:{asvg:{key:"xmlns:asvg",value:"http://schemas.microsoft.com/office/drawing/2016/SVG/main"},embed:{key:"r:embed",value:`rId{${B.fileName}}`}}}),QY=(B)=>new X0({name:"a:ext",attributes:{uri:{key:"uri",value:"{96DAC541-7B7A-43D3-8B79-37D633B846F1}"}},children:[ZY(B)]}),JY=(B)=>new X0({name:"a:extLst",children:[QY(B)]}),KY=(B)=>new X0({name:"a:blip",attributes:{embed:{key:"r:embed",value:`rId{${B.type==="svg"?B.fallback.fileName:B.fileName}}`},cstate:{key:"cstate",value:"none"}},children:B.type==="svg"?[JY(B)]:[]}),VY=class extends t{constructor(){super("a:srcRect")}},qY=class extends t{constructor(){super("a:fillRect")}},MY=class extends t{constructor(){super("a:stretch");this.root.push(new qY)}},XY=class extends t{constructor(B){super("pic:blipFill");this.root.push(KY(B)),this.root.push(new VY),this.root.push(new MY)}},RY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{noChangeAspect:"noChangeAspect",noChangeArrowheads:"noChangeArrowheads"})}},LY=class extends t{constructor(){super("a:picLocks");this.root.push(new RY({noChangeAspect:1,noChangeArrowheads:1}))}},IY=class extends t{constructor(){super("pic:cNvPicPr");this.root.push(new LY)}},X4=(B,U)=>new X0({name:"a:hlinkClick",attributes:L0(L0({},U?{xmlns:{key:"xmlns:a",value:"http://schemas.openxmlformats.org/drawingml/2006/main"}}:{}),{},{id:{key:"r:id",value:`rId${B}`}})}),OY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"id",name:"name",descr:"descr"})}},FY=class extends t{constructor(){super("pic:cNvPr");this.root.push(new OY({id:0,name:"",descr:""}))}prepForXml(B){for(let U=B.stack.length-1;U>=0;U--){let G=B.stack[U];if(!(G instanceof m2))continue;this.root.push(X4(G.linkId,!1));break}return super.prepForXml(B)}},HY=class extends t{constructor(){super("pic:nvPicPr");this.root.push(new FY),this.root.push(new IY)}},WY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns:pic"})}},a6=class extends t{constructor({mediaData:B,transform:U,outline:G}){super("pic:pic");this.root.push(new WY({xmlns:"http://schemas.openxmlformats.org/drawingml/2006/picture"})),this.root.push(new HY),this.root.push(new XY(B)),this.root.push(new M4({element:"pic",transform:U,outline:G}))}},PY=(B)=>new X0({name:"wpg:grpSpPr",children:[new V4(B)]}),wY=()=>new X0({name:"wpg:cNvGrpSpPr"}),AY=(B)=>new X0({name:"wpg:wgp",children:[wY(),PY(B.transformation),...B.children]}),jY=class extends t{constructor({mediaData:B,transform:U,outline:G,solidFill:Y}){super("a:graphicData");if(B.type==="wps"){this.root.push(new J8({uri:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"}));let Q=l6(L0(L0({},B.data),{},{transformation:U,outline:G,solidFill:Y}));this.root.push(Q)}else if(B.type==="wpg"){this.root.push(new J8({uri:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"}));let Q=AY({children:B.children.map((K)=>{if(K.type==="wps")return l6(L0(L0({},K.data),{},{transformation:K.transformation,outline:K.outline,solidFill:K.solidFill}));else return new a6({mediaData:K,transform:K.transformation,outline:K.outline})}),transformation:U});this.root.push(Q)}else{this.root.push(new J8({uri:"http://schemas.openxmlformats.org/drawingml/2006/picture"}));let Q=new a6({mediaData:B,transform:U,outline:G});this.root.push(Q)}}},NY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{a:"xmlns:a"})}},R4=class extends t{constructor({mediaData:B,transform:U,outline:G,solidFill:Y}){super("a:graphic");e(this,"data",void 0),this.root.push(new NY({a:"http://schemas.openxmlformats.org/drawingml/2006/main"})),this.data=new jY({mediaData:B,transform:U,outline:G,solidFill:Y}),this.root.push(this.data)}},e2={NONE:0,SQUARE:1,TIGHT:2,TOP_AND_BOTTOM:3},L4={BOTH_SIDES:"bothSides",LEFT:"left",RIGHT:"right",LARGEST:"largest"},w8=()=>new X0({name:"wp:wrapNone"}),I4=(B,U={top:0,bottom:0,left:0,right:0})=>new X0({name:"wp:wrapSquare",attributes:{wrapText:{key:"wrapText",value:B.side||L4.BOTH_SIDES},distT:{key:"distT",value:U.top},distB:{key:"distB",value:U.bottom},distL:{key:"distL",value:U.left},distR:{key:"distR",value:U.right}}}),O4=(B={top:0,bottom:0})=>new X0({name:"wp:wrapTight",attributes:{distT:{key:"distT",value:B.top},distB:{key:"distB",value:B.bottom}}}),F4=(B={top:0,bottom:0})=>new X0({name:"wp:wrapTopAndBottom",attributes:{distT:{key:"distT",value:B.top},distB:{key:"distB",value:B.bottom}}}),H4=class extends t{constructor({name:B,description:U,title:G,id:Y}={name:"",description:"",title:""}){super("wp:docPr");e(this,"docPropertiesUniqueNumericId",oB());let Q={id:{key:"id",value:Y!==null&&Y!==void 0?Y:this.docPropertiesUniqueNumericId()},name:{key:"name",value:B}};if(U!==null&&U!==void 0)Q.description={key:"descr",value:U};if(G!==null&&G!==void 0)Q.title={key:"title",value:G};this.root.push(new k8(Q))}prepForXml(B){for(let U=B.stack.length-1;U>=0;U--){let G=B.stack[U];if(!(G instanceof m2))continue;this.root.push(X4(G.linkId,!0));break}return super.prepForXml(B)}},W4=({top:B,right:U,bottom:G,left:Y})=>new X0({name:"wp:effectExtent",attributes:{top:{key:"t",value:B},right:{key:"r",value:U},bottom:{key:"b",value:G},left:{key:"l",value:Y}}}),P4=({x:B,y:U})=>new X0({name:"wp:extent",attributes:{x:{key:"cx",value:B},y:{key:"cy",value:U}}}),zY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns:a",noChangeAspect:"noChangeAspect"})}},EY=class extends t{constructor(){super("a:graphicFrameLocks");this.root.push(new zY({xmlns:"http://schemas.openxmlformats.org/drawingml/2006/main",noChangeAspect:1}))}},w4=()=>new X0({name:"wp:cNvGraphicFramePr",children:[new EY]}),TY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{distT:"distT",distB:"distB",distL:"distL",distR:"distR",allowOverlap:"allowOverlap",behindDoc:"behindDoc",layoutInCell:"layoutInCell",locked:"locked",relativeHeight:"relativeHeight",simplePos:"simplePos"})}},DY=class extends t{constructor({mediaData:B,transform:U,drawingOptions:G}){super("wp:anchor");let Y=L0({allowOverlap:!0,behindDocument:!1,lockAnchor:!1,layoutInCell:!0,verticalPosition:{},horizontalPosition:{}},G.floating);if(this.root.push(new TY({distT:Y.margins?Y.margins.top||0:0,distB:Y.margins?Y.margins.bottom||0:0,distL:Y.margins?Y.margins.left||0:0,distR:Y.margins?Y.margins.right||0:0,simplePos:"0",allowOverlap:Y.allowOverlap===!0?"1":"0",behindDoc:Y.behindDocument===!0?"1":"0",locked:Y.lockAnchor===!0?"1":"0",layoutInCell:Y.layoutInCell===!0?"1":"0",relativeHeight:Y.zIndex?Y.zIndex:U.emus.y})),this.root.push(G4()),this.root.push(Q4(Y.horizontalPosition)),this.root.push(J4(Y.verticalPosition)),this.root.push(P4({x:U.emus.x,y:U.emus.y})),this.root.push(W4({top:0,right:0,bottom:0,left:0})),G.floating!==void 0&&G.floating.wrap!==void 0)switch(G.floating.wrap.type){case e2.SQUARE:this.root.push(I4(G.floating.wrap,G.floating.margins));break;case e2.TIGHT:this.root.push(O4(G.floating.margins));break;case e2.TOP_AND_BOTTOM:this.root.push(F4(G.floating.margins));break;case e2.NONE:default:this.root.push(w8())}else this.root.push(w8());this.root.push(new H4(G.docProperties)),this.root.push(w4()),this.root.push(new R4({mediaData:B,transform:U,outline:G.outline,solidFill:G.solidFill}))}},CY=({mediaData:B,transform:U,docProperties:G,outline:Y,solidFill:Q})=>{var K,Z,J,M;return new X0({name:"wp:inline",attributes:{distanceTop:{key:"distT",value:0},distanceBottom:{key:"distB",value:0},distanceLeft:{key:"distL",value:0},distanceRight:{key:"distR",value:0}},children:[P4({x:U.emus.x,y:U.emus.y}),W4(Y?{top:((K=Y.width)!==null&&K!==void 0?K:9525)*2,right:((Z=Y.width)!==null&&Z!==void 0?Z:9525)*2,bottom:((J=Y.width)!==null&&J!==void 0?J:9525)*2,left:((M=Y.width)!==null&&M!==void 0?M:9525)*2}:{top:0,right:0,bottom:0,left:0}),new H4(G),w4(),new R4({mediaData:B,transform:U,outline:Y,solidFill:Q})]})},c1=class extends t{constructor(B,U={}){super("w:drawing");if(!U.floating)this.root.push(CY({mediaData:B,transform:B.transformation,docProperties:U.docProperties,outline:U.outline,solidFill:U.solidFill}));else this.root.push(new DY({mediaData:B,transform:B.transformation,drawingOptions:U}))}},kY=(B)=>{let U=B.indexOf(";base64,"),G=U===-1?0:U+8;return new Uint8Array(atob(B.substring(G)).split("").map((Y)=>Y.charCodeAt(0)))},A4=(B)=>typeof B==="string"?kY(B):B,K8=(B,U)=>({data:A4(B.data),fileName:U,transformation:{pixels:{x:Math.round(B.transformation.width),y:Math.round(B.transformation.height)},emus:{x:Math.round(B.transformation.width*9525),y:Math.round(B.transformation.height*9525)},flip:B.transformation.flip,rotation:B.transformation.rotation?B.transformation.rotation*60000:void 0}}),$Y=class extends t{constructor(B){var U=(...Z)=>(super(...Z),e(this,"imageData",void 0),this);let G=`${W8(B.data)}.${B.type}`,Y=B.type==="svg"?L0(L0({type:B.type},K8(B,G)),{},{fallback:L0({type:B.fallback.type},K8(L0(L0({},B.fallback),{},{transformation:B.transformation}),`${W8(B.fallback.data)}.${B.fallback.type}`))}):L0({type:B.type},K8(B,G)),Q=new c1(Y,{floating:B.floating,docProperties:B.altText,outline:B.outline}),K=new T0({children:[Q]});if(B.insertion)U("w:ins"),this.root.push(new b0({id:B.insertion.id,author:B.insertion.author,date:B.insertion.date})),this.addChildElement(K);else if(B.deletion)U("w:del"),this.root.push(new b0({id:B.deletion.id,author:B.deletion.author,date:B.deletion.date})),this.addChildElement(K);else U("w:r"),this.root.push(new U2({})),this.root.push(Q);this.imageData=Y}prepForXml(B){if(B.file.Media.addImage(this.imageData.fileName,this.imageData),this.imageData.type==="svg")B.file.Media.addImage(this.imageData.fallback.fileName,this.imageData.fallback);return super.prepForXml(B)}},i8=(B)=>{var U,G,Y,Q,K,Z,J,M;return{offset:{pixels:{x:Math.round((U=(G=B.offset)===null||G===void 0?void 0:G.left)!==null&&U!==void 0?U:0),y:Math.round((Y=(Q=B.offset)===null||Q===void 0?void 0:Q.top)!==null&&Y!==void 0?Y:0)},emus:{x:Math.round(((K=(Z=B.offset)===null||Z===void 0?void 0:Z.left)!==null&&K!==void 0?K:0)*9525),y:Math.round(((J=(M=B.offset)===null||M===void 0?void 0:M.top)!==null&&J!==void 0?J:0)*9525)}},pixels:{x:Math.round(B.width),y:Math.round(B.height)},emus:{x:Math.round(B.width*9525),y:Math.round(B.height*9525)},flip:B.flip,rotation:B.rotation?B.rotation*60000:void 0}},SY=class extends T0{constructor(B){super({});e(this,"wpsShapeData",void 0),this.wpsShapeData={type:B.type,transformation:i8(B.transformation),data:L0({},B)};let U=new c1(this.wpsShapeData,{floating:B.floating,docProperties:B.altText,outline:B.outline,solidFill:B.solidFill});this.root.push(U)}},bY=class extends T0{constructor(B){super({});e(this,"wpgGroupData",void 0),e(this,"mediaDatas",void 0),this.wpgGroupData={type:B.type,transformation:i8(B.transformation),children:B.children};let U=new c1(this.wpgGroupData,{floating:B.floating,docProperties:B.altText});this.mediaDatas=B.children.filter((G)=>G.type!=="wps").map((G)=>G),this.root.push(U)}prepForXml(B){return this.mediaDatas.forEach((U)=>{if(B.file.Media.addImage(U.fileName,U),U.type==="svg")B.file.Media.addImage(U.fallback.fileName,U.fallback)}),super.prepForXml(B)}},vY=class extends t{constructor(B){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push(`SEQ ${B}`)}},yY=class extends T0{constructor(B){super({});this.root.push(e0(!0)),this.root.push(new vY(B)),this.root.push(q2()),this.root.push(B2())}},gY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{instr:"w:instr"})}},n8=class extends t{constructor(B,U){super("w:fldSimple");if(this.root.push(new gY({instr:B})),U!==void 0)this.root.push(new Q1(U))}},fY=class extends n8{constructor(B){super(` MERGEFIELD ${B} `,`«${B}»`)}},xY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns"})}},j4={EXTERNAL:"External"},_Y=(B,U,G,Y)=>new X0({name:"Relationship",attributes:{id:{key:"Id",value:B},type:{key:"Type",value:U},target:{key:"Target",value:G},targetMode:{key:"TargetMode",value:Y}}}),w2=class extends t{constructor(){super("Relationships");this.root.push(new xY({xmlns:"http://schemas.openxmlformats.org/package/2006/relationships"}))}addRelationship(B,U,G,Y){this.root.push(_Y(`rId${B}`,U,G,Y))}get RelationshipCount(){return this.root.length-1}},hY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id",initials:"w:initials",author:"w:author",date:"w:date"})}},s8=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id"})}},uY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{"xmlns:cx":"xmlns:cx","xmlns:cx1":"xmlns:cx1","xmlns:cx2":"xmlns:cx2","xmlns:cx3":"xmlns:cx3","xmlns:cx4":"xmlns:cx4","xmlns:cx5":"xmlns:cx5","xmlns:cx6":"xmlns:cx6","xmlns:cx7":"xmlns:cx7","xmlns:cx8":"xmlns:cx8","xmlns:mc":"xmlns:mc","xmlns:aink":"xmlns:aink","xmlns:am3d":"xmlns:am3d","xmlns:o":"xmlns:o","xmlns:r":"xmlns:r","xmlns:m":"xmlns:m","xmlns:v":"xmlns:v","xmlns:wp14":"xmlns:wp14","xmlns:wp":"xmlns:wp","xmlns:w10":"xmlns:w10","xmlns:w":"xmlns:w","xmlns:w14":"xmlns:w14","xmlns:w15":"xmlns:w15","xmlns:w16cex":"xmlns:w16cex","xmlns:w16cid":"xmlns:w16cid","xmlns:w16":"xmlns:w16","xmlns:w16sdtdh":"xmlns:w16sdtdh","xmlns:w16se":"xmlns:w16se","xmlns:wpg":"xmlns:wpg","xmlns:wpi":"xmlns:wpi","xmlns:wne":"xmlns:wne","xmlns:wps":"xmlns:wps"})}},dY=class extends t{constructor(B){super("w:commentRangeStart");this.root.push(new s8({id:B}))}},cY=class extends t{constructor(B){super("w:commentRangeEnd");this.root.push(new s8({id:B}))}},mY=class extends t{constructor(B){super("w:commentReference");this.root.push(new s8({id:B}))}},A8=class extends t{constructor({id:B,initials:U,author:G,date:Y=new Date,children:Q},K){super("w:comment");e(this,"paraId",void 0),this.paraId=K,this.root.push(new hY({id:B,initials:U,author:G,date:Y.toISOString()}));for(let Z of Q)this.root.push(Z)}prepForXml(B){let U=super.prepForXml(B);if(!U||!this.paraId)return U;let G=U["w:comment"];if(!Array.isArray(G))return U;for(let Y=G.length-1;Y>=0;Y--){let Q=G[Y];if(Q&&typeof Q==="object"&&"w:p"in Q){let K=Q["w:p"];if(Array.isArray(K))K.unshift({_attr:{"w14:paraId":this.paraId,"w14:textId":this.paraId}});break}}return U}},N4=(B)=>(B+1).toString(16).toUpperCase().padStart(8,"0"),z4=class extends t{constructor({children:B}){super("w:comments");if(e(this,"relationships",void 0),e(this,"threadData",void 0),this.root.push(new uY({"xmlns:cx":"http://schemas.microsoft.com/office/drawing/2014/chartex","xmlns:cx1":"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex","xmlns:cx2":"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex","xmlns:cx3":"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex","xmlns:cx4":"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex","xmlns:cx5":"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex","xmlns:cx6":"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex","xmlns:cx7":"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex","xmlns:cx8":"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex","xmlns:mc":"http://schemas.openxmlformats.org/markup-compatibility/2006","xmlns:aink":"http://schemas.microsoft.com/office/drawing/2016/ink","xmlns:am3d":"http://schemas.microsoft.com/office/drawing/2017/model3d","xmlns:o":"urn:schemas-microsoft-com:office:office","xmlns:r":"http://schemas.openxmlformats.org/officeDocument/2006/relationships","xmlns:m":"http://schemas.openxmlformats.org/officeDocument/2006/math","xmlns:v":"urn:schemas-microsoft-com:vml","xmlns:wp14":"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing","xmlns:wp":"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing","xmlns:w10":"urn:schemas-microsoft-com:office:word","xmlns:w":"http://schemas.openxmlformats.org/wordprocessingml/2006/main","xmlns:w14":"http://schemas.microsoft.com/office/word/2010/wordml","xmlns:w15":"http://schemas.microsoft.com/office/word/2012/wordml","xmlns:w16cex":"http://schemas.microsoft.com/office/word/2018/wordml/cex","xmlns:w16cid":"http://schemas.microsoft.com/office/word/2016/wordml/cid","xmlns:w16":"http://schemas.microsoft.com/office/word/2018/wordml","xmlns:w16sdtdh":"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash","xmlns:w16se":"http://schemas.microsoft.com/office/word/2015/wordml/symex","xmlns:wpg":"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup","xmlns:wpi":"http://schemas.microsoft.com/office/word/2010/wordprocessingInk","xmlns:wne":"http://schemas.microsoft.com/office/word/2006/wordml","xmlns:wps":"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"})),B.some((U)=>U.parentId!==void 0)){let U=new Map(B.map((G)=>[G.id,N4(G.id)]));for(let G of B)this.root.push(new A8(G,U.get(G.id)));this.threadData=B.map((G)=>({paraId:U.get(G.id),parentParaId:G.parentId!==void 0?U.get(G.parentId):void 0,done:G.resolved}))}else for(let U of B)this.root.push(new A8(U));this.relationships=new w2}get Relationships(){return this.relationships}get ThreadData(){return this.threadData}},lY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{"xmlns:wpc":"xmlns:wpc","xmlns:mc":"xmlns:mc","xmlns:w15":"xmlns:w15","mc:Ignorable":"mc:Ignorable"})}},aY=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{paraId:"w15:paraId",paraIdParent:"w15:paraIdParent",done:"w15:done"})}},pY=class extends t{constructor(B){super("w15:commentEx");this.root.push(new aY({paraId:B.paraId,paraIdParent:B.parentParaId,done:B.done!==void 0?B.done?"1":"0":void 0}))}},E4=class extends t{constructor(B){super("w15:commentsEx");this.root.push(new lY({"xmlns:wpc":"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas","xmlns:mc":"http://schemas.openxmlformats.org/markup-compatibility/2006","xmlns:w15":"http://schemas.microsoft.com/office/word/2012/wordml","mc:Ignorable":"w15"}));for(let U of B)this.root.push(new pY(U))}},rY=class extends S0{constructor(){super("w:noBreakHyphen")}},iY=class extends S0{constructor(){super("w:softHyphen")}},nY=class extends S0{constructor(){super("w:dayShort")}},sY=class extends S0{constructor(){super("w:monthShort")}},oY=class extends S0{constructor(){super("w:yearShort")}},tY=class extends S0{constructor(){super("w:dayLong")}},eY=class extends S0{constructor(){super("w:monthLong")}},BZ=class extends S0{constructor(){super("w:yearLong")}},UZ=class extends S0{constructor(){super("w:annotationRef")}},GZ=class extends S0{constructor(){super("w:footnoteRef")}},T4=class extends S0{constructor(){super("w:endnoteRef")}},YZ=class extends S0{constructor(){super("w:separator")}},ZZ=class extends S0{constructor(){super("w:continuationSeparator")}},QZ=class extends S0{constructor(){super("w:pgNum")}},JZ=class extends S0{constructor(){super("w:cr")}},D4=class extends S0{constructor(){super("w:tab")}},KZ=class extends S0{constructor(){super("w:lastRenderedPageBreak")}},VZ={LEFT:"left",CENTER:"center",RIGHT:"right"},qZ={MARGIN:"margin",INDENT:"indent"},MZ={NONE:"none",DOT:"dot",HYPHEN:"hyphen",UNDERSCORE:"underscore",MIDDLE_DOT:"middleDot"},XZ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{alignment:"w:alignment",relativeTo:"w:relativeTo",leader:"w:leader"})}},RZ=class extends t{constructor(B){super("w:ptab");this.root.push(new XZ({alignment:B.alignment,relativeTo:B.relativeTo,leader:B.leader}))}},C4={COLUMN:"column",PAGE:"page"},k4=class extends t{constructor(B){super("w:br");this.root.push(new C0({type:B}))}},LZ=class extends T0{constructor(){super({});this.root.push(new k4(C4.PAGE))}},IZ=class extends T0{constructor(){super({});this.root.push(new k4(C4.COLUMN))}},$4=class extends t{constructor(){super("w:pageBreakBefore")}},k2={AT_LEAST:"atLeast",EXACTLY:"exactly",EXACT:"exact",AUTO:"auto"},S4=({after:B,before:U,line:G,lineRule:Y,beforeAutoSpacing:Q,afterAutoSpacing:K})=>new X0({name:"w:spacing",attributes:{after:{key:"w:after",value:B},before:{key:"w:before",value:U},line:{key:"w:line",value:G},lineRule:{key:"w:lineRule",value:Y},beforeAutoSpacing:{key:"w:beforeAutospacing",value:Q},afterAutoSpacing:{key:"w:afterAutospacing",value:K}}}),OZ={HEADING_1:"Heading1",HEADING_2:"Heading2",HEADING_3:"Heading3",HEADING_4:"Heading4",HEADING_5:"Heading5",HEADING_6:"Heading6",TITLE:"Title"},x2=(B)=>new X0({name:"w:pStyle",attributes:{val:{key:"w:val",value:B}}}),j8={LEFT:"left",RIGHT:"right",CENTER:"center",BAR:"bar",CLEAR:"clear",DECIMAL:"decimal",END:"end",NUM:"num",START:"start"},FZ={DOT:"dot",HYPHEN:"hyphen",MIDDLE_DOT:"middleDot",NONE:"none",UNDERSCORE:"underscore"},HZ={MAX:9026},b4=({type:B,position:U,leader:G})=>new X0({name:"w:tab",attributes:{val:{key:"w:val",value:B},pos:{key:"w:pos",value:U},leader:{key:"w:leader",value:G}}}),v4=(B)=>new X0({name:"w:tabs",children:B.map((U)=>b4(U))}),D1=class extends t{constructor(B,U){super("w:numPr");this.root.push(new WZ(U)),this.root.push(new PZ(B))}},WZ=class extends t{constructor(B){super("w:ilvl");if(B>9)throw Error("Level cannot be greater than 9. Read more here: https://answers.microsoft.com/en-us/msoffice/forum/all/does-word-support-more-than-9-list-levels/d130fdcd-1781-446d-8c84-c6c79124e4d7");this.root.push(new C0({val:B}))}},PZ=class extends t{constructor(B){super("w:numId");this.root.push(new C0({val:typeof B==="string"?`{${B}}`:B}))}},F1=class extends t{constructor(...B){super(...B);e(this,"fileChild",Symbol())}},wZ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"r:id",history:"w:history",anchor:"w:anchor"})}},AZ={INTERNAL:"INTERNAL",EXTERNAL:"EXTERNAL"},m2=class extends t{constructor(B,U,G){super("w:hyperlink");e(this,"linkId",void 0),this.linkId=U;let Y=new wZ({history:1,anchor:G?G:void 0,id:!G?`rId${this.linkId}`:void 0});this.root.push(Y),B.forEach((Q)=>{this.root.push(Q)})}},y4=class extends m2{constructor(B){super(B.children,O1(),B.anchor)}},o8=class extends t{constructor(B){super("w:externalHyperlink");e(this,"options",void 0),this.options=B}},jZ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id",name:"w:name"})}},NZ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id"})}},g4=class{constructor(B){e(this,"bookmarkUniqueNumericId",tB()),e(this,"start",void 0),e(this,"children",void 0),e(this,"end",void 0);let U=this.bookmarkUniqueNumericId();this.start=new f4(B.id,U),this.children=B.children,this.end=new x4(U)}},f4=class extends t{constructor(B,U){super("w:bookmarkStart");let G=new jZ({name:B,id:U});this.root.push(G)}},x4=class extends t{constructor(B){super("w:bookmarkEnd");let U=new NZ({id:B});this.root.push(U)}},zZ=function(B){return B.NONE="none",B.RELATIVE="relative",B.NO_CONTEXT="no_context",B.FULL_CONTEXT="full_context",B}({}),EZ={["relative"]:"\\r",["no_context"]:"\\n",["full_context"]:"\\w",["none"]:void 0},TZ=class extends n8{constructor(B,U,G={}){let{hyperlink:Y=!0,referenceFormat:Q="full_context"}=G,K=`${`REF ${B}`} ${[...Y?["\\h"]:[],...[EZ[Q]].filter((Z)=>!!Z)].join(" ")}`;super(K,U)}},_4=(B)=>new X0({name:"w:outlineLvl",attributes:{val:{key:"w:val",value:B}}}),DZ=class extends t{constructor(B,U={}){super("w:instrText");this.root.push(new _0({space:x0.PRESERVE}));let G=`PAGEREF ${B}`;if(U.hyperlink)G=`${G} \\h`;if(U.useRelativePosition)G=`${G} \\p`;this.root.push(G)}},CZ=class extends T0{constructor(B,U={}){super({children:[e0(!0),new DZ(B,U),B2()]})}},kZ={ANSI:"00",DEFAULT:"01",SYMBOL:"02",MAC:"4D",JIS:"80",HANGUL:"81",JOHAB:"82",GB_2312:"86",CHINESEBIG5:"88",GREEK:"A1",TURKISH:"A2",VIETNAMESE:"A3",HEBREW:"B1",ARABIC:"B2",BALTIC:"BA",RUSSIAN:"CC",THAI:"DE",EASTEUROPE:"EE",OEM:"FF"},z1=({id:B,fontKey:U,subsetted:G},Y)=>new X0({name:Y,attributes:L0({id:{key:"r:id",value:B}},U?{fontKey:{key:"w:fontKey",value:`{${U}}`}}:{}),children:[...G?[new M0("w:subsetted",G)]:[]]}),$Z=({name:B,altName:U,panose1:G,charset:Y,family:Q,notTrueType:K,pitch:Z,sig:J,embedRegular:M,embedBold:W,embedItalic:I,embedBoldItalic:F})=>new X0({name:"w:font",attributes:{name:{key:"w:name",value:B}},children:[...U?[f2("w:altName",U)]:[],...G?[f2("w:panose1",G)]:[],...Y?[f2("w:charset",Y)]:[],...Q?[f2("w:family",Q)]:[],...K?[new M0("w:notTrueType",K)]:[],...Z?[f2("w:pitch",Z)]:[],...J?[new X0({name:"w:sig",attributes:{usb0:{key:"w:usb0",value:J.usb0},usb1:{key:"w:usb1",value:J.usb1},usb2:{key:"w:usb2",value:J.usb2},usb3:{key:"w:usb3",value:J.usb3},csb0:{key:"w:csb0",value:J.csb0},csb1:{key:"w:csb1",value:J.csb1}}})]:[],...M?[z1(M,"w:embedRegular")]:[],...W?[z1(W,"w:embedBold")]:[],...I?[z1(I,"w:embedItalic")]:[],...F?[z1(F,"w:embedBoldItalic")]:[]]}),SZ=({name:B,index:U,fontKey:G,characterSet:Y})=>$Z({name:B,sig:{usb0:"E0002AFF",usb1:"C000247B",usb2:"00000009",usb3:"00000000",csb0:"000001FF",csb1:"00000000"},charset:Y,family:"auto",pitch:"variable",embedRegular:{fontKey:G,id:`rId${U}`}}),bZ=(B)=>new X0({name:"w:fonts",attributes:{mc:{key:"xmlns:mc",value:"http://schemas.openxmlformats.org/markup-compatibility/2006"},r:{key:"xmlns:r",value:"http://schemas.openxmlformats.org/officeDocument/2006/relationships"},w:{key:"xmlns:w",value:"http://schemas.openxmlformats.org/wordprocessingml/2006/main"},w14:{key:"xmlns:w14",value:"http://schemas.microsoft.com/office/word/2010/wordml"},w15:{key:"xmlns:w15",value:"http://schemas.microsoft.com/office/word/2012/wordml"},w16cex:{key:"xmlns:w16cex",value:"http://schemas.microsoft.com/office/word/2018/wordml/cex"},w16cid:{key:"xmlns:w16cid",value:"http://schemas.microsoft.com/office/word/2016/wordml/cid"},w16:{key:"xmlns:w16",value:"http://schemas.microsoft.com/office/word/2018/wordml"},w16sdtdh:{key:"xmlns:w16sdtdh",value:"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash"},w16se:{key:"xmlns:w16se",value:"http://schemas.microsoft.com/office/word/2015/wordml/symex"},Ignorable:{key:"mc:Ignorable",value:"w14 w15 w16se w16cid w16 w16cex w16sdtdh"}},children:B.map((U,G)=>SZ({name:U.name,index:G+1,fontKey:U.fontKey,characterSet:U.characterSet}))}),h4=class{constructor(B){e(this,"options",void 0),e(this,"fontTable",void 0),e(this,"relationships",void 0),e(this,"fontOptionsWithKey",[]),this.options=B,this.fontOptionsWithKey=B.map((U)=>L0(L0({},U),{},{fontKey:eB()})),this.fontTable=bZ(this.fontOptionsWithKey),this.relationships=new w2;for(let U=0;Unew X0({name:"w:wordWrap",attributes:{val:{key:"w:val",value:0}}}),yZ={NONE:"none",DROP:"drop",MARGIN:"margin"},gZ={MARGIN:"margin",PAGE:"page",TEXT:"text"},fZ={AROUND:"around",AUTO:"auto",NONE:"none",NOT_BESIDE:"notBeside",THROUGH:"through",TIGHT:"tight"},u4=(B)=>{var U,G;return new X0({name:"w:framePr",attributes:{anchorLock:{key:"w:anchorLock",value:B.anchorLock},dropCap:{key:"w:dropCap",value:B.dropCap},width:{key:"w:w",value:B.width},height:{key:"w:h",value:B.height},x:{key:"w:x",value:B.position?B.position.x:void 0},y:{key:"w:y",value:B.position?B.position.y:void 0},anchorHorizontal:{key:"w:hAnchor",value:B.anchor.horizontal},anchorVertical:{key:"w:vAnchor",value:B.anchor.vertical},spaceHorizontal:{key:"w:hSpace",value:(U=B.space)===null||U===void 0?void 0:U.horizontal},spaceVertical:{key:"w:vSpace",value:(G=B.space)===null||G===void 0?void 0:G.vertical},rule:{key:"w:hRule",value:B.rule},alignmentX:{key:"w:xAlign",value:B.alignment?B.alignment.x:void 0},alignmentY:{key:"w:yAlign",value:B.alignment?B.alignment.y:void 0},lines:{key:"w:lines",value:B.lines},wrap:{key:"w:wrap",value:B.wrap}}})},X2=class extends R2{constructor(B){super("w:pPr",B===null||B===void 0?void 0:B.includeIfEmpty);if(e(this,"numberingReferences",[]),!B)return this;if(B.heading)this.push(x2(B.heading));if(B.bullet)this.push(x2("ListParagraph"));if(B.numbering){if(!B.style&&!B.heading){if(!B.numbering.custom)this.push(x2("ListParagraph"))}}if(B.style)this.push(x2(B.style));if(B.keepNext!==void 0)this.push(new M0("w:keepNext",B.keepNext));if(B.keepLines!==void 0)this.push(new M0("w:keepLines",B.keepLines));if(B.pageBreakBefore)this.push(new $4);if(B.frame)this.push(u4(B.frame));if(B.widowControl!==void 0)this.push(new M0("w:widowControl",B.widowControl));if(B.bullet)this.push(new D1(1,B.bullet.level));if(B.numbering){var U,G;this.numberingReferences.push({reference:B.numbering.reference,instance:(U=B.numbering.instance)!==null&&U!==void 0?U:0}),this.push(new D1(`${B.numbering.reference}-${(G=B.numbering.instance)!==null&&G!==void 0?G:0}`,B.numbering.level))}else if(B.numbering===!1)this.push(new D1(0,0));if(B.border)this.push(new xB(B.border));if(B.thematicBreak)this.push(new _B);if(B.shading)this.push(X1(B.shading));if(B.wordWrap)this.push(vZ());if(B.overflowPunctuation)this.push(new M0("w:overflowPunct",B.overflowPunctuation));let Y=[...B.rightTabStop!==void 0?[{type:j8.RIGHT,position:B.rightTabStop}]:[],...B.tabStops?B.tabStops:[],...B.leftTabStop!==void 0?[{type:j8.LEFT,position:B.leftTabStop}]:[]];if(Y.length>0)this.push(v4(Y));if(B.bidirectional!==void 0)this.push(new M0("w:bidi",B.bidirectional));if(B.spacing)this.push(S4(B.spacing));if(B.indent)this.push(hB(B.indent));if(B.contextualSpacing!==void 0)this.push(new M0("w:contextualSpacing",B.contextualSpacing));if(B.alignment)this.push(c8(B.alignment));if(B.outlineLevel!==void 0)this.push(_4(B.outlineLevel));if(B.suppressLineNumbers!==void 0)this.push(new M0("w:suppressLineNumbers",B.suppressLineNumbers));if(B.autoSpaceEastAsianText!==void 0)this.push(new M0("w:autoSpaceDN",B.autoSpaceEastAsianText));if(B.run)this.push(new mB(B.run));if(B.revision)this.push(new d4(B.revision))}push(B){this.root.push(B)}prepForXml(B){if(!(B.viewWrapper instanceof h4))for(let U of this.numberingReferences)B.file.Numbering.createConcreteNumberingInstance(U.reference,U.instance);return super.prepForXml(B)}},d4=class extends t{constructor(B){super("w:pPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.root.push(new X2(L0(L0({},B),{},{includeIfEmpty:!0})))}},d0=class extends F1{constructor(B){super("w:p");if(e(this,"properties",void 0),typeof B==="string")return this.properties=new X2({}),this.root.push(this.properties),this.root.push(new Q1(B)),this;if(this.properties=new X2(B),this.root.push(this.properties),B.text)this.root.push(new Q1(B.text));if(B.children)for(let U of B.children){if(U instanceof g4){this.root.push(U.start);for(let G of U.children)this.root.push(G);this.root.push(U.end);continue}this.root.push(U)}}prepForXml(B){for(let U of this.root)if(U instanceof o8){let G=this.root.indexOf(U),Y=new m2(U.options.children,O1());B.viewWrapper.Relationships.addRelationship(Y.linkId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",U.options.link,j4.EXTERNAL),this.root[G]=Y}return super.prepForXml(B)}addRunToFront(B){return this.root.splice(1,0,B),this}},xZ=class extends t{constructor(B){super("m:oMath");for(let U of B.children)this.root.push(U)}},_Z=class extends t{constructor(B){super("m:t");this.root.push(B)}},hZ=class extends t{constructor(B){super("m:r");this.root.push(new _Z(B))}},c4=class extends t{constructor(B){super("m:den");for(let U of B)this.root.push(U)}},m4=class extends t{constructor(B){super("m:num");for(let U of B)this.root.push(U)}},uZ=class extends t{constructor(B){super("m:f");this.root.push(new m4(B.numerator)),this.root.push(new c4(B.denominator))}},l4=({accent:B})=>new X0({name:"m:chr",attributes:{accent:{key:"m:val",value:B}}}),y0=({children:B})=>new X0({name:"m:e",children:B}),a4=({value:B})=>new X0({name:"m:limLoc",attributes:{value:{key:"m:val",value:B||"undOvr"}}}),dZ=()=>new X0({name:"m:subHide",attributes:{hide:{key:"m:val",value:1}}}),cZ=()=>new X0({name:"m:supHide",attributes:{hide:{key:"m:val",value:1}}}),t8=({accent:B,hasSuperScript:U,hasSubScript:G,limitLocationVal:Y})=>new X0({name:"m:naryPr",children:[...B?[l4({accent:B})]:[],a4({value:Y}),...!U?[cZ()]:[],...!G?[dZ()]:[]]}),l2=({children:B})=>new X0({name:"m:sub",children:B}),a2=({children:B})=>new X0({name:"m:sup",children:B}),mZ=class extends t{constructor(B){super("m:nary");if(this.root.push(t8({accent:"∑",hasSuperScript:!!B.superScript,hasSubScript:!!B.subScript})),B.subScript)this.root.push(l2({children:B.subScript}));if(B.superScript)this.root.push(a2({children:B.superScript}));this.root.push(y0({children:B.children}))}},lZ=class extends t{constructor(B){super("m:nary");if(this.root.push(t8({accent:"",hasSuperScript:!!B.superScript,hasSubScript:!!B.subScript,limitLocationVal:"subSup"})),B.subScript)this.root.push(l2({children:B.subScript}));if(B.superScript)this.root.push(a2({children:B.superScript}));this.root.push(y0({children:B.children}))}},e8=class extends t{constructor(B){super("m:lim");for(let U of B)this.root.push(U)}},aZ=class extends t{constructor(B){super("m:limUpp");this.root.push(y0({children:B.children})),this.root.push(new e8(B.limit))}},pZ=class extends t{constructor(B){super("m:limLow");this.root.push(y0({children:B.children})),this.root.push(new e8(B.limit))}},p4=()=>new X0({name:"m:sSupPr"}),rZ=class extends t{constructor(B){super("m:sSup");this.root.push(p4()),this.root.push(y0({children:B.children})),this.root.push(a2({children:B.superScript}))}},r4=()=>new X0({name:"m:sSubPr"}),iZ=class extends t{constructor(B){super("m:sSub");this.root.push(r4()),this.root.push(y0({children:B.children})),this.root.push(l2({children:B.subScript}))}},i4=()=>new X0({name:"m:sSubSupPr"}),nZ=class extends t{constructor(B){super("m:sSubSup");this.root.push(i4()),this.root.push(y0({children:B.children})),this.root.push(l2({children:B.subScript})),this.root.push(a2({children:B.superScript}))}},n4=()=>new X0({name:"m:sPrePr"}),sZ=class extends X0{constructor({children:B,subScript:U,superScript:G}){super({name:"m:sPre",children:[n4(),y0({children:B}),l2({children:U}),a2({children:G})]})}},oZ="",s4=class extends t{constructor(B){super("m:deg");if(B)for(let U of B)this.root.push(U)}},tZ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{hide:"m:val"})}},eZ=class extends t{constructor(){super("m:degHide");this.root.push(new tZ({hide:1}))}},o4=class extends t{constructor(B){super("m:radPr");if(!B)this.root.push(new eZ)}},BQ=class extends t{constructor(B){super("m:rad");this.root.push(new o4(!!B.degree)),this.root.push(new s4(B.degree)),this.root.push(y0({children:B.children}))}},t4=class extends t{constructor(B){super("m:fName");for(let U of B)this.root.push(U)}},e4=class extends t{constructor(){super("m:funcPr")}},UQ=class extends t{constructor(B){super("m:func");this.root.push(new e4),this.root.push(new t4(B.name)),this.root.push(y0({children:B.children}))}},GQ=({character:B})=>new X0({name:"m:begChr",attributes:{character:{key:"m:val",value:B}}}),YQ=({character:B})=>new X0({name:"m:endChr",attributes:{character:{key:"m:val",value:B}}}),m1=({characters:B})=>new X0({name:"m:dPr",children:B?[GQ({character:B.beginningCharacter}),YQ({character:B.endingCharacter})]:[]}),ZQ=class extends t{constructor(B){super("m:d");this.root.push(m1({})),this.root.push(y0({children:B.children}))}},QQ=class extends t{constructor(B){super("m:d");this.root.push(m1({characters:{beginningCharacter:"[",endingCharacter:"]"}})),this.root.push(y0({children:B.children}))}},JQ=class extends t{constructor(B){super("m:d");this.root.push(m1({characters:{beginningCharacter:"{",endingCharacter:"}"}})),this.root.push(y0({children:B.children}))}},KQ=class extends t{constructor(B){super("m:d");this.root.push(m1({characters:{beginningCharacter:"〈",endingCharacter:"〉"}})),this.root.push(y0({children:B.children}))}},VQ=(B)=>new X0({name:"w:gridCol",attributes:B!==void 0?{width:{key:"w:w",value:E0(B)}}:void 0}),B9=class extends t{constructor(B,U){super("w:tblGrid");for(let G of B)this.root.push(VQ(G));if(U)this.root.push(new MQ(U))}},qQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id"})}},MQ=class extends t{constructor(B){super("w:tblGridChange");this.root.push(new qQ({id:B.id})),this.root.push(new B9(B.columnWidths))}},XQ=class extends t{constructor(B){super("w:ins");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.addChildElement(new Q1(B))}},RQ=class extends t{constructor(){super("w:delInstrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("PAGE")}},LQ=class extends t{constructor(){super("w:delInstrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("NUMPAGES")}},IQ=class extends t{constructor(){super("w:delInstrText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push("SECTIONPAGES")}},p6=class extends t{constructor(B){super("w:delText");this.root.push(new _0({space:x0.PRESERVE})),this.root.push(B)}},OQ=class extends t{constructor(B){super("w:del");e(this,"deletedTextRunWrapper",void 0),this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.deletedTextRunWrapper=new FQ(B),this.addChildElement(this.deletedTextRunWrapper)}},FQ=class extends t{constructor(B){super("w:r");if(this.root.push(new U2(B)),B.children)for(let U of B.children){if(typeof U==="string"){switch(U){case H2.CURRENT:this.root.push(e0()),this.root.push(new RQ),this.root.push(q2()),this.root.push(B2());break;case H2.TOTAL_PAGES:this.root.push(e0()),this.root.push(new LQ),this.root.push(q2()),this.root.push(B2());break;case H2.TOTAL_PAGES_IN_SECTION:this.root.push(e0()),this.root.push(new IQ),this.root.push(q2()),this.root.push(B2());break;default:this.root.push(new p6(U));break}continue}this.root.push(U)}else if(B.text)this.root.push(new p6(B.text));if(B.break)for(let U=0;Unew X0({name:"w:vAlign",attributes:{verticalAlign:{key:"w:val",value:B}}}),q9=({marginUnitType:B=b1.DXA,top:U,left:G,bottom:Y,right:Q})=>[{name:"w:top",size:U},{name:"w:left",size:G},{name:"w:bottom",size:Y},{name:"w:right",size:Q}].filter((K)=>K.size!==void 0).map(({name:K,size:Z})=>J1(K,{type:B,size:Z})),PQ=(B)=>{let U=q9(B);if(U.length===0)return;return new X0({name:"w:tblCellMar",children:U})},wQ=(B)=>{let U=q9(B);if(U.length===0)return;return new X0({name:"w:tcMar",children:U})},b1={AUTO:"auto",DXA:"dxa",NIL:"nil",PERCENTAGE:"pct"},J1=(B,{type:U=b1.AUTO,size:G})=>{let Y=G;if(U===b1.PERCENTAGE&&typeof G==="number")Y=`${G}%`;return new X0({name:B,attributes:{type:{key:"w:type",value:U},size:{key:"w:w",value:d8(Y)}}})},M9=class extends R2{constructor(B){super("w:tcBorders");if(B.top)this.root.push(A0("w:top",B.top));if(B.start)this.root.push(A0("w:start",B.start));if(B.left)this.root.push(A0("w:left",B.left));if(B.bottom)this.root.push(A0("w:bottom",B.bottom));if(B.end)this.root.push(A0("w:end",B.end));if(B.right)this.root.push(A0("w:right",B.right))}},AQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},X9=class extends t{constructor(B){super("w:gridSpan");this.root.push(new AQ({val:D0(B)}))}},U6={CONTINUE:"continue",RESTART:"restart"},jQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},N8=class extends t{constructor(B){super("w:vMerge");this.root.push(new jQ({val:B}))}},NQ={BOTTOM_TO_TOP_LEFT_TO_RIGHT:"btLr",LEFT_TO_RIGHT_TOP_TO_BOTTOM:"lrTb",TOP_TO_BOTTOM_RIGHT_TO_LEFT:"tbRl"},zQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},R9=class extends t{constructor(B){super("w:textDirection");this.root.push(new zQ({val:B}))}},L9=class extends R2{constructor(B){super("w:tcPr",B.includeIfEmpty);if(B.width)this.root.push(J1("w:tcW",B.width));if(B.columnSpan)this.root.push(new X9(B.columnSpan));if(B.verticalMerge)this.root.push(new N8(B.verticalMerge));else if(B.rowSpan&&B.rowSpan>1)this.root.push(new N8(U6.RESTART));if(B.borders)this.root.push(new M9(B.borders));if(B.shading)this.root.push(X1(B.shading));if(B.margins){let U=wQ(B.margins);if(U)this.root.push(U)}if(B.textDirection)this.root.push(new R9(B.textDirection));if(B.verticalAlign)this.root.push(B6(B.verticalAlign));if(B.insertion)this.root.push(new Y9(B.insertion));if(B.deletion)this.root.push(new Z9(B.deletion));if(B.revision)this.root.push(new EQ(B.revision));if(B.cellMerge)this.root.push(new J9(B.cellMerge))}},EQ=class extends t{constructor(B){super("w:tcPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.root.push(new L9(L0(L0({},B),{},{includeIfEmpty:!0})))}},G6=class extends t{constructor(B){super("w:tc");e(this,"options",void 0),this.options=B,this.root.push(new L9(B));for(let U of B.children)this.root.push(U)}prepForXml(B){if(!(this.root[this.root.length-1]instanceof d0))this.root.push(new d0({}));return super.prepForXml(B)}},v2={style:d1.NONE,size:0,color:"auto"},y2={style:d1.SINGLE,size:4,color:"auto"},Y6=class extends t{constructor(B){var U,G,Y,Q,K,Z;super("w:tblBorders");this.root.push(A0("w:top",(U=B.top)!==null&&U!==void 0?U:y2)),this.root.push(A0("w:left",(G=B.left)!==null&&G!==void 0?G:y2)),this.root.push(A0("w:bottom",(Y=B.bottom)!==null&&Y!==void 0?Y:y2)),this.root.push(A0("w:right",(Q=B.right)!==null&&Q!==void 0?Q:y2)),this.root.push(A0("w:insideH",(K=B.insideHorizontal)!==null&&K!==void 0?K:y2)),this.root.push(A0("w:insideV",(Z=B.insideVertical)!==null&&Z!==void 0?Z:y2))}};e(Y6,"NONE",{top:v2,bottom:v2,left:v2,right:v2,insideHorizontal:v2,insideVertical:v2});var TQ={MARGIN:"margin",PAGE:"page",TEXT:"text"},DQ={CENTER:"center",INSIDE:"inside",LEFT:"left",OUTSIDE:"outside",RIGHT:"right"},CQ={CENTER:"center",INSIDE:"inside",BOTTOM:"bottom",OUTSIDE:"outside",INLINE:"inline",TOP:"top"},kQ={NEVER:"never",OVERLAP:"overlap"},$Q=(B)=>new X0({name:"w:tblOverlap",attributes:{val:{key:"w:val",value:B}}}),I9=({horizontalAnchor:B,verticalAnchor:U,absoluteHorizontalPosition:G,relativeHorizontalPosition:Y,absoluteVerticalPosition:Q,relativeVerticalPosition:K,bottomFromText:Z,topFromText:J,leftFromText:M,rightFromText:W,overlap:I})=>new X0({name:"w:tblpPr",attributes:{leftFromText:{key:"w:leftFromText",value:M===void 0?void 0:E0(M)},rightFromText:{key:"w:rightFromText",value:W===void 0?void 0:E0(W)},topFromText:{key:"w:topFromText",value:J===void 0?void 0:E0(J)},bottomFromText:{key:"w:bottomFromText",value:Z===void 0?void 0:E0(Z)},absoluteHorizontalPosition:{key:"w:tblpX",value:G===void 0?void 0:t0(G)},absoluteVerticalPosition:{key:"w:tblpY",value:Q===void 0?void 0:t0(Q)},horizontalAnchor:{key:"w:horzAnchor",value:B},relativeHorizontalPosition:{key:"w:tblpXSpec",value:Y},relativeVerticalPosition:{key:"w:tblpYSpec",value:K},verticalAnchor:{key:"w:vertAnchor",value:U}},children:I?[$Q(I)]:void 0}),SQ={AUTOFIT:"autofit",FIXED:"fixed"},O9=(B)=>new X0({name:"w:tblLayout",attributes:{type:{key:"w:type",value:B}}}),bQ={DXA:"dxa",NIL:"nil"},F9=({type:B=bQ.DXA,value:U})=>new X0({name:"w:tblCellSpacing",attributes:{type:{key:"w:type",value:B},value:{key:"w:w",value:d8(U)}}}),H9=({firstRow:B,lastRow:U,firstColumn:G,lastColumn:Y,noHBand:Q,noVBand:K})=>new X0({name:"w:tblLook",attributes:{firstRow:{key:"w:firstRow",value:B},lastRow:{key:"w:lastRow",value:U},firstColumn:{key:"w:firstColumn",value:G},lastColumn:{key:"w:lastColumn",value:Y},noHBand:{key:"w:noHBand",value:Q},noVBand:{key:"w:noVBand",value:K}}}),Z6=class extends R2{constructor(B){super("w:tblPr",B.includeIfEmpty);if(B.style)this.root.push(new M2("w:tblStyle",B.style));if(B.float)this.root.push(I9(B.float));if(B.visuallyRightToLeft!==void 0)this.root.push(new M0("w:bidiVisual",B.visuallyRightToLeft));if(B.width)this.root.push(J1("w:tblW",B.width));if(B.alignment)this.root.push(c8(B.alignment));if(B.indent)this.root.push(J1("w:tblInd",B.indent));if(B.borders)this.root.push(new Y6(B.borders));if(B.shading)this.root.push(X1(B.shading));if(B.layout)this.root.push(O9(B.layout));if(B.cellMargin){let U=PQ(B.cellMargin);if(U)this.root.push(U)}if(B.tableLook)this.root.push(H9(B.tableLook));if(B.cellSpacing)this.root.push(F9(B.cellSpacing));if(B.revision)this.root.push(new vQ(B.revision))}},vQ=class extends t{constructor(B){super("w:tblPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.root.push(new Z6(L0(L0({},B),{},{includeIfEmpty:!0})))}},yQ=class extends F1{constructor({rows:B,width:U,columnWidths:G=Array(Math.max(...B.map((A)=>A.CellCount))).fill(100),columnWidthsRevision:Y,margins:Q,indent:K,float:Z,layout:J,style:M,borders:W,alignment:I,visuallyRightToLeft:F,tableLook:D,cellSpacing:w,revision:P}){super("w:tbl");this.root.push(new Z6({borders:W!==null&&W!==void 0?W:{},width:U!==null&&U!==void 0?U:{size:100},indent:K,float:Z,layout:J,style:M,alignment:I,cellMargin:Q,visuallyRightToLeft:F,tableLook:D,cellSpacing:w,revision:P})),this.root.push(new B9(G,Y));for(let A of B)this.root.push(A);B.forEach((A,E)=>{if(E===B.length-1)return;let C=0;A.cells.forEach((j)=>{if(j.options.rowSpan&&j.options.rowSpan>1){let v=new G6({rowSpan:j.options.rowSpan-1,columnSpan:j.options.columnSpan,borders:j.options.borders,children:[],verticalMerge:U6.CONTINUE});B[E+1].addCellToColumnIndex(v,C)}C+=j.options.columnSpan||1})})}},gQ={AUTO:"auto",ATLEAST:"atLeast",EXACT:"exact"},W9=(B,U)=>new X0({name:"w:trHeight",attributes:{value:{key:"w:val",value:E0(B)},rule:{key:"w:hRule",value:U}}}),Q6=class extends R2{constructor(B){super("w:trPr",B.includeIfEmpty);if(B.cantSplit!==void 0)this.root.push(new M0("w:cantSplit",B.cantSplit));if(B.tableHeader!==void 0)this.root.push(new M0("w:tblHeader",B.tableHeader));if(B.height)this.root.push(W9(B.height.value,B.height.rule));if(B.cellSpacing)this.root.push(F9(B.cellSpacing));if(B.insertion)this.root.push(new U9(B.insertion));if(B.deletion)this.root.push(new G9(B.deletion));if(B.revision)this.root.push(new P9(B.revision))}},P9=class extends t{constructor(B){super("w:trPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.root.push(new Q6(L0(L0({},B),{},{includeIfEmpty:!0})))}},fQ=class extends t{constructor(B){super("w:tr");e(this,"options",void 0),this.options=B,this.root.push(new Q6(B));for(let U of B.children)this.root.push(U)}get CellCount(){return this.options.children.length}get cells(){return this.root.filter((B)=>B instanceof G6)}addCellToIndex(B,U){this.root.splice(U+1,0,B)}addCellToColumnIndex(B,U){let G=this.columnIndexToRootIndex(U,!0);this.addCellToIndex(B,G-1)}rootIndexToColumnIndex(B){if(B<1||B>=this.root.length)throw Error(`cell 'rootIndex' should between 1 to ${this.root.length-1}`);let U=0;for(let G=1;G=this.root.length)if(U)return this.root.length;else throw Error(`cell 'columnIndex' should not great than ${G-1}`);let Q=this.root[Y];Y+=1,G+=Q&&Q.options.columnSpan||1}return Y-1}},xQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns",vt:"xmlns:vt"})}},_Q=class extends t{constructor(){super("Properties");this.root.push(new xQ({xmlns:"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",vt:"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"}))}},hQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns"})}},V2=(B,U)=>new X0({name:"Default",attributes:{contentType:{key:"ContentType",value:B},extension:{key:"Extension",value:U}}}),f0=(B,U)=>new X0({name:"Override",attributes:{contentType:{key:"ContentType",value:B},partName:{key:"PartName",value:U}}}),uQ=class extends t{constructor(){super("Types");this.root.push(new hQ({xmlns:"http://schemas.openxmlformats.org/package/2006/content-types"})),this.root.push(V2("image/png","png")),this.root.push(V2("image/jpeg","jpeg")),this.root.push(V2("image/jpeg","jpg")),this.root.push(V2("image/bmp","bmp")),this.root.push(V2("image/gif","gif")),this.root.push(V2("image/svg+xml","svg")),this.root.push(V2("application/vnd.openxmlformats-package.relationships+xml","rels")),this.root.push(V2("application/xml","xml")),this.root.push(V2("application/vnd.openxmlformats-officedocument.obfuscatedFont","odttf")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml","/word/document.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml","/word/styles.xml")),this.root.push(f0("application/vnd.openxmlformats-package.core-properties+xml","/docProps/core.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.custom-properties+xml","/docProps/custom.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.extended-properties+xml","/docProps/app.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml","/word/numbering.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml","/word/footnotes.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml","/word/endnotes.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml","/word/settings.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml","/word/comments.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml","/word/fontTable.xml"))}addCommentsExtended(){this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml","/word/commentsExtended.xml"))}addFooter(B){this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",`/word/footer${B}.xml`))}addHeader(B){this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",`/word/header${B}.xml`))}},v1={wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",cp:"http://schemas.openxmlformats.org/package/2006/metadata/core-properties",dc:"http://purl.org/dc/elements/1.1/",dcterms:"http://purl.org/dc/terms/",dcmitype:"http://purl.org/dc/dcmitype/",xsi:"http://www.w3.org/2001/XMLSchema-instance",cx:"http://schemas.microsoft.com/office/drawing/2014/chartex",cx1:"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex",cx2:"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex",cx3:"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex",cx4:"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex",cx5:"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex",cx6:"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex",cx7:"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex",cx8:"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex",aink:"http://schemas.microsoft.com/office/drawing/2016/ink",am3d:"http://schemas.microsoft.com/office/drawing/2017/model3d",w16cex:"http://schemas.microsoft.com/office/word/2018/wordml/cex",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16:"http://schemas.microsoft.com/office/word/2018/wordml",w16sdtdh:"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash",w16se:"http://schemas.microsoft.com/office/word/2015/wordml/symex"},H1=class extends F0{constructor(B,U){super(L0({Ignorable:U},Object.fromEntries(B.map((G)=>[G,v1[G]]))));e(this,"xmlKeys",L0({Ignorable:"mc:Ignorable"},Object.fromEntries(Object.keys(v1).map((G)=>[G,`xmlns:${G}`]))))}},dQ=class extends t{constructor(B){super("cp:coreProperties");if(this.root.push(new H1(["cp","dc","dcterms","dcmitype","xsi"])),B.title)this.root.push(new O2("dc:title",B.title));if(B.subject)this.root.push(new O2("dc:subject",B.subject));if(B.creator)this.root.push(new O2("dc:creator",B.creator));if(B.keywords)this.root.push(new O2("cp:keywords",B.keywords));if(B.description)this.root.push(new O2("dc:description",B.description));if(B.lastModifiedBy)this.root.push(new O2("cp:lastModifiedBy",B.lastModifiedBy));if(B.revision)this.root.push(new O2("cp:revision",String(B.revision)));this.root.push(new r6("dcterms:created")),this.root.push(new r6("dcterms:modified"))}},cQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{type:"xsi:type"})}},r6=class extends t{constructor(B){super(B);this.root.push(new cQ({type:"dcterms:W3CDTF"})),this.root.push(fB(new Date))}},mQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{xmlns:"xmlns",vt:"xmlns:vt"})}},lQ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{formatId:"fmtid",pid:"pid",name:"name"})}},aQ=class extends t{constructor(B,U){super("property");this.root.push(new lQ({formatId:"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",pid:B.toString(),name:U.name})),this.root.push(new pQ(U.value))}},pQ=class extends t{constructor(B){super("vt:lpwstr");this.root.push(B)}},rQ=class extends t{constructor(B){super("Properties");e(this,"nextId",void 0),e(this,"properties",[]),this.root.push(new mQ({xmlns:"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",vt:"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"})),this.nextId=2;for(let U of B)this.addCustomProperty(U)}prepForXml(B){return this.properties.forEach((U)=>this.root.push(U)),super.prepForXml(B)}addCustomProperty(B){this.properties.push(new aQ(this.nextId++,B))}},w9=({space:B,count:U,separate:G,equalWidth:Y,children:Q})=>new X0({name:"w:cols",attributes:{space:{key:"w:space",value:B===void 0?void 0:E0(B)},count:{key:"w:num",value:U===void 0?void 0:D0(U)},separate:{key:"w:sep",value:G},equalWidth:{key:"w:equalWidth",value:Y}},children:!Y&&Q?Q:void 0}),iQ={DEFAULT:"default",LINES:"lines",LINES_AND_CHARS:"linesAndChars",SNAP_TO_CHARS:"snapToChars"},A9=({type:B,linePitch:U,charSpace:G})=>new X0({name:"w:docGrid",attributes:{type:{key:"w:type",value:B},linePitch:{key:"w:linePitch",value:D0(U)},charSpace:{key:"w:charSpace",value:G?D0(G):void 0}}}),D2={DEFAULT:"default",FIRST:"first",EVEN:"even"},z8={HEADER:"w:headerReference",FOOTER:"w:footerReference"},C1=(B,U)=>new X0({name:B,attributes:{type:{key:"w:type",value:U.type||D2.DEFAULT},id:{key:"r:id",value:`rId${U.id}`}}}),nQ={NEW_PAGE:"newPage",NEW_SECTION:"newSection",CONTINUOUS:"continuous"},j9=({countBy:B,start:U,restart:G,distance:Y})=>new X0({name:"w:lnNumType",attributes:{countBy:{key:"w:countBy",value:B===void 0?void 0:D0(B)},start:{key:"w:start",value:U===void 0?void 0:D0(U)},restart:{key:"w:restart",value:G},distance:{key:"w:distance",value:Y===void 0?void 0:E0(Y)}}}),sQ={ALL_PAGES:"allPages",FIRST_PAGE:"firstPage",NOT_FIRST_PAGE:"notFirstPage"},oQ={PAGE:"page",TEXT:"text"},tQ={BACK:"back",FRONT:"front"},i6=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{display:"w:display",offsetFrom:"w:offsetFrom",zOrder:"w:zOrder"})}},N9=class extends R2{constructor(B){super("w:pgBorders");if(!B)return this;if(B.pageBorders)this.root.push(new i6({display:B.pageBorders.display,offsetFrom:B.pageBorders.offsetFrom,zOrder:B.pageBorders.zOrder}));else this.root.push(new i6({}));if(B.pageBorderTop)this.root.push(A0("w:top",B.pageBorderTop));if(B.pageBorderLeft)this.root.push(A0("w:left",B.pageBorderLeft));if(B.pageBorderBottom)this.root.push(A0("w:bottom",B.pageBorderBottom));if(B.pageBorderRight)this.root.push(A0("w:right",B.pageBorderRight))}},z9=(B,U,G,Y,Q,K,Z)=>new X0({name:"w:pgMar",attributes:{top:{key:"w:top",value:t0(B)},right:{key:"w:right",value:E0(U)},bottom:{key:"w:bottom",value:t0(G)},left:{key:"w:left",value:E0(Y)},header:{key:"w:header",value:E0(Q)},footer:{key:"w:footer",value:E0(K)},gutter:{key:"w:gutter",value:E0(Z)}}}),eQ={HYPHEN:"hyphen",PERIOD:"period",COLON:"colon",EM_DASH:"emDash",EN_DASH:"endash"},E9=({start:B,formatType:U,separator:G})=>new X0({name:"w:pgNumType",attributes:{start:{key:"w:start",value:B===void 0?void 0:D0(B)},formatType:{key:"w:fmt",value:U},separator:{key:"w:chapSep",value:G}}}),y1={PORTRAIT:"portrait",LANDSCAPE:"landscape"},T9=({width:B,height:U,orientation:G,code:Y})=>{let Q=E0(B),K=E0(U);return new X0({name:"w:pgSz",attributes:{width:{key:"w:w",value:G===y1.LANDSCAPE?K:Q},height:{key:"w:h",value:G===y1.LANDSCAPE?Q:K},orientation:{key:"w:orient",value:G},code:{key:"w:code",value:Y}}})},BJ={LEFT_TO_RIGHT_TOP_TO_BOTTOM:"lrTb",TOP_TO_BOTTOM_RIGHT_TO_LEFT:"tbRl"},UJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},D9=class extends t{constructor(B){super("w:textDirection");this.root.push(new UJ({val:B}))}},GJ={NEXT_PAGE:"nextPage",NEXT_COLUMN:"nextColumn",CONTINUOUS:"continuous",EVEN_PAGE:"evenPage",ODD_PAGE:"oddPage"},C9=(B)=>new X0({name:"w:type",attributes:{val:{key:"w:val",value:B}}}),F2={TOP:1440,RIGHT:1440,BOTTOM:1440,LEFT:1440,HEADER:708,FOOTER:708,GUTTER:0},k1={WIDTH:11906,HEIGHT:16838,ORIENTATION:y1.PORTRAIT},J6=class extends t{constructor({page:{size:{width:B=k1.WIDTH,height:U=k1.HEIGHT,orientation:G=k1.ORIENTATION,code:Y}={},margin:{top:Q=F2.TOP,right:K=F2.RIGHT,bottom:Z=F2.BOTTOM,left:J=F2.LEFT,header:M=F2.HEADER,footer:W=F2.FOOTER,gutter:I=F2.GUTTER}={},pageNumbers:F={},borders:D,textDirection:w}={},grid:{linePitch:P=360,charSpace:A,type:E}={},headerWrapperGroup:C={},footerWrapperGroup:j={},lineNumbers:v,titlePage:S,verticalAlign:H,column:X,type:$,revision:x}={}){super("w:sectPr");if(this.addHeaderFooterGroup(z8.HEADER,C),this.addHeaderFooterGroup(z8.FOOTER,j),$)this.root.push(C9($));if(this.root.push(T9({width:B,height:U,orientation:G,code:Y})),this.root.push(z9(Q,K,Z,J,M,W,I)),D)this.root.push(new N9(D));if(v)this.root.push(j9(v));if(this.root.push(E9(F)),X)this.root.push(w9(X));if(H)this.root.push(B6(H));if(S!==void 0)this.root.push(new M0("w:titlePg",S));if(w)this.root.push(new D9(w));if(x)this.root.push(new k9(x));this.root.push(A9({linePitch:P,charSpace:A,type:E}))}addHeaderFooterGroup(B,U){if(U.default)this.root.push(C1(B,{type:D2.DEFAULT,id:U.default.View.ReferenceId}));if(U.first)this.root.push(C1(B,{type:D2.FIRST,id:U.first.View.ReferenceId}));if(U.even)this.root.push(C1(B,{type:D2.EVEN,id:U.even.View.ReferenceId}))}},k9=class extends t{constructor(B){super("w:sectPrChange");this.root.push(new b0({id:B.id,author:B.author,date:B.date})),this.root.push(new J6(B))}},YJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{width:"w:w",space:"w:space"})}},ZJ=class extends t{constructor(B){super("w:col");this.root.push(new YJ({width:E0(B.width),space:B.space===void 0?void 0:E0(B.space)}))}},$9=class extends t{constructor(){super("w:body");e(this,"sections",[])}addSection(B){let U=this.sections.pop();this.root.push(this.createSectionParagraph(U)),this.sections.push(new J6(B))}prepForXml(B){if(this.sections.length===1)this.root.splice(0,1),this.root.push(this.sections.pop());return super.prepForXml(B)}push(B){this.root.push(B)}createSectionParagraph(B){let U=new d0({}),G=new X2({});return G.push(B),U.addChildElement(G),U}},S9=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{color:"w:color",themeColor:"w:themeColor",themeShade:"w:themeShade",themeTint:"w:themeTint"})}},b9=class extends t{constructor(B){super("w:background");this.root.push(new S9({color:B.color===void 0?void 0:C2(B.color),themeColor:B.themeColor,themeShade:B.themeShade===void 0?void 0:H8(B.themeShade),themeTint:B.themeTint===void 0?void 0:H8(B.themeTint)}))}},QJ=class extends t{constructor(B){super("w:document");if(e(this,"body",void 0),this.root.push(new H1(["wpc","mc","o","r","m","v","wp14","wp","w10","w","w14","w15","wpg","wpi","wne","wps","cx","cx1","cx2","cx3","cx4","cx5","cx6","cx7","cx8","aink","am3d","w16cex","w16cid","w16","w16sdtdh","w16se"],"w14 w15 wp14")),this.body=new $9,B.background)this.root.push(new b9(B.background));this.root.push(this.body)}add(B){return this.body.push(B),this}get Body(){return this.body}},JJ=class{constructor(B){e(this,"document",void 0),e(this,"relationships",void 0),this.document=new QJ(B),this.relationships=new w2}get View(){return this.document}get Relationships(){return this.relationships}},KJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",Ignorable:"mc:Ignorable"})}},VJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{type:"w:type",id:"w:id"})}},qJ=class extends T0{constructor(){super({style:"EndnoteReference"});this.root.push(new T4)}},n6={SEPARATOR:"separator",CONTINUATION_SEPARATOR:"continuationSeparator"},V8=class extends t{constructor(B){super("w:endnote");this.root.push(new VJ({type:B.type,id:B.id}));for(let U=0;U9)throw Error("Level cannot be greater than 9. Read more here: https://answers.microsoft.com/en-us/msoffice/forum/all/does-word-support-more-than-9-list-levels/d130fdcd-1781-446d-8c84-c6c79124e4d7");this.root.push(new NJ({ilvl:D0(B),tentative:1}))}},h9=class extends V6{},$J=class extends V6{},SJ=class extends t{constructor(B){super("w:multiLevelType");this.root.push(new C0({val:B}))}},bJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{abstractNumId:"w:abstractNumId",restartNumberingAfterBreak:"w15:restartNumberingAfterBreak"})}},E8=class extends t{constructor(B,U){super("w:abstractNum");e(this,"id",void 0),this.root.push(new bJ({abstractNumId:D0(B),restartNumberingAfterBreak:0})),this.root.push(new SJ("hybridMultilevel")),this.id=B;for(let G of U)this.root.push(new h9(G))}},vJ=class extends t{constructor(B){super("w:abstractNumId");this.root.push(new C0({val:B}))}},yJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{numId:"w:numId"})}},T8=class extends t{constructor(B){super("w:num");if(e(this,"numId",void 0),e(this,"reference",void 0),e(this,"instance",void 0),this.numId=B.numId,this.reference=B.reference,this.instance=B.instance,this.root.push(new yJ({numId:D0(B.numId)})),this.root.push(new vJ(D0(B.abstractNumId))),B.overrideLevels&&B.overrideLevels.length)for(let U of B.overrideLevels)this.root.push(new u9(U.num,U.start))}},gJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{ilvl:"w:ilvl"})}},u9=class extends t{constructor(B,U){super("w:lvlOverride");if(this.root.push(new gJ({ilvl:B})),U!==void 0)this.root.push(new xJ(U))}},fJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},xJ=class extends t{constructor(B){super("w:startOverride");this.root.push(new fJ({val:B}))}},d9=class extends t{constructor(B){super("w:numbering");e(this,"abstractNumberingMap",new Map),e(this,"concreteNumberingMap",new Map),e(this,"referenceConfigMap",new Map),e(this,"abstractNumUniqueNumericId",nB()),e(this,"concreteNumUniqueNumericId",sB()),this.root.push(new H1(["wpc","mc","o","r","m","v","wp14","wp","w10","w","w14","w15","wpg","wpi","wne","wps"],"w14 w15 wp14"));let U=new E8(this.abstractNumUniqueNumericId(),[{level:0,format:i0.BULLET,text:"●",alignment:c0.LEFT,style:{paragraph:{indent:{left:u0(0.5),hanging:u0(0.25)}}}},{level:1,format:i0.BULLET,text:"○",alignment:c0.LEFT,style:{paragraph:{indent:{left:u0(1),hanging:u0(0.25)}}}},{level:2,format:i0.BULLET,text:"■",alignment:c0.LEFT,style:{paragraph:{indent:{left:2160,hanging:u0(0.25)}}}},{level:3,format:i0.BULLET,text:"●",alignment:c0.LEFT,style:{paragraph:{indent:{left:2880,hanging:u0(0.25)}}}},{level:4,format:i0.BULLET,text:"○",alignment:c0.LEFT,style:{paragraph:{indent:{left:3600,hanging:u0(0.25)}}}},{level:5,format:i0.BULLET,text:"■",alignment:c0.LEFT,style:{paragraph:{indent:{left:4320,hanging:u0(0.25)}}}},{level:6,format:i0.BULLET,text:"●",alignment:c0.LEFT,style:{paragraph:{indent:{left:5040,hanging:u0(0.25)}}}},{level:7,format:i0.BULLET,text:"●",alignment:c0.LEFT,style:{paragraph:{indent:{left:5760,hanging:u0(0.25)}}}},{level:8,format:i0.BULLET,text:"●",alignment:c0.LEFT,style:{paragraph:{indent:{left:6480,hanging:u0(0.25)}}}}]);this.concreteNumberingMap.set("default-bullet-numbering",new T8({numId:1,abstractNumId:U.id,reference:"default-bullet-numbering",instance:0,overrideLevels:[{num:0,start:1}]})),this.abstractNumberingMap.set("default-bullet-numbering",U);for(let G of B.config)this.abstractNumberingMap.set(G.reference,new E8(this.abstractNumUniqueNumericId(),G.levels)),this.referenceConfigMap.set(G.reference,G.levels)}prepForXml(B){for(let U of this.abstractNumberingMap.values())this.root.push(U);for(let U of this.concreteNumberingMap.values())this.root.push(U);return super.prepForXml(B)}createConcreteNumberingInstance(B,U){let G=this.abstractNumberingMap.get(B);if(!G)return;let Y=`${B}-${U}`;if(this.concreteNumberingMap.has(Y))return;let Q=this.referenceConfigMap.get(B),K=Q&&Q[0].start,Z={numId:this.concreteNumUniqueNumericId(),abstractNumId:G.id,reference:B,instance:U,overrideLevels:[typeof K==="number"&&Number.isInteger(K)?{num:0,start:K}:{num:0,start:1}]};this.concreteNumberingMap.set(Y,new T8(Z))}get ConcreteNumbering(){return Array.from(this.concreteNumberingMap.values())}get ReferenceConfig(){return Array.from(this.referenceConfigMap.values())}},_J=(B)=>new X0({name:"w:compatSetting",attributes:{version:{key:"w:val",value:B},name:{key:"w:name",value:"compatibilityMode"},uri:{key:"w:uri",value:"http://schemas.microsoft.com/office/word"}}}),hJ=class extends t{constructor(B){super("w:compat");if(B.version)this.root.push(_J(B.version));if(B.useSingleBorderforContiguousCells)this.root.push(new M0("w:useSingleBorderforContiguousCells",B.useSingleBorderforContiguousCells));if(B.wordPerfectJustification)this.root.push(new M0("w:wpJustification",B.wordPerfectJustification));if(B.noTabStopForHangingIndent)this.root.push(new M0("w:noTabHangInd",B.noTabStopForHangingIndent));if(B.noLeading)this.root.push(new M0("w:noLeading",B.noLeading));if(B.spaceForUnderline)this.root.push(new M0("w:spaceForUL",B.spaceForUnderline));if(B.noColumnBalance)this.root.push(new M0("w:noColumnBalance",B.noColumnBalance));if(B.balanceSingleByteDoubleByteWidth)this.root.push(new M0("w:balanceSingleByteDoubleByteWidth",B.balanceSingleByteDoubleByteWidth));if(B.noExtraLineSpacing)this.root.push(new M0("w:noExtraLineSpacing",B.noExtraLineSpacing));if(B.doNotLeaveBackslashAlone)this.root.push(new M0("w:doNotLeaveBackslashAlone",B.doNotLeaveBackslashAlone));if(B.underlineTrailingSpaces)this.root.push(new M0("w:ulTrailSpace",B.underlineTrailingSpaces));if(B.doNotExpandShiftReturn)this.root.push(new M0("w:doNotExpandShiftReturn",B.doNotExpandShiftReturn));if(B.spacingInWholePoints)this.root.push(new M0("w:spacingInWholePoints",B.spacingInWholePoints));if(B.lineWrapLikeWord6)this.root.push(new M0("w:lineWrapLikeWord6",B.lineWrapLikeWord6));if(B.printBodyTextBeforeHeader)this.root.push(new M0("w:printBodyTextBeforeHeader",B.printBodyTextBeforeHeader));if(B.printColorsBlack)this.root.push(new M0("w:printColBlack",B.printColorsBlack));if(B.spaceWidth)this.root.push(new M0("w:wpSpaceWidth",B.spaceWidth));if(B.showBreaksInFrames)this.root.push(new M0("w:showBreaksInFrames",B.showBreaksInFrames));if(B.subFontBySize)this.root.push(new M0("w:subFontBySize",B.subFontBySize));if(B.suppressBottomSpacing)this.root.push(new M0("w:suppressBottomSpacing",B.suppressBottomSpacing));if(B.suppressTopSpacing)this.root.push(new M0("w:suppressTopSpacing",B.suppressTopSpacing));if(B.suppressSpacingAtTopOfPage)this.root.push(new M0("w:suppressSpacingAtTopOfPage",B.suppressSpacingAtTopOfPage));if(B.suppressTopSpacingWP)this.root.push(new M0("w:suppressTopSpacingWP",B.suppressTopSpacingWP));if(B.suppressSpBfAfterPgBrk)this.root.push(new M0("w:suppressSpBfAfterPgBrk",B.suppressSpBfAfterPgBrk));if(B.swapBordersFacingPages)this.root.push(new M0("w:swapBordersFacingPages",B.swapBordersFacingPages));if(B.convertMailMergeEsc)this.root.push(new M0("w:convMailMergeEsc",B.convertMailMergeEsc));if(B.truncateFontHeightsLikeWP6)this.root.push(new M0("w:truncateFontHeightsLikeWP6",B.truncateFontHeightsLikeWP6));if(B.macWordSmallCaps)this.root.push(new M0("w:mwSmallCaps",B.macWordSmallCaps));if(B.usePrinterMetrics)this.root.push(new M0("w:usePrinterMetrics",B.usePrinterMetrics));if(B.doNotSuppressParagraphBorders)this.root.push(new M0("w:doNotSuppressParagraphBorders",B.doNotSuppressParagraphBorders));if(B.wrapTrailSpaces)this.root.push(new M0("w:wrapTrailSpaces",B.wrapTrailSpaces));if(B.footnoteLayoutLikeWW8)this.root.push(new M0("w:footnoteLayoutLikeWW8",B.footnoteLayoutLikeWW8));if(B.shapeLayoutLikeWW8)this.root.push(new M0("w:shapeLayoutLikeWW8",B.shapeLayoutLikeWW8));if(B.alignTablesRowByRow)this.root.push(new M0("w:alignTablesRowByRow",B.alignTablesRowByRow));if(B.forgetLastTabAlignment)this.root.push(new M0("w:forgetLastTabAlignment",B.forgetLastTabAlignment));if(B.adjustLineHeightInTable)this.root.push(new M0("w:adjustLineHeightInTable",B.adjustLineHeightInTable));if(B.autoSpaceLikeWord95)this.root.push(new M0("w:autoSpaceLikeWord95",B.autoSpaceLikeWord95));if(B.noSpaceRaiseLower)this.root.push(new M0("w:noSpaceRaiseLower",B.noSpaceRaiseLower));if(B.doNotUseHTMLParagraphAutoSpacing)this.root.push(new M0("w:doNotUseHTMLParagraphAutoSpacing",B.doNotUseHTMLParagraphAutoSpacing));if(B.layoutRawTableWidth)this.root.push(new M0("w:layoutRawTableWidth",B.layoutRawTableWidth));if(B.layoutTableRowsApart)this.root.push(new M0("w:layoutTableRowsApart",B.layoutTableRowsApart));if(B.useWord97LineBreakRules)this.root.push(new M0("w:useWord97LineBreakRules",B.useWord97LineBreakRules));if(B.doNotBreakWrappedTables)this.root.push(new M0("w:doNotBreakWrappedTables",B.doNotBreakWrappedTables));if(B.doNotSnapToGridInCell)this.root.push(new M0("w:doNotSnapToGridInCell",B.doNotSnapToGridInCell));if(B.selectFieldWithFirstOrLastCharacter)this.root.push(new M0("w:selectFldWithFirstOrLastChar",B.selectFieldWithFirstOrLastCharacter));if(B.applyBreakingRules)this.root.push(new M0("w:applyBreakingRules",B.applyBreakingRules));if(B.doNotWrapTextWithPunctuation)this.root.push(new M0("w:doNotWrapTextWithPunct",B.doNotWrapTextWithPunctuation));if(B.doNotUseEastAsianBreakRules)this.root.push(new M0("w:doNotUseEastAsianBreakRules",B.doNotUseEastAsianBreakRules));if(B.useWord2002TableStyleRules)this.root.push(new M0("w:useWord2002TableStyleRules",B.useWord2002TableStyleRules));if(B.growAutofit)this.root.push(new M0("w:growAutofit",B.growAutofit));if(B.useFELayout)this.root.push(new M0("w:useFELayout",B.useFELayout));if(B.useNormalStyleForList)this.root.push(new M0("w:useNormalStyleForList",B.useNormalStyleForList));if(B.doNotUseIndentAsNumberingTabStop)this.root.push(new M0("w:doNotUseIndentAsNumberingTabStop",B.doNotUseIndentAsNumberingTabStop));if(B.useAlternateEastAsianLineBreakRules)this.root.push(new M0("w:useAltKinsokuLineBreakRules",B.useAlternateEastAsianLineBreakRules));if(B.allowSpaceOfSameStyleInTable)this.root.push(new M0("w:allowSpaceOfSameStyleInTable",B.allowSpaceOfSameStyleInTable));if(B.doNotSuppressIndentation)this.root.push(new M0("w:doNotSuppressIndentation",B.doNotSuppressIndentation));if(B.doNotAutofitConstrainedTables)this.root.push(new M0("w:doNotAutofitConstrainedTables",B.doNotAutofitConstrainedTables));if(B.autofitToFirstFixedWidthCell)this.root.push(new M0("w:autofitToFirstFixedWidthCell",B.autofitToFirstFixedWidthCell));if(B.underlineTabInNumberingList)this.root.push(new M0("w:underlineTabInNumList",B.underlineTabInNumberingList));if(B.displayHangulFixedWidth)this.root.push(new M0("w:displayHangulFixedWidth",B.displayHangulFixedWidth));if(B.splitPgBreakAndParaMark)this.root.push(new M0("w:splitPgBreakAndParaMark",B.splitPgBreakAndParaMark));if(B.doNotVerticallyAlignCellWithSp)this.root.push(new M0("w:doNotVertAlignCellWithSp",B.doNotVerticallyAlignCellWithSp));if(B.doNotBreakConstrainedForcedTable)this.root.push(new M0("w:doNotBreakConstrainedForcedTable",B.doNotBreakConstrainedForcedTable));if(B.ignoreVerticalAlignmentInTextboxes)this.root.push(new M0("w:doNotVertAlignInTxbx",B.ignoreVerticalAlignmentInTextboxes));if(B.useAnsiKerningPairs)this.root.push(new M0("w:useAnsiKerningPairs",B.useAnsiKerningPairs));if(B.cachedColumnBalance)this.root.push(new M0("w:cachedColBalance",B.cachedColumnBalance))}},uJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",Ignorable:"mc:Ignorable"})}},dJ=class extends t{constructor(B){var U,G,Y,Q,K,Z,J,M;super("w:settings");if(this.root.push(new uJ({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",Ignorable:"w14 w15 wp14"})),this.root.push(new M0("w:displayBackgroundShape",!0)),B.trackRevisions!==void 0)this.root.push(new M0("w:trackRevisions",B.trackRevisions));if(B.evenAndOddHeaders!==void 0)this.root.push(new M0("w:evenAndOddHeaders",B.evenAndOddHeaders));if(B.updateFields!==void 0)this.root.push(new M0("w:updateFields",B.updateFields));if(B.defaultTabStop!==void 0)this.root.push(new _2("w:defaultTabStop",B.defaultTabStop));if(((U=B.hyphenation)===null||U===void 0?void 0:U.autoHyphenation)!==void 0)this.root.push(new M0("w:autoHyphenation",B.hyphenation.autoHyphenation));if(((G=B.hyphenation)===null||G===void 0?void 0:G.hyphenationZone)!==void 0)this.root.push(new _2("w:hyphenationZone",B.hyphenation.hyphenationZone));if(((Y=B.hyphenation)===null||Y===void 0?void 0:Y.consecutiveHyphenLimit)!==void 0)this.root.push(new _2("w:consecutiveHyphenLimit",B.hyphenation.consecutiveHyphenLimit));if(((Q=B.hyphenation)===null||Q===void 0?void 0:Q.doNotHyphenateCaps)!==void 0)this.root.push(new M0("w:doNotHyphenateCaps",B.hyphenation.doNotHyphenateCaps));this.root.push(new hJ(L0(L0({},(K=B.compatibility)!==null&&K!==void 0?K:{}),{},{version:(Z=(J=(M=B.compatibility)===null||M===void 0?void 0:M.version)!==null&&J!==void 0?J:B.compatibilityModeVersion)!==null&&Z!==void 0?Z:15})))}},c9=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w:val"})}},cJ=class extends t{constructor(B){super("w:name");this.root.push(new c9({val:B}))}},mJ=class extends t{constructor(B){super("w:uiPriority");this.root.push(new c9({val:D0(B)}))}},lJ=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{type:"w:type",styleId:"w:styleId",default:"w:default",customStyle:"w:customStyle"})}},m9=class extends t{constructor(B,U){super("w:style");if(this.root.push(new lJ(B)),U.name)this.root.push(new cJ(U.name));if(U.basedOn)this.root.push(new M2("w:basedOn",U.basedOn));if(U.next)this.root.push(new M2("w:next",U.next));if(U.link)this.root.push(new M2("w:link",U.link));if(U.uiPriority!==void 0)this.root.push(new mJ(U.uiPriority));if(U.semiHidden!==void 0)this.root.push(new M0("w:semiHidden",U.semiHidden));if(U.unhideWhenUsed!==void 0)this.root.push(new M0("w:unhideWhenUsed",U.unhideWhenUsed));if(U.quickFormat!==void 0)this.root.push(new M0("w:qFormat",U.quickFormat))}},p2=class extends m9{constructor(B){super({type:"paragraph",styleId:B.id},B);e(this,"paragraphProperties",void 0),e(this,"runProperties",void 0),this.paragraphProperties=new X2(B.paragraph),this.runProperties=new U2(B.run),this.root.push(this.paragraphProperties),this.root.push(this.runProperties)}},$2=class extends m9{constructor(B){super({type:"character",styleId:B.id},L0({uiPriority:99,unhideWhenUsed:!0},B));e(this,"runProperties",void 0),this.runProperties=new U2(B.run),this.root.push(this.runProperties)}},A2=class extends p2{constructor(B){super(L0({basedOn:"Normal",next:"Normal",quickFormat:!0},B))}},aJ=class extends A2{constructor(B){super(L0({id:"Title",name:"Title"},B))}},pJ=class extends A2{constructor(B){super(L0({id:"Heading1",name:"Heading 1"},B))}},rJ=class extends A2{constructor(B){super(L0({id:"Heading2",name:"Heading 2"},B))}},iJ=class extends A2{constructor(B){super(L0({id:"Heading3",name:"Heading 3"},B))}},nJ=class extends A2{constructor(B){super(L0({id:"Heading4",name:"Heading 4"},B))}},sJ=class extends A2{constructor(B){super(L0({id:"Heading5",name:"Heading 5"},B))}},oJ=class extends A2{constructor(B){super(L0({id:"Heading6",name:"Heading 6"},B))}},tJ=class extends A2{constructor(B){super(L0({id:"Strong",name:"Strong"},B))}},eJ=class extends p2{constructor(B){super(L0({id:"ListParagraph",name:"List Paragraph",basedOn:"Normal",quickFormat:!0},B))}},BK=class extends p2{constructor(B){super(L0({id:"FootnoteText",name:"footnote text",link:"FootnoteTextChar",basedOn:"Normal",uiPriority:99,semiHidden:!0,unhideWhenUsed:!0,paragraph:{spacing:{after:0,line:240,lineRule:k2.AUTO}},run:{size:20}},B))}},UK=class extends $2{constructor(B){super(L0({id:"FootnoteReference",name:"footnote reference",basedOn:"DefaultParagraphFont",semiHidden:!0,run:{superScript:!0}},B))}},GK=class extends $2{constructor(B){super(L0({id:"FootnoteTextChar",name:"Footnote Text Char",basedOn:"DefaultParagraphFont",link:"FootnoteText",semiHidden:!0,run:{size:20}},B))}},YK=class extends p2{constructor(B){super(L0({id:"EndnoteText",name:"endnote text",link:"EndnoteTextChar",basedOn:"Normal",uiPriority:99,semiHidden:!0,unhideWhenUsed:!0,paragraph:{spacing:{after:0,line:240,lineRule:k2.AUTO}},run:{size:20}},B))}},ZK=class extends $2{constructor(B){super(L0({id:"EndnoteReference",name:"endnote reference",basedOn:"DefaultParagraphFont",semiHidden:!0,run:{superScript:!0}},B))}},QK=class extends $2{constructor(B){super(L0({id:"EndnoteTextChar",name:"Endnote Text Char",basedOn:"DefaultParagraphFont",link:"EndnoteText",semiHidden:!0,run:{size:20}},B))}},JK=class extends $2{constructor(B){super(L0({id:"Hyperlink",name:"Hyperlink",basedOn:"DefaultParagraphFont",run:{color:"0563C1",underline:{type:r8.SINGLE}}},B))}},$1=class extends t{constructor(B){super("w:styles");if(B.initialStyles)this.root.push(B.initialStyles);if(B.importedStyles)for(let U of B.importedStyles)this.root.push(U);if(B.paragraphStyles)for(let U of B.paragraphStyles)this.root.push(new p2(U));if(B.characterStyles)for(let U of B.characterStyles)this.root.push(new $2(U))}},l9=class extends t{constructor(B){super("w:pPrDefault");this.root.push(new X2(B))}},a9=class extends t{constructor(B){super("w:rPrDefault");this.root.push(new U2(B))}},p9=class extends t{constructor(B){super("w:docDefaults");e(this,"runPropertiesDefaults",void 0),e(this,"paragraphPropertiesDefaults",void 0),this.runPropertiesDefaults=new a9(B.run),this.paragraphPropertiesDefaults=new l9(B.paragraph),this.root.push(this.runPropertiesDefaults),this.root.push(this.paragraphPropertiesDefaults)}},KK=class{newInstance(B){let U=(0,_1.xml2js)(B,{compact:!1}),G;for(let Q of U.elements||[])if(Q.name==="w:styles")G=Q;if(G===void 0)throw Error("can not find styles element");let Y=G.elements||[];return{initialStyles:new $B(G.attributes),importedStyles:Y.map((Q)=>h1(Q))}}},M8=class{newInstance(B={}){var U;return{initialStyles:new H1(["mc","r","w","w14","w15"],"w14 w15"),importedStyles:[new p9((U=B.document)!==null&&U!==void 0?U:{}),new aJ(L0({run:{size:56}},B.title)),new pJ(L0({run:{color:"2E74B5",size:32}},B.heading1)),new rJ(L0({run:{color:"2E74B5",size:26}},B.heading2)),new iJ(L0({run:{color:"1F4D78",size:24}},B.heading3)),new nJ(L0({run:{color:"2E74B5",italics:!0}},B.heading4)),new sJ(L0({run:{color:"2E74B5"}},B.heading5)),new oJ(L0({run:{color:"1F4D78"}},B.heading6)),new tJ(L0({run:{bold:!0}},B.strong)),new eJ(B.listParagraph||{}),new JK(B.hyperlink||{}),new UK(B.footnoteReference||{}),new BK(B.footnoteText||{}),new GK(B.footnoteTextChar||{}),new ZK(B.endnoteReference||{}),new YK(B.endnoteText||{}),new QK(B.endnoteTextChar||{})]}}},VK=class{constructor(B){var U,G,Y,Q,K,Z,J,M,W,I,F,D;if(e(this,"currentRelationshipId",1),e(this,"documentWrapper",void 0),e(this,"headers",[]),e(this,"footers",[]),e(this,"coreProperties",void 0),e(this,"numbering",void 0),e(this,"media",void 0),e(this,"fileRelationships",void 0),e(this,"footnotesWrapper",void 0),e(this,"endnotesWrapper",void 0),e(this,"settings",void 0),e(this,"contentTypes",void 0),e(this,"customProperties",void 0),e(this,"appProperties",void 0),e(this,"styles",void 0),e(this,"comments",void 0),e(this,"commentsExtended",void 0),e(this,"fontWrapper",void 0),this.coreProperties=new dQ(L0(L0({},B),{},{creator:(U=B.creator)!==null&&U!==void 0?U:"Un-named",revision:(G=B.revision)!==null&&G!==void 0?G:1,lastModifiedBy:(Y=B.lastModifiedBy)!==null&&Y!==void 0?Y:"Un-named"})),this.numbering=new d9(B.numbering?B.numbering:{config:[]}),this.comments=new z4((Q=B.comments)!==null&&Q!==void 0?Q:{children:[]}),this.comments.ThreadData)this.commentsExtended=new E4(this.comments.ThreadData);if(this.fileRelationships=new w2,this.customProperties=new rQ((K=B.customProperties)!==null&&K!==void 0?K:[]),this.appProperties=new _Q,this.footnotesWrapper=new PJ,this.endnotesWrapper=new RJ,this.contentTypes=new uQ,this.documentWrapper=new JJ({background:B.background}),this.settings=new dJ({compatibilityModeVersion:B.compatabilityModeVersion,compatibility:B.compatibility,evenAndOddHeaders:B.evenAndOddHeaderAndFooters?!0:!1,trackRevisions:(Z=B.features)===null||Z===void 0?void 0:Z.trackRevisions,updateFields:(J=B.features)===null||J===void 0?void 0:J.updateFields,defaultTabStop:B.defaultTabStop,hyphenation:{autoHyphenation:(M=B.hyphenation)===null||M===void 0?void 0:M.autoHyphenation,hyphenationZone:(W=B.hyphenation)===null||W===void 0?void 0:W.hyphenationZone,consecutiveHyphenLimit:(I=B.hyphenation)===null||I===void 0?void 0:I.consecutiveHyphenLimit,doNotHyphenateCaps:(F=B.hyphenation)===null||F===void 0?void 0:F.doNotHyphenateCaps}}),this.media=new K6,B.externalStyles!==void 0){var w;let P=new M8().newInstance((w=B.styles)===null||w===void 0?void 0:w.default),A=new KK().newInstance(B.externalStyles);this.styles=new $1(L0(L0({},A),{},{importedStyles:[...P.importedStyles,...A.importedStyles]}))}else if(B.styles){let P=new M8().newInstance(B.styles.default);this.styles=new $1(L0(L0({},P),B.styles))}else{let P=new M8;this.styles=new $1(P.newInstance())}this.addDefaultRelationships();for(let P of B.sections)this.addSection(P);if(B.footnotes)for(let P in B.footnotes)this.footnotesWrapper.View.createFootNote(parseFloat(P),B.footnotes[P].children);if(B.endnotes)for(let P in B.endnotes)this.endnotesWrapper.View.createEndnote(parseFloat(P),B.endnotes[P].children);this.fontWrapper=new h4((D=B.fonts)!==null&&D!==void 0?D:[])}addSection({headers:B={},footers:U={},children:G,properties:Y}){this.documentWrapper.View.Body.addSection(L0(L0({},Y),{},{headerWrapperGroup:{default:B.default?this.createHeader(B.default):void 0,first:B.first?this.createHeader(B.first):void 0,even:B.even?this.createHeader(B.even):void 0},footerWrapperGroup:{default:U.default?this.createFooter(U.default):void 0,first:U.first?this.createFooter(U.first):void 0,even:U.even?this.createFooter(U.even):void 0}}));for(let Q of G)this.documentWrapper.View.add(Q)}createHeader(B){let U=new _9(this.media,this.currentRelationshipId++);for(let G of B.options.children)U.add(G);return this.addHeaderToDocument(U),U}createFooter(B){let U=new f9(this.media,this.currentRelationshipId++);for(let G of B.options.children)U.add(G);return this.addFooterToDocument(U),U}addHeaderToDocument(B,U=D2.DEFAULT){this.headers.push({header:B,type:U}),this.documentWrapper.Relationships.addRelationship(B.View.ReferenceId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",`header${this.headers.length}.xml`),this.contentTypes.addHeader(this.headers.length)}addFooterToDocument(B,U=D2.DEFAULT){this.footers.push({footer:B,type:U}),this.documentWrapper.Relationships.addRelationship(B.View.ReferenceId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",`footer${this.footers.length}.xml`),this.contentTypes.addFooter(this.footers.length)}addDefaultRelationships(){if(this.fileRelationships.addRelationship(1,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","word/document.xml"),this.fileRelationships.addRelationship(2,"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties","docProps/core.xml"),this.fileRelationships.addRelationship(3,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties","docProps/app.xml"),this.fileRelationships.addRelationship(4,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties","docProps/custom.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles","styles.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering","numbering.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes","footnotes.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes","endnotes.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings","settings.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments","comments.xml"),this.commentsExtended)this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.microsoft.com/office/2011/relationships/commentsExtended","commentsExtended.xml"),this.contentTypes.addCommentsExtended()}get Document(){return this.documentWrapper}get Styles(){return this.styles}get CoreProperties(){return this.coreProperties}get Numbering(){return this.numbering}get Media(){return this.media}get FileRelationships(){return this.fileRelationships}get Headers(){return this.headers.map((B)=>B.header)}get Footers(){return this.footers.map((B)=>B.footer)}get ContentTypes(){return this.contentTypes}get CustomProperties(){return this.customProperties}get AppProperties(){return this.appProperties}get FootNotes(){return this.footnotesWrapper}get Endnotes(){return this.endnotesWrapper}get Settings(){return this.settings}get Comments(){return this.comments}get CommentsExtended(){return this.commentsExtended}get FontTable(){return this.fontWrapper}},qK=class extends t{constructor(B={}){super("w:instrText");e(this,"properties",void 0),this.properties=B,this.root.push(new _0({space:x0.PRESERVE}));let U="TOC";if(this.properties.captionLabel)U=`${U} \\a "${this.properties.captionLabel}"`;if(this.properties.entriesFromBookmark)U=`${U} \\b "${this.properties.entriesFromBookmark}"`;if(this.properties.captionLabelIncludingNumbers)U=`${U} \\c "${this.properties.captionLabelIncludingNumbers}"`;if(this.properties.sequenceAndPageNumbersSeparator)U=`${U} \\d "${this.properties.sequenceAndPageNumbersSeparator}"`;if(this.properties.tcFieldIdentifier)U=`${U} \\f "${this.properties.tcFieldIdentifier}"`;if(this.properties.hyperlink)U=`${U} \\h`;if(this.properties.tcFieldLevelRange)U=`${U} \\l "${this.properties.tcFieldLevelRange}"`;if(this.properties.pageNumbersEntryLevelsRange)U=`${U} \\n "${this.properties.pageNumbersEntryLevelsRange}"`;if(this.properties.headingStyleRange)U=`${U} \\o "${this.properties.headingStyleRange}"`;if(this.properties.entryAndPageNumberSeparator)U=`${U} \\p "${this.properties.entryAndPageNumberSeparator}"`;if(this.properties.seqFieldIdentifierForPrefix)U=`${U} \\s "${this.properties.seqFieldIdentifierForPrefix}"`;if(this.properties.stylesWithLevels&&this.properties.stylesWithLevels.length){let G=this.properties.stylesWithLevels.map((Y)=>`${Y.styleName},${Y.level}`).join(",");U=`${U} \\t "${G}"`}if(this.properties.useAppliedParagraphOutlineLevel)U=`${U} \\u`;if(this.properties.preserveTabInEntries)U=`${U} \\w`;if(this.properties.preserveNewLineInEntries)U=`${U} \\x`;if(this.properties.hideTabAndPageNumbersInWebView)U=`${U} \\z`;this.root.push(U)}},r9=class extends t{constructor(){super("w:sdtContent")}},i9=class extends t{constructor(B){super("w:sdtPr");if(B)this.root.push(new M2("w:alias",B))}};function MK(B,U){if(B==null)return{};var G={};for(var Y in B)if({}.hasOwnProperty.call(B,Y)){if(U.includes(Y))continue;G[Y]=B[Y]}return G}function n9(B,U){if(B==null)return{};var G,Y,Q=MK(B,U);if(Object.getOwnPropertySymbols){var K=Object.getOwnPropertySymbols(B);for(Y=0;Y0){let{stylesWithLevels:W}=K,I=Y.map((D,w)=>{var P,A;let E=this.buildCachedContentParagraphChild(D,K),C=(P=W===null||W===void 0||(A=W.find((v)=>v.level===D.level))===null||A===void 0?void 0:A.styleName)!==null&&P!==void 0?P:`TOC${D.level}`,j=w===0?[...J,E]:w===Y.length-1?[E,...M]:[E];return new d0({style:C,tabStops:this.getTabStopsForLevel(D.level),children:j})}),F=I;if(Y.length<=1)F=[...I,new d0({children:M})];for(let D of F)Z.addChildElement(D)}else{let W=new d0({children:J});Z.addChildElement(W);for(let F of G)Z.addChildElement(F);let I=new d0({children:M});Z.addChildElement(I)}this.root.push(Z)}getTabStopsForLevel(B,U=9025){return[{type:"clear",position:U+1-(B-1)*240},{type:"right",position:U,leader:"dot"}]}buildCachedContentRun(B,U){var G,Y;return new T0({style:(U===null||U===void 0?void 0:U.hyperlink)&&B.href!==void 0?"IndexLink":void 0,children:[new Z1({text:B.title}),new D4,new Z1({text:(G=(Y=B.page)===null||Y===void 0?void 0:Y.toString())!==null&&G!==void 0?G:""})]})}buildCachedContentParagraphChild(B,U){let G=this.buildCachedContentRun(B,U);if((U===null||U===void 0?void 0:U.hyperlink)&&B.href!==void 0)return new y4({anchor:B.href,children:[G]});return G}},LK=class{constructor(B,U){e(this,"styleName",void 0),e(this,"level",void 0),this.styleName=B,this.level=U}},IK=class{constructor(B={children:[]}){e(this,"options",void 0),this.options=B}},OK=class{constructor(B={children:[]}){e(this,"options",void 0),this.options=B}},s9=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id"})}},o9=class extends t{constructor(B){super("w:footnoteReference");this.root.push(new s9({id:B}))}},FK=class extends T0{constructor(B){super({style:"FootnoteReference"});this.root.push(new o9(B))}},t9=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{id:"w:id"})}},e9=class extends t{constructor(B){super("w:endnoteReference");this.root.push(new t9({id:B}))}},HK=class extends T0{constructor(B){super({style:"EndnoteReference"});this.root.push(new e9(B))}},o6=class extends F0{constructor(...B){super(...B);e(this,"xmlKeys",{val:"w14:val",symbolfont:"w14:font"})}},S1=class extends t{constructor(B,U,G){super(B);if(G)this.root.push(new o6({val:SB(U),symbolfont:G}));else this.root.push(new o6({val:U}))}},B5=class extends t{constructor(B){var U,G,Y,Q,K,Z,J,M;super("w14:checkbox");e(this,"DEFAULT_UNCHECKED_SYMBOL","2610"),e(this,"DEFAULT_CHECKED_SYMBOL","2612"),e(this,"DEFAULT_FONT","MS Gothic");let W=(B===null||B===void 0?void 0:B.checked)?"1":"0",I,F;this.root.push(new S1("w14:checked",W)),I=(B===null||B===void 0||(U=B.checkedState)===null||U===void 0?void 0:U.value)?B===null||B===void 0||(G=B.checkedState)===null||G===void 0?void 0:G.value:this.DEFAULT_CHECKED_SYMBOL,F=(B===null||B===void 0||(Y=B.checkedState)===null||Y===void 0?void 0:Y.font)?B===null||B===void 0||(Q=B.checkedState)===null||Q===void 0?void 0:Q.font:this.DEFAULT_FONT,this.root.push(new S1("w14:checkedState",I,F)),I=(B===null||B===void 0||(K=B.uncheckedState)===null||K===void 0?void 0:K.value)?B===null||B===void 0||(Z=B.uncheckedState)===null||Z===void 0?void 0:Z.value:this.DEFAULT_UNCHECKED_SYMBOL,F=(B===null||B===void 0||(J=B.uncheckedState)===null||J===void 0?void 0:J.font)?B===null||B===void 0||(M=B.uncheckedState)===null||M===void 0?void 0:M.font:this.DEFAULT_FONT,this.root.push(new S1("w14:uncheckedState",I,F))}},WK=class extends t{constructor(B){var U,G,Y,Q;super("w:sdt");e(this,"DEFAULT_UNCHECKED_SYMBOL","2610"),e(this,"DEFAULT_CHECKED_SYMBOL","2612"),e(this,"DEFAULT_FONT","MS Gothic");let K=new i9(B===null||B===void 0?void 0:B.alias);K.addChildElement(new B5(B)),this.root.push(K);let Z=new r9,J=B===null||B===void 0||(U=B.checkedState)===null||U===void 0?void 0:U.font,M=B===null||B===void 0||(G=B.checkedState)===null||G===void 0?void 0:G.value,W=B===null||B===void 0||(Y=B.uncheckedState)===null||Y===void 0?void 0:Y.font,I=B===null||B===void 0||(Q=B.uncheckedState)===null||Q===void 0?void 0:Q.value,F,D;if(B===null||B===void 0?void 0:B.checked)F=J?J:this.DEFAULT_FONT,D=M?M:this.DEFAULT_CHECKED_SYMBOL;else F=W?W:this.DEFAULT_FONT,D=I?I:this.DEFAULT_UNCHECKED_SYMBOL;let w=new aB({char:D,symbolfont:F});Z.addChildElement(w),this.root.push(Z)}},PK=({shape:B})=>new X0({name:"w:pict",children:[B]}),wK=({children:B=[]})=>new X0({name:"w:txbxContent",children:B}),AK=({style:B,children:U,inset:G})=>new X0({name:"v:textbox",attributes:{style:{key:"style",value:B},insetMode:{key:"insetmode",value:G?"custom":"auto"},inset:{key:"inset",value:G?`${G.left}, ${G.top}, ${G.right}, ${G.bottom}`:void 0}},children:[wK({children:U})]}),jK="#_x0000_t202",NK={flip:"flip",height:"height",left:"left",marginBottom:"margin-bottom",marginLeft:"margin-left",marginRight:"margin-right",marginTop:"margin-top",positionHorizontal:"mso-position-horizontal",positionHorizontalRelative:"mso-position-horizontal-relative",positionVertical:"mso-position-vertical",positionVerticalRelative:"mso-position-vertical-relative",wrapDistanceBottom:"mso-wrap-distance-bottom",wrapDistanceLeft:"mso-wrap-distance-left",wrapDistanceRight:"mso-wrap-distance-right",wrapDistanceTop:"mso-wrap-distance-top",wrapEdited:"mso-wrap-edited",wrapStyle:"mso-wrap-style",position:"position",rotation:"rotation",top:"top",visibility:"visibility",width:"width",zIndex:"z-index"},zK=(B)=>B?Object.entries(B).map(([U,G])=>`${NK[U]}:${G}`).join(";"):void 0,EK=({id:B,children:U,type:G=jK,style:Y})=>new X0({name:"v:shape",attributes:{id:{key:"id",value:B},type:{key:"type",value:G},style:{key:"style",value:zK(Y)}},children:[AK({style:"mso-fit-shape-to-text:t;",children:U})]}),TK=["style","children"],DK=class extends F1{constructor(B){let{style:U,children:G}=B,Y=n9(B,TK);super("w:p");this.root.push(new X2(Y)),this.root.push(PK({shape:EK({children:G,id:O1(),style:U})}))}},CK=R0((B,U)=>{d2(),P2();/*! - - JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - - (c) 2009-2016 Stuart Knightley - Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - - JSZip uses the library pako released under the MIT license : - https://github.com/nodeca/pako/blob/main/LICENSE - */(function(G){if(typeof B=="object"&&typeof U<"u")U.exports=G();else if(typeof define=="function"&&define.amd)define([],G);else(typeof window<"u"?window:typeof v0<"u"?v0:typeof self<"u"?self:this).JSZip=G()})(function(){return function G(Y,Q,K){function Z(W,I){if(!Q[W]){if(!Y[W]){var F=typeof N1=="function"&&N1;if(!I&&F)return F(W,!0);if(J)return J(W,!0);var D=Error("Cannot find module '"+W+"'");throw D.code="MODULE_NOT_FOUND",D}var w=Q[W]={exports:{}};Y[W][0].call(w.exports,function(P){var A=Y[W][1][P];return Z(A||P)},w,w.exports,G,Y,Q,K)}return Q[W].exports}for(var J=typeof N1=="function"&&N1,M=0;M>2,w=(3&W)<<4|I>>4,P=1>6:64,A=2>4,I=(15&D)<<4|(w=J.indexOf(M.charAt(A++)))>>2,F=(3&w)<<6|(P=J.indexOf(M.charAt(A++))),j[E++]=W,w!==64&&(j[E++]=I),P!==64&&(j[E++]=F);return j}},{"./support":30,"./utils":32}],2:[function(G,Y,Q){var K=G("./external"),Z=G("./stream/DataWorker"),J=G("./stream/Crc32Probe"),M=G("./stream/DataLengthProbe");function W(I,F,D,w,P){this.compressedSize=I,this.uncompressedSize=F,this.crc32=D,this.compression=w,this.compressedContent=P}W.prototype={getContentWorker:function(){var I=new Z(K.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new M("data_length")),F=this;return I.on("end",function(){if(this.streamInfo.data_length!==F.uncompressedSize)throw Error("Bug : uncompressed data size mismatch")}),I},getCompressedWorker:function(){return new Z(K.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},W.createWorkerFrom=function(I,F,D){return I.pipe(new J).pipe(new M("uncompressedSize")).pipe(F.compressWorker(D)).pipe(new M("compressedSize")).withStreamInfo("compression",F)},Y.exports=W},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(G,Y,Q){var K=G("./stream/GenericWorker");Q.STORE={magic:"\x00\x00",compressWorker:function(){return new K("STORE compression")},uncompressWorker:function(){return new K("STORE decompression")}},Q.DEFLATE=G("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(G,Y,Q){var K=G("./utils"),Z=function(){for(var J,M=[],W=0;W<256;W++){J=W;for(var I=0;I<8;I++)J=1&J?3988292384^J>>>1:J>>>1;M[W]=J}return M}();Y.exports=function(J,M){return J!==void 0&&J.length?K.getTypeOf(J)!=="string"?function(W,I,F,D){var w=Z,P=D+F;W^=-1;for(var A=D;A>>8^w[255&(W^I[A])];return-1^W}(0|M,J,J.length,0):function(W,I,F,D){var w=Z,P=D+F;W^=-1;for(var A=D;A>>8^w[255&(W^I.charCodeAt(A))];return-1^W}(0|M,J,J.length,0):0}},{"./utils":32}],5:[function(G,Y,Q){Q.base64=!1,Q.binary=!1,Q.dir=!1,Q.createFolders=!0,Q.date=null,Q.compression=null,Q.compressionOptions=null,Q.comment=null,Q.unixPermissions=null,Q.dosPermissions=null},{}],6:[function(G,Y,Q){var K=null;K=typeof Promise<"u"?Promise:G("lie"),Y.exports={Promise:K}},{lie:37}],7:[function(G,Y,Q){var K=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",Z=G("pako"),J=G("./utils"),M=G("./stream/GenericWorker"),W=K?"uint8array":"array";function I(F,D){M.call(this,"FlateWorker/"+F),this._pako=null,this._pakoAction=F,this._pakoOptions=D,this.meta={}}Q.magic="\b\x00",J.inherits(I,M),I.prototype.processChunk=function(F){this.meta=F.meta,this._pako===null&&this._createPako(),this._pako.push(J.transformTo(W,F.data),!1)},I.prototype.flush=function(){M.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},I.prototype.cleanUp=function(){M.prototype.cleanUp.call(this),this._pako=null},I.prototype._createPako=function(){this._pako=new Z[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var F=this;this._pako.onData=function(D){F.push({data:D,meta:F.meta})}},Q.compressWorker=function(F){return new I("Deflate",F)},Q.uncompressWorker=function(){return new I("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(G,Y,Q){function K(w,P){var A,E="";for(A=0;A>>=8;return E}function Z(w,P,A,E,C,j){var v,S,H=w.file,X=w.compression,$=j!==W.utf8encode,x=J.transformTo("string",j(H.name)),N=J.transformTo("string",W.utf8encode(H.name)),a=H.comment,U0=J.transformTo("string",j(a)),b=J.transformTo("string",W.utf8encode(a)),c=N.length!==H.name.length,T=b.length!==a.length,m="",B0="",i="",V0=H.dir,s=H.date,G0={crc32:0,compressedSize:0,uncompressedSize:0};P&&!A||(G0.crc32=w.crc32,G0.compressedSize=w.compressedSize,G0.uncompressedSize=w.uncompressedSize);var r=0;P&&(r|=8),$||!c&&!T||(r|=2048);var y=0,n=0;V0&&(y|=16),C==="UNIX"?(n=798,y|=function(Y0,O0){var z=Y0;return Y0||(z=O0?16893:33204),(65535&z)<<16}(H.unixPermissions,V0)):(n=20,y|=function(Y0){return 63&(Y0||0)}(H.dosPermissions)),v=s.getUTCHours(),v<<=6,v|=s.getUTCMinutes(),v<<=5,v|=s.getUTCSeconds()/2,S=s.getUTCFullYear()-1980,S<<=4,S|=s.getUTCMonth()+1,S<<=5,S|=s.getUTCDate(),c&&(B0=K(1,1)+K(I(x),4)+N,m+="up"+K(B0.length,2)+B0),T&&(i=K(1,1)+K(I(U0),4)+b,m+="uc"+K(i.length,2)+i);var o="";return o+=` -\x00`,o+=K(r,2),o+=X.magic,o+=K(v,2),o+=K(S,2),o+=K(G0.crc32,4),o+=K(G0.compressedSize,4),o+=K(G0.uncompressedSize,4),o+=K(x.length,2),o+=K(m.length,2),{fileRecord:F.LOCAL_FILE_HEADER+o+x+m,dirRecord:F.CENTRAL_FILE_HEADER+K(n,2)+o+K(U0.length,2)+"\x00\x00\x00\x00"+K(y,4)+K(E,4)+x+m+U0}}var J=G("../utils"),M=G("../stream/GenericWorker"),W=G("../utf8"),I=G("../crc32"),F=G("../signature");function D(w,P,A,E){M.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=P,this.zipPlatform=A,this.encodeFileName=E,this.streamFiles=w,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}J.inherits(D,M),D.prototype.push=function(w){var P=w.meta.percent||0,A=this.entriesCount,E=this._sources.length;this.accumulate?this.contentBuffer.push(w):(this.bytesWritten+=w.data.length,M.prototype.push.call(this,{data:w.data,meta:{currentFile:this.currentFile,percent:A?(P+100*(A-E-1))/A:100}}))},D.prototype.openedSource=function(w){this.currentSourceOffset=this.bytesWritten,this.currentFile=w.file.name;var P=this.streamFiles&&!w.file.dir;if(P){var A=Z(w,P,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:A.fileRecord,meta:{percent:0}})}else this.accumulate=!0},D.prototype.closedSource=function(w){this.accumulate=!1;var P=this.streamFiles&&!w.file.dir,A=Z(w,P,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(A.dirRecord),P)this.push({data:function(E){return F.DATA_DESCRIPTOR+K(E.crc32,4)+K(E.compressedSize,4)+K(E.uncompressedSize,4)}(w),meta:{percent:100}});else for(this.push({data:A.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},D.prototype.flush=function(){for(var w=this.bytesWritten,P=0;P=this.index;M--)W=(W<<8)+this.byteAt(M);return this.index+=J,W},readString:function(J){return K.transformTo("string",this.readData(J))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var J=this.readInt(4);return new Date(Date.UTC(1980+(J>>25&127),(J>>21&15)-1,J>>16&31,J>>11&31,J>>5&63,(31&J)<<1))}},Y.exports=Z},{"../utils":32}],19:[function(G,Y,Q){var K=G("./Uint8ArrayReader");function Z(J){K.call(this,J)}G("../utils").inherits(Z,K),Z.prototype.readData=function(J){this.checkOffset(J);var M=this.data.slice(this.zero+this.index,this.zero+this.index+J);return this.index+=J,M},Y.exports=Z},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(G,Y,Q){var K=G("./DataReader");function Z(J){K.call(this,J)}G("../utils").inherits(Z,K),Z.prototype.byteAt=function(J){return this.data.charCodeAt(this.zero+J)},Z.prototype.lastIndexOfSignature=function(J){return this.data.lastIndexOf(J)-this.zero},Z.prototype.readAndCheckSignature=function(J){return J===this.readData(4)},Z.prototype.readData=function(J){this.checkOffset(J);var M=this.data.slice(this.zero+this.index,this.zero+this.index+J);return this.index+=J,M},Y.exports=Z},{"../utils":32,"./DataReader":18}],21:[function(G,Y,Q){var K=G("./ArrayReader");function Z(J){K.call(this,J)}G("../utils").inherits(Z,K),Z.prototype.readData=function(J){if(this.checkOffset(J),J===0)return new Uint8Array(0);var M=this.data.subarray(this.zero+this.index,this.zero+this.index+J);return this.index+=J,M},Y.exports=Z},{"../utils":32,"./ArrayReader":17}],22:[function(G,Y,Q){var K=G("../utils"),Z=G("../support"),J=G("./ArrayReader"),M=G("./StringReader"),W=G("./NodeBufferReader"),I=G("./Uint8ArrayReader");Y.exports=function(F){var D=K.getTypeOf(F);return K.checkSupport(D),D!=="string"||Z.uint8array?D==="nodebuffer"?new W(F):Z.uint8array?new I(K.transformTo("uint8array",F)):new J(K.transformTo("array",F)):new M(F)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(G,Y,Q){Q.LOCAL_FILE_HEADER="PK\x03\x04",Q.CENTRAL_FILE_HEADER="PK\x01\x02",Q.CENTRAL_DIRECTORY_END="PK\x05\x06",Q.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x06\x07",Q.ZIP64_CENTRAL_DIRECTORY_END="PK\x06\x06",Q.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(G,Y,Q){var K=G("./GenericWorker"),Z=G("../utils");function J(M){K.call(this,"ConvertWorker to "+M),this.destType=M}Z.inherits(J,K),J.prototype.processChunk=function(M){this.push({data:Z.transformTo(this.destType,M.data),meta:M.meta})},Y.exports=J},{"../utils":32,"./GenericWorker":28}],25:[function(G,Y,Q){var K=G("./GenericWorker"),Z=G("../crc32");function J(){K.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}G("../utils").inherits(J,K),J.prototype.processChunk=function(M){this.streamInfo.crc32=Z(M.data,this.streamInfo.crc32||0),this.push(M)},Y.exports=J},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(G,Y,Q){var K=G("../utils"),Z=G("./GenericWorker");function J(M){Z.call(this,"DataLengthProbe for "+M),this.propName=M,this.withStreamInfo(M,0)}K.inherits(J,Z),J.prototype.processChunk=function(M){if(M){var W=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=W+M.data.length}Z.prototype.processChunk.call(this,M)},Y.exports=J},{"../utils":32,"./GenericWorker":28}],27:[function(G,Y,Q){var K=G("../utils"),Z=G("./GenericWorker");function J(M){Z.call(this,"DataWorker");var W=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,M.then(function(I){W.dataIsReady=!0,W.data=I,W.max=I&&I.length||0,W.type=K.getTypeOf(I),W.isPaused||W._tickAndRepeat()},function(I){W.error(I)})}K.inherits(J,Z),J.prototype.cleanUp=function(){Z.prototype.cleanUp.call(this),this.data=null},J.prototype.resume=function(){return!!Z.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,K.delay(this._tickAndRepeat,[],this)),!0)},J.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(K.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},J.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var M=null,W=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":M=this.data.substring(this.index,W);break;case"uint8array":M=this.data.subarray(this.index,W);break;case"array":case"nodebuffer":M=this.data.slice(this.index,W)}return this.index=W,this.push({data:M,meta:{percent:this.max?this.index/this.max*100:0}})},Y.exports=J},{"../utils":32,"./GenericWorker":28}],28:[function(G,Y,Q){function K(Z){this.name=Z||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}K.prototype={push:function(Z){this.emit("data",Z)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(Z){this.emit("error",Z)}return!0},error:function(Z){return!this.isFinished&&(this.isPaused?this.generatedError=Z:(this.isFinished=!0,this.emit("error",Z),this.previous&&this.previous.error(Z),this.cleanUp()),!0)},on:function(Z,J){return this._listeners[Z].push(J),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(Z,J){if(this._listeners[Z])for(var M=0;M "+Z:Z}},Y.exports=K},{}],29:[function(G,Y,Q){var K=G("../utils"),Z=G("./ConvertWorker"),J=G("./GenericWorker"),M=G("../base64"),W=G("../support"),I=G("../external"),F=null;if(W.nodestream)try{F=G("../nodejs/NodejsStreamOutputAdapter")}catch(P){}function D(P,A){return new I.Promise(function(E,C){var j=[],v=P._internalType,S=P._outputType,H=P._mimeType;P.on("data",function(X,$){j.push(X),A&&A($)}).on("error",function(X){j=[],C(X)}).on("end",function(){try{E(function(X,$,x){switch(X){case"blob":return K.newBlob(K.transformTo("arraybuffer",$),x);case"base64":return M.encode($);default:return K.transformTo(X,$)}}(S,function(X,$){var x,N=0,a=null,U0=0;for(x=0;x<$.length;x++)U0+=$[x].length;switch(X){case"string":return $.join("");case"array":return Array.prototype.concat.apply([],$);case"uint8array":for(a=new Uint8Array(U0),x=0;x<$.length;x++)a.set($[x],N),N+=$[x].length;return a;case"nodebuffer":return Buffer.concat($);default:throw Error("concat : unsupported type '"+X+"'")}}(v,j),H))}catch(X){C(X)}j=[]}).resume()})}function w(P,A,E){var C=A;switch(A){case"blob":case"arraybuffer":C="uint8array";break;case"base64":C="string"}try{this._internalType=C,this._outputType=A,this._mimeType=E,K.checkSupport(C),this._worker=P.pipe(new Z(C)),P.lock()}catch(j){this._worker=new J("error"),this._worker.error(j)}}w.prototype={accumulate:function(P){return D(this,P)},on:function(P,A){var E=this;return P==="data"?this._worker.on(P,function(C){A.call(E,C.data,C.meta)}):this._worker.on(P,function(){K.delay(A,arguments,E)}),this},resume:function(){return K.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(P){if(K.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw Error(this._outputType+" is not supported by this method");return new F(this,{objectMode:this._outputType!=="nodebuffer"},P)}},Y.exports=w},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(G,Y,Q){if(Q.base64=!0,Q.array=!0,Q.string=!0,Q.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",Q.nodebuffer=typeof Buffer<"u",Q.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")Q.blob=!1;else{var K=new ArrayBuffer(0);try{Q.blob=new Blob([K],{type:"application/zip"}).size===0}catch(J){try{var Z=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);Z.append(K),Q.blob=Z.getBlob("application/zip").size===0}catch(M){Q.blob=!1}}}try{Q.nodestream=!!G("readable-stream").Readable}catch(J){Q.nodestream=!1}},{"readable-stream":16}],31:[function(G,Y,Q){for(var K=G("./utils"),Z=G("./support"),J=G("./nodejsUtils"),M=G("./stream/GenericWorker"),W=Array(256),I=0;I<256;I++)W[I]=252<=I?6:248<=I?5:240<=I?4:224<=I?3:192<=I?2:1;W[254]=W[254]=1;function F(){M.call(this,"utf-8 decode"),this.leftOver=null}function D(){M.call(this,"utf-8 encode")}Q.utf8encode=function(w){return Z.nodebuffer?J.newBufferFrom(w,"utf-8"):function(P){var A,E,C,j,v,S=P.length,H=0;for(j=0;j>>6:(E<65536?A[v++]=224|E>>>12:(A[v++]=240|E>>>18,A[v++]=128|E>>>12&63),A[v++]=128|E>>>6&63),A[v++]=128|63&E);return A}(w)},Q.utf8decode=function(w){return Z.nodebuffer?K.transformTo("nodebuffer",w).toString("utf-8"):function(P){var A,E,C,j,v=P.length,S=Array(2*v);for(A=E=0;A>10&1023,S[E++]=56320|1023&C)}return S.length!==E&&(S.subarray?S=S.subarray(0,E):S.length=E),K.applyFromCharCode(S)}(w=K.transformTo(Z.uint8array?"uint8array":"array",w))},K.inherits(F,M),F.prototype.processChunk=function(w){var P=K.transformTo(Z.uint8array?"uint8array":"array",w.data);if(this.leftOver&&this.leftOver.length){if(Z.uint8array){var A=P;(P=new Uint8Array(A.length+this.leftOver.length)).set(this.leftOver,0),P.set(A,this.leftOver.length)}else P=this.leftOver.concat(P);this.leftOver=null}var E=function(j,v){var S;for((v=v||j.length)>j.length&&(v=j.length),S=v-1;0<=S&&(192&j[S])==128;)S--;return S<0?v:S===0?v:S+W[j[S]]>v?S:v}(P),C=P;E!==P.length&&(Z.uint8array?(C=P.subarray(0,E),this.leftOver=P.subarray(E,P.length)):(C=P.slice(0,E),this.leftOver=P.slice(E,P.length))),this.push({data:Q.utf8decode(C),meta:w.meta})},F.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:Q.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},Q.Utf8DecodeWorker=F,K.inherits(D,M),D.prototype.processChunk=function(w){this.push({data:Q.utf8encode(w.data),meta:w.meta})},Q.Utf8EncodeWorker=D},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(G,Y,Q){var K=G("./support"),Z=G("./base64"),J=G("./nodejsUtils"),M=G("./external");function W(A){return A}function I(A,E){for(var C=0;C>8;this.dir=!!(16&this.externalFileAttributes),w==0&&(this.dosPermissions=63&this.externalFileAttributes),w==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var w=K(this.extraFields[1].value);this.uncompressedSize===Z.MAX_VALUE_32BITS&&(this.uncompressedSize=w.readInt(8)),this.compressedSize===Z.MAX_VALUE_32BITS&&(this.compressedSize=w.readInt(8)),this.localHeaderOffset===Z.MAX_VALUE_32BITS&&(this.localHeaderOffset=w.readInt(8)),this.diskNumberStart===Z.MAX_VALUE_32BITS&&(this.diskNumberStart=w.readInt(4))}},readExtraFields:function(w){var P,A,E,C=w.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});w.index+4>>6:(w<65536?D[E++]=224|w>>>12:(D[E++]=240|w>>>18,D[E++]=128|w>>>12&63),D[E++]=128|w>>>6&63),D[E++]=128|63&w);return D},Q.buf2binstring=function(F){return I(F,F.length)},Q.binstring2buf=function(F){for(var D=new K.Buf8(F.length),w=0,P=D.length;w>10&1023,j[P++]=56320|1023&A)}return I(j,P)},Q.utf8border=function(F,D){var w;for((D=D||F.length)>F.length&&(D=F.length),w=D-1;0<=w&&(192&F[w])==128;)w--;return w<0?D:w===0?D:w+M[F[w]]>D?w:D}},{"./common":41}],43:[function(G,Y,Q){Y.exports=function(K,Z,J,M){for(var W=65535&K|0,I=K>>>16&65535|0,F=0;J!==0;){for(J-=F=2000>>1:Z>>>1;J[M]=Z}return J}();Y.exports=function(Z,J,M,W){var I=K,F=W+M;Z^=-1;for(var D=W;D>>8^I[255&(Z^J[D])];return-1^Z}},{}],46:[function(G,Y,Q){var K,Z=G("../utils/common"),J=G("./trees"),M=G("./adler32"),W=G("./crc32"),I=G("./messages"),F=0,D=4,w=0,P=-2,A=-1,E=4,C=2,j=8,v=9,S=286,H=30,X=19,$=2*S+1,x=15,N=3,a=258,U0=a+N+1,b=42,c=113,T=1,m=2,B0=3,i=4;function V0(R,p){return R.msg=I[p],p}function s(R){return(R<<1)-(4R.avail_out&&(k=R.avail_out),k!==0&&(Z.arraySet(R.output,p.pending_buf,p.pending_out,k,R.next_out),R.next_out+=k,p.pending_out+=k,R.total_out+=k,R.avail_out-=k,p.pending-=k,p.pending===0&&(p.pending_out=0))}function y(R,p){J._tr_flush_block(R,0<=R.block_start?R.block_start:-1,R.strstart-R.block_start,p),R.block_start=R.strstart,r(R.strm)}function n(R,p){R.pending_buf[R.pending++]=p}function o(R,p){R.pending_buf[R.pending++]=p>>>8&255,R.pending_buf[R.pending++]=255&p}function Y0(R,p){var k,V,q=R.max_chain_length,O=R.strstart,_=R.prev_length,l=R.nice_match,d=R.strstart>R.w_size-U0?R.strstart-(R.w_size-U0):0,Q0=R.window,q0=R.w_mask,K0=R.prev,I0=R.strstart+a,H0=Q0[O+_-1],W0=Q0[O+_];R.prev_length>=R.good_match&&(q>>=2),l>R.lookahead&&(l=R.lookahead);do if(Q0[(k=p)+_]===W0&&Q0[k+_-1]===H0&&Q0[k]===Q0[O]&&Q0[++k]===Q0[O+1]){O+=2,k++;do;while(Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Q0[++O]===Q0[++k]&&Od&&--q!=0);return _<=R.lookahead?_:R.lookahead}function O0(R){var p,k,V,q,O,_,l,d,Q0,q0,K0=R.w_size;do{if(q=R.window_size-R.lookahead-R.strstart,R.strstart>=K0+(K0-U0)){for(Z.arraySet(R.window,R.window,K0,K0,0),R.match_start-=K0,R.strstart-=K0,R.block_start-=K0,p=k=R.hash_size;V=R.head[--p],R.head[p]=K0<=V?V-K0:0,--k;);for(p=k=K0;V=R.prev[--p],R.prev[p]=K0<=V?V-K0:0,--k;);q+=K0}if(R.strm.avail_in===0)break;if(_=R.strm,l=R.window,d=R.strstart+R.lookahead,Q0=q,q0=void 0,q0=_.avail_in,Q0=N)for(O=R.strstart-R.insert,R.ins_h=R.window[O],R.ins_h=(R.ins_h<=N&&(R.ins_h=(R.ins_h<=N)if(V=J._tr_tally(R,R.strstart-R.match_start,R.match_length-N),R.lookahead-=R.match_length,R.match_length<=R.max_lazy_match&&R.lookahead>=N){for(R.match_length--;R.strstart++,R.ins_h=(R.ins_h<=N&&(R.ins_h=(R.ins_h<=N&&R.match_length<=R.prev_length){for(q=R.strstart+R.lookahead-N,V=J._tr_tally(R,R.strstart-1-R.prev_match,R.prev_length-N),R.lookahead-=R.prev_length-1,R.prev_length-=2;++R.strstart<=q&&(R.ins_h=(R.ins_h<R.pending_buf_size-5&&(k=R.pending_buf_size-5);;){if(R.lookahead<=1){if(O0(R),R.lookahead===0&&p===F)return T;if(R.lookahead===0)break}R.strstart+=R.lookahead,R.lookahead=0;var V=R.block_start+k;if((R.strstart===0||R.strstart>=V)&&(R.lookahead=R.strstart-V,R.strstart=V,y(R,!1),R.strm.avail_out===0))return T;if(R.strstart-R.block_start>=R.w_size-U0&&(y(R,!1),R.strm.avail_out===0))return T}return R.insert=0,p===D?(y(R,!0),R.strm.avail_out===0?B0:i):(R.strstart>R.block_start&&(y(R,!1),R.strm.avail_out),T)}),new u(4,4,8,4,z),new u(4,5,16,8,z),new u(4,6,32,32,z),new u(4,4,16,16,L),new u(8,16,32,32,L),new u(8,16,128,128,L),new u(8,32,128,256,L),new u(32,128,258,1024,L),new u(32,258,258,4096,L)],Q.deflateInit=function(R,p){return f(R,p,j,15,8,0)},Q.deflateInit2=f,Q.deflateReset=g,Q.deflateResetKeep=Z0,Q.deflateSetHeader=function(R,p){return R&&R.state?R.state.wrap!==2?P:(R.state.gzhead=p,w):P},Q.deflate=function(R,p){var k,V,q,O;if(!R||!R.state||5>8&255),n(V,V.gzhead.time>>16&255),n(V,V.gzhead.time>>24&255),n(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),n(V,255&V.gzhead.os),V.gzhead.extra&&V.gzhead.extra.length&&(n(V,255&V.gzhead.extra.length),n(V,V.gzhead.extra.length>>8&255)),V.gzhead.hcrc&&(R.adler=W(R.adler,V.pending_buf,V.pending,0)),V.gzindex=0,V.status=69):(n(V,0),n(V,0),n(V,0),n(V,0),n(V,0),n(V,V.level===9?2:2<=V.strategy||V.level<2?4:0),n(V,3),V.status=c);else{var _=j+(V.w_bits-8<<4)<<8;_|=(2<=V.strategy||V.level<2?0:V.level<6?1:V.level===6?2:3)<<6,V.strstart!==0&&(_|=32),_+=31-_%31,V.status=c,o(V,_),V.strstart!==0&&(o(V,R.adler>>>16),o(V,65535&R.adler)),R.adler=1}if(V.status===69)if(V.gzhead.extra){for(q=V.pending;V.gzindex<(65535&V.gzhead.extra.length)&&(V.pending!==V.pending_buf_size||(V.gzhead.hcrc&&V.pending>q&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),r(R),q=V.pending,V.pending!==V.pending_buf_size));)n(V,255&V.gzhead.extra[V.gzindex]),V.gzindex++;V.gzhead.hcrc&&V.pending>q&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),V.gzindex===V.gzhead.extra.length&&(V.gzindex=0,V.status=73)}else V.status=73;if(V.status===73)if(V.gzhead.name){q=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>q&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),r(R),q=V.pending,V.pending===V.pending_buf_size)){O=1;break}O=V.gzindexq&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),O===0&&(V.gzindex=0,V.status=91)}else V.status=91;if(V.status===91)if(V.gzhead.comment){q=V.pending;do{if(V.pending===V.pending_buf_size&&(V.gzhead.hcrc&&V.pending>q&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),r(R),q=V.pending,V.pending===V.pending_buf_size)){O=1;break}O=V.gzindexq&&(R.adler=W(R.adler,V.pending_buf,V.pending-q,q)),O===0&&(V.status=103)}else V.status=103;if(V.status===103&&(V.gzhead.hcrc?(V.pending+2>V.pending_buf_size&&r(R),V.pending+2<=V.pending_buf_size&&(n(V,255&R.adler),n(V,R.adler>>8&255),R.adler=0,V.status=c)):V.status=c),V.pending!==0){if(r(R),R.avail_out===0)return V.last_flush=-1,w}else if(R.avail_in===0&&s(p)<=s(k)&&p!==D)return V0(R,-5);if(V.status===666&&R.avail_in!==0)return V0(R,-5);if(R.avail_in!==0||V.lookahead!==0||p!==F&&V.status!==666){var l=V.strategy===2?function(d,Q0){for(var q0;;){if(d.lookahead===0&&(O0(d),d.lookahead===0)){if(Q0===F)return T;break}if(d.match_length=0,q0=J._tr_tally(d,0,d.window[d.strstart]),d.lookahead--,d.strstart++,q0&&(y(d,!1),d.strm.avail_out===0))return T}return d.insert=0,Q0===D?(y(d,!0),d.strm.avail_out===0?B0:i):d.last_lit&&(y(d,!1),d.strm.avail_out===0)?T:m}(V,p):V.strategy===3?function(d,Q0){for(var q0,K0,I0,H0,W0=d.window;;){if(d.lookahead<=a){if(O0(d),d.lookahead<=a&&Q0===F)return T;if(d.lookahead===0)break}if(d.match_length=0,d.lookahead>=N&&0d.lookahead&&(d.match_length=d.lookahead)}if(d.match_length>=N?(q0=J._tr_tally(d,1,d.match_length-N),d.lookahead-=d.match_length,d.strstart+=d.match_length,d.match_length=0):(q0=J._tr_tally(d,0,d.window[d.strstart]),d.lookahead--,d.strstart++),q0&&(y(d,!1),d.strm.avail_out===0))return T}return d.insert=0,Q0===D?(y(d,!0),d.strm.avail_out===0?B0:i):d.last_lit&&(y(d,!1),d.strm.avail_out===0)?T:m}(V,p):K[V.level].func(V,p);if(l!==B0&&l!==i||(V.status=666),l===T||l===B0)return R.avail_out===0&&(V.last_flush=-1),w;if(l===m&&(p===1?J._tr_align(V):p!==5&&(J._tr_stored_block(V,0,0,!1),p===3&&(G0(V.head),V.lookahead===0&&(V.strstart=0,V.block_start=0,V.insert=0))),r(R),R.avail_out===0))return V.last_flush=-1,w}return p!==D?w:V.wrap<=0?1:(V.wrap===2?(n(V,255&R.adler),n(V,R.adler>>8&255),n(V,R.adler>>16&255),n(V,R.adler>>24&255),n(V,255&R.total_in),n(V,R.total_in>>8&255),n(V,R.total_in>>16&255),n(V,R.total_in>>24&255)):(o(V,R.adler>>>16),o(V,65535&R.adler)),r(R),0=k.w_size&&(O===0&&(G0(k.head),k.strstart=0,k.block_start=0,k.insert=0),Q0=new Z.Buf8(k.w_size),Z.arraySet(Q0,p,q0-k.w_size,k.w_size,0),p=Q0,q0=k.w_size),_=R.avail_in,l=R.next_in,d=R.input,R.avail_in=q0,R.next_in=0,R.input=p,O0(k);k.lookahead>=N;){for(V=k.strstart,q=k.lookahead-(N-1);k.ins_h=(k.ins_h<>>=N=x>>>24,v-=N,(N=x>>>16&255)===0)m[I++]=65535&x;else{if(!(16&N)){if((64&N)==0){x=S[(65535&x)+(j&(1<>>=N,v-=N),v<15&&(j+=T[M++]<>>=N=x>>>24,v-=N,!(16&(N=x>>>16&255))){if((64&N)==0){x=H[(65535&x)+(j&(1<>>=N,v-=N,(N=I-F)>3,j&=(1<<(v-=a<<3))-1,K.next_in=M,K.next_out=I,K.avail_in=M>>24&255)+(b>>>8&65280)+((65280&b)<<8)+((255&b)<<24)}function j(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new K.Buf16(320),this.work=new K.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(b){var c;return b&&b.state?(c=b.state,b.total_in=b.total_out=c.total=0,b.msg="",c.wrap&&(b.adler=1&c.wrap),c.mode=P,c.last=0,c.havedict=0,c.dmax=32768,c.head=null,c.hold=0,c.bits=0,c.lencode=c.lendyn=new K.Buf32(A),c.distcode=c.distdyn=new K.Buf32(E),c.sane=1,c.back=-1,D):w}function S(b){var c;return b&&b.state?((c=b.state).wsize=0,c.whave=0,c.wnext=0,v(b)):w}function H(b,c){var T,m;return b&&b.state?(m=b.state,c<0?(T=0,c=-c):(T=1+(c>>4),c<48&&(c&=15)),c&&(c<8||15=i.wsize?(K.arraySet(i.window,c,T-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(m<(B0=i.wsize-i.wnext)&&(B0=m),K.arraySet(i.window,c,T-m,B0,i.wnext),(m-=B0)?(K.arraySet(i.window,c,T-m,m,0),i.wnext=m,i.whave=i.wsize):(i.wnext+=B0,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,T.check=J(T.check,O,2,0),y=r=0,T.mode=2;break}if(T.flags=0,T.head&&(T.head.done=!1),!(1&T.wrap)||(((255&r)<<8)+(r>>8))%31){b.msg="incorrect header check",T.mode=30;break}if((15&r)!=8){b.msg="unknown compression method",T.mode=30;break}if(y-=4,R=8+(15&(r>>>=4)),T.wbits===0)T.wbits=R;else if(R>T.wbits){b.msg="invalid window size",T.mode=30;break}T.dmax=1<>8&1),512&T.flags&&(O[0]=255&r,O[1]=r>>>8&255,T.check=J(T.check,O,2,0)),y=r=0,T.mode=3;case 3:for(;y<32;){if(s===0)break B;s--,r+=m[i++]<>>8&255,O[2]=r>>>16&255,O[3]=r>>>24&255,T.check=J(T.check,O,4,0)),y=r=0,T.mode=4;case 4:for(;y<16;){if(s===0)break B;s--,r+=m[i++]<>8),512&T.flags&&(O[0]=255&r,O[1]=r>>>8&255,T.check=J(T.check,O,2,0)),y=r=0,T.mode=5;case 5:if(1024&T.flags){for(;y<16;){if(s===0)break B;s--,r+=m[i++]<>>8&255,T.check=J(T.check,O,2,0)),y=r=0}else T.head&&(T.head.extra=null);T.mode=6;case 6:if(1024&T.flags&&(s<(Y0=T.length)&&(Y0=s),Y0&&(T.head&&(R=T.head.extra_len-T.length,T.head.extra||(T.head.extra=Array(T.head.extra_len)),K.arraySet(T.head.extra,m,i,Y0,R)),512&T.flags&&(T.check=J(T.check,m,Y0,i)),s-=Y0,i+=Y0,T.length-=Y0),T.length))break B;T.length=0,T.mode=7;case 7:if(2048&T.flags){if(s===0)break B;for(Y0=0;R=m[i+Y0++],T.head&&R&&T.length<65536&&(T.head.name+=String.fromCharCode(R)),R&&Y0>9&1,T.head.done=!0),b.adler=T.check=0,T.mode=12;break;case 10:for(;y<32;){if(s===0)break B;s--,r+=m[i++]<>>=7&y,y-=7&y,T.mode=27;break}for(;y<3;){if(s===0)break B;s--,r+=m[i++]<>>=1)){case 0:T.mode=14;break;case 1:if(a(T),T.mode=20,c!==6)break;r>>>=2,y-=2;break B;case 2:T.mode=17;break;case 3:b.msg="invalid block type",T.mode=30}r>>>=2,y-=2;break;case 14:for(r>>>=7&y,y-=7&y;y<32;){if(s===0)break B;s--,r+=m[i++]<>>16^65535)){b.msg="invalid stored block lengths",T.mode=30;break}if(T.length=65535&r,y=r=0,T.mode=15,c===6)break B;case 15:T.mode=16;case 16:if(Y0=T.length){if(s>>=5,y-=5,T.ndist=1+(31&r),r>>>=5,y-=5,T.ncode=4+(15&r),r>>>=4,y-=4,286>>=3,y-=3}for(;T.have<19;)T.lens[_[T.have++]]=0;if(T.lencode=T.lendyn,T.lenbits=7,k={bits:T.lenbits},p=W(0,T.lens,0,19,T.lencode,0,T.work,k),T.lenbits=k.bits,p){b.msg="invalid code lengths set",T.mode=30;break}T.have=0,T.mode=19;case 19:for(;T.have>>16&255,h=65535&q,!((L=q>>>24)<=y);){if(s===0)break B;s--,r+=m[i++]<>>=L,y-=L,T.lens[T.have++]=h;else{if(h===16){for(V=L+2;y>>=L,y-=L,T.have===0){b.msg="invalid bit length repeat",T.mode=30;break}R=T.lens[T.have-1],Y0=3+(3&r),r>>>=2,y-=2}else if(h===17){for(V=L+3;y>>=L)),r>>>=3,y-=3}else{for(V=L+7;y>>=L)),r>>>=7,y-=7}if(T.have+Y0>T.nlen+T.ndist){b.msg="invalid bit length repeat",T.mode=30;break}for(;Y0--;)T.lens[T.have++]=R}}if(T.mode===30)break;if(T.lens[256]===0){b.msg="invalid code -- missing end-of-block",T.mode=30;break}if(T.lenbits=9,k={bits:T.lenbits},p=W(I,T.lens,0,T.nlen,T.lencode,0,T.work,k),T.lenbits=k.bits,p){b.msg="invalid literal/lengths set",T.mode=30;break}if(T.distbits=6,T.distcode=T.distdyn,k={bits:T.distbits},p=W(F,T.lens,T.nlen,T.ndist,T.distcode,0,T.work,k),T.distbits=k.bits,p){b.msg="invalid distances set",T.mode=30;break}if(T.mode=20,c===6)break B;case 20:T.mode=21;case 21:if(6<=s&&258<=G0){b.next_out=V0,b.avail_out=G0,b.next_in=i,b.avail_in=s,T.hold=r,T.bits=y,M(b,o),V0=b.next_out,B0=b.output,G0=b.avail_out,i=b.next_in,m=b.input,s=b.avail_in,r=T.hold,y=T.bits,T.mode===12&&(T.back=-1);break}for(T.back=0;u=(q=T.lencode[r&(1<>>16&255,h=65535&q,!((L=q>>>24)<=y);){if(s===0)break B;s--,r+=m[i++]<>Z0)])>>>16&255,h=65535&q,!(Z0+(L=q>>>24)<=y);){if(s===0)break B;s--,r+=m[i++]<>>=Z0,y-=Z0,T.back+=Z0}if(r>>>=L,y-=L,T.back+=L,T.length=h,u===0){T.mode=26;break}if(32&u){T.back=-1,T.mode=12;break}if(64&u){b.msg="invalid literal/length code",T.mode=30;break}T.extra=15&u,T.mode=22;case 22:if(T.extra){for(V=T.extra;y>>=T.extra,y-=T.extra,T.back+=T.extra}T.was=T.length,T.mode=23;case 23:for(;u=(q=T.distcode[r&(1<>>16&255,h=65535&q,!((L=q>>>24)<=y);){if(s===0)break B;s--,r+=m[i++]<>Z0)])>>>16&255,h=65535&q,!(Z0+(L=q>>>24)<=y);){if(s===0)break B;s--,r+=m[i++]<>>=Z0,y-=Z0,T.back+=Z0}if(r>>>=L,y-=L,T.back+=L,64&u){b.msg="invalid distance code",T.mode=30;break}T.offset=h,T.extra=15&u,T.mode=24;case 24:if(T.extra){for(V=T.extra;y>>=T.extra,y-=T.extra,T.back+=T.extra}if(T.offset>T.dmax){b.msg="invalid distance too far back",T.mode=30;break}T.mode=25;case 25:if(G0===0)break B;if(Y0=o-G0,T.offset>Y0){if((Y0=T.offset-Y0)>T.whave&&T.sane){b.msg="invalid distance too far back",T.mode=30;break}O0=Y0>T.wnext?(Y0-=T.wnext,T.wsize-Y0):T.wnext-Y0,Y0>T.length&&(Y0=T.length),z=T.window}else z=B0,O0=V0-T.offset,Y0=T.length;for(G0$?(N=O0[z+E[c]],y[n+E[c]]):(N=96,0),j=1<>V0)+(v-=j)]=x<<24|N<<16|a|0,v!==0;);for(j=1<>=1;if(j!==0?(r&=j-1,r+=j):r=0,c++,--o[b]==0){if(b===m)break;b=F[D+E[c]]}if(B0>>7)]}function n(q,O){q.pending_buf[q.pending++]=255&O,q.pending_buf[q.pending++]=O>>>8&255}function o(q,O,_){q.bi_valid>C-_?(q.bi_buf|=O<>C-q.bi_valid,q.bi_valid+=_-C):(q.bi_buf|=O<>>=1,_<<=1,0<--O;);return _>>>1}function z(q,O,_){var l,d,Q0=Array(E+1),q0=0;for(l=1;l<=E;l++)Q0[l]=q0=q0+_[l-1]<<1;for(d=0;d<=O;d++){var K0=q[2*d+1];K0!==0&&(q[2*d]=O0(Q0[K0]++,K0))}}function L(q){var O;for(O=0;O>1;1<=_;_--)Z0(q,Q0,_);for(d=I0;_=q.heap[1],q.heap[1]=q.heap[q.heap_len--],Z0(q,Q0,1),l=q.heap[1],q.heap[--q.heap_max]=_,q.heap[--q.heap_max]=l,Q0[2*d]=Q0[2*_]+Q0[2*l],q.depth[d]=(q.depth[_]>=q.depth[l]?q.depth[_]:q.depth[l])+1,Q0[2*_+1]=Q0[2*l+1]=d,q.heap[1]=d++,Z0(q,Q0,1),2<=q.heap_len;);q.heap[--q.heap_max]=q.heap[1],function(W0,k0){var L2,m0,r2,N0,W1,a1,Y2=k0.dyn_tree,L6=k0.max_code,q5=k0.stat_desc.static_tree,M5=k0.stat_desc.has_stree,X5=k0.stat_desc.extra_bits,I6=k0.stat_desc.extra_base,i2=k0.stat_desc.max_length,P1=0;for(N0=0;N0<=E;N0++)W0.bl_count[N0]=0;for(Y2[2*W0.heap[W0.heap_max]+1]=0,L2=W0.heap_max+1;L2>=7;d>>=1)if(1&H0&&K0.dyn_ltree[2*I0]!==0)return Z;if(K0.dyn_ltree[18]!==0||K0.dyn_ltree[20]!==0||K0.dyn_ltree[26]!==0)return J;for(I0=32;I0>>3,(Q0=q.static_len+3+7>>>3)<=d&&(d=Q0)):d=Q0=_+5,_+4<=d&&O!==-1?V(q,O,_,l):q.strategy===4||Q0===d?(o(q,2+(l?1:0),3),g(q,U0,b)):(o(q,4+(l?1:0),3),function(K0,I0,H0,W0){var k0;for(o(K0,I0-257,5),o(K0,H0-1,5),o(K0,W0-4,4),k0=0;k0>>8&255,q.pending_buf[q.d_buf+2*q.last_lit+1]=255&O,q.pending_buf[q.l_buf+q.last_lit]=255&_,q.last_lit++,O===0?q.dyn_ltree[2*_]++:(q.matches++,O--,q.dyn_ltree[2*(T[_]+F+1)]++,q.dyn_dtree[2*y(O)]++),q.last_lit===q.lit_bufsize-1},Q._tr_align=function(q){o(q,2,3),Y0(q,v,U0),function(O){O.bi_valid===16?(n(O,O.bi_buf),O.bi_buf=0,O.bi_valid=0):8<=O.bi_valid&&(O.pending_buf[O.pending++]=255&O.bi_buf,O.bi_buf>>=8,O.bi_valid-=8)}(q)}},{"../utils/common":41}],53:[function(G,Y,Q){Y.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(G,Y,Q){(function(K){(function(Z,J){if(!Z.setImmediate){var M,W,I,F,D=1,w={},P=!1,A=Z.document,E=Object.getPrototypeOf&&Object.getPrototypeOf(Z);E=E&&E.setTimeout?E:Z,M={}.toString.call(Z.process)==="[object process]"?function(S){P0.nextTick(function(){j(S)})}:function(){if(Z.postMessage&&!Z.importScripts){var S=!0,H=Z.onmessage;return Z.onmessage=function(){S=!1},Z.postMessage("","*"),Z.onmessage=H,S}}()?(F="setImmediate$"+Math.random()+"$",Z.addEventListener?Z.addEventListener("message",v,!1):Z.attachEvent("onmessage",v),function(S){Z.postMessage(F+S,"*")}):Z.MessageChannel?((I=new MessageChannel).port1.onmessage=function(S){j(S.data)},function(S){I.port2.postMessage(S)}):A&&("onreadystatechange"in A.createElement("script"))?(W=A.documentElement,function(S){var H=A.createElement("script");H.onreadystatechange=function(){j(S),H.onreadystatechange=null,W.removeChild(H),H=null},W.appendChild(H)}):function(S){setTimeout(j,0,S)},E.setImmediate=function(S){typeof S!="function"&&(S=Function(""+S));for(var H=Array(arguments.length-1),X=0;X"u"?K===void 0?this:K:self)}).call(this,typeof v0<"u"?v0:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})}),kK=R0((B,U)=>{var G={"&":"&",'"':""","'":"'","<":"<",">":">"};function Y(Q){return Q&&Q.replace?Q.replace(/([&"<>'])/g,function(K,Z){return G[Z]}):Q}U.exports=Y}),$K=R0((B,U)=>{P2();var G=kK(),Y=f8().Stream,Q=" ";function K(F,D){if(typeof D!=="object")D={indent:D};var w=D.stream?new Y:null,P="",A=!1,E=!D.indent?"":D.indent===!0?Q:D.indent,C=!0;function j($){if(!C)$();else P0.nextTick($)}function v($,x){if(x!==void 0)P+=x;if($&&!A)w=w||new Y,A=!0;if($&&A){var N=P;j(function(){w.emit("data",N)}),P=""}}function S($,x){W(v,M($,E,E?1:0),x)}function H(){if(w){var $=P;j(function(){w.emit("data",$),w.emit("end"),w.readable=!1,w.emit("close")})}}function X($){var x={version:"1.0",encoding:$.encoding||"UTF-8"};if($.standalone)x.standalone=$.standalone;S({"?xml":{_attr:x}}),P=P.replace("/>","?>")}if(j(function(){C=!1}),D.declaration)X(D.declaration);if(F&&F.forEach)F.forEach(function($,x){var N;if(x+1===F.length)N=H;S($,N)});else S(F,H);if(w)return w.readable=!0,w;return P}function Z(){var F={_elem:M(Array.prototype.slice.call(arguments))};return F.push=function(D){if(!this.append)throw Error("not assigned to a parent!");var w=this,P=this._elem.indent;W(this.append,M(D,P,this._elem.icount+(P?1:0)),function(){w.append(!0)})},F.close=function(D){if(D!==void 0)this.push(D);if(this.end)this.end()},F}function J(F,D){return Array(D||0).join(F||"")}function M(F,D,w){w=w||0;var P=J(D,w),A,E=F,C=!1;if(typeof F==="object"){if(A=Object.keys(F)[0],E=F[A],E&&E._elem)return E._elem.name=A,E._elem.icount=w,E._elem.indent=D,E._elem.indents=P,E._elem.interrupt=E,E._elem}var j=[],v=[],S;function H(X){Object.keys(X).forEach(function($){j.push(I($,X[$]))})}switch(typeof E){case"object":if(E===null)break;if(E._attr)H(E._attr);if(E._cdata)v.push(("/g,"]]]]>")+"]]>");if(E.forEach){if(S=!1,v.push(""),E.forEach(function(X){if(typeof X=="object")if(Object.keys(X)[0]=="_attr")H(X._attr);else v.push(M(X,D,w+1));else v.pop(),S=!0,v.push(G(X))}),!S)v.push("")}break;default:v.push(G(E))}return{name:A,interrupt:C,attributes:j,content:v,icount:w,indents:P,indent:D}}function W(F,D,w){if(typeof D!="object")return F(!1,D);var P=D.interrupt?1:D.content.length;function A(){while(D.content.length){var C=D.content.shift();if(C===void 0)continue;if(E(C))return;W(F,C)}if(F(!1,(P>1?D.indents:"")+(D.name?"":"")+(D.indent&&!w?` -`:"")),w)w()}function E(C){if(C.interrupt)return C.interrupt.append=F,C.interrupt.end=A,C.interrupt=!1,F(!0),!0;return!1}if(F(!1,D.indents+(D.name?"<"+D.name:"")+(D.attributes.length?" "+D.attributes.join(" "):"")+(P?D.name?">":"":D.name?"/>":"")+(D.indent&&P>1?` -`:"")),!P)return F(!1,D.indent?` -`:"");if(!E(D))A()}function I(F,D){return F+'="'+G(D)+'"'}U.exports=K,U.exports.element=U.exports.Element=Z}),SK=f8(),h2=C8(CK(),1),w0=C8($K(),1),o2=0,X8=32,bK=32,vK=(B,U)=>{let G=U.replace(/-/g,"");if(G.length!==bK)throw Error(`Error: Cannot extract GUID from font filename: ${U}`);let Y=G.replace(/(..)/g,"$1 ").trim().split(" ").map((Z)=>parseInt(Z,16));Y.reverse();let Q=B.slice(o2,X8).map((Z,J)=>Z^Y[J%Y.length]),K=new Uint8Array(o2+Q.length+Math.max(0,B.length-X8));return K.set(B.slice(0,o2)),K.set(Q,o2),K.set(B.slice(X8),o2+Q.length),K},q6=class{format(B,U={stack:[]}){let G=B.prepForXml(U);if(G)return G;else throw Error("XMLComponent did not format correctly")}},U5=class{replace(B,U,G){let Y=B;return U.forEach((Q,K)=>{Y=Y.replace(new RegExp(`{${Q.fileName}}`,"g"),(G+K).toString())}),Y}getMediaData(B,U){return U.Array.filter((G)=>B.search(`{${G.fileName}}`)>0)}},yK=class{replace(B,U){let G=B;for(let Y of U)G=G.replace(new RegExp(`{${Y.reference}-${Y.instance}}`,"g"),Y.numId.toString());return G}},gK=class{constructor(){e(this,"formatter",void 0),e(this,"imageReplacer",void 0),e(this,"numberingReplacer",void 0),this.formatter=new q6,this.imageReplacer=new U5,this.numberingReplacer=new yK}compile(B,U,G=[]){let Y=new h2.default,Q=this.xmlifyFile(B,U),K=new Map(Object.entries(Q));for(let[,Z]of K)if(Array.isArray(Z))for(let J of Z)Y.file(J.path,U1(J.data));else Y.file(Z.path,U1(Z.data));for(let Z of G)Y.file(Z.path,U1(Z.data));for(let Z of B.Media.Array)if(Z.type!=="svg")Y.file(`word/media/${Z.fileName}`,Z.data);else Y.file(`word/media/${Z.fileName}`,Z.data),Y.file(`word/media/${Z.fallback.fileName}`,Z.fallback.data);for(let[Z,{data:J,fontKey:M}]of B.FontTable.fontOptionsWithKey.entries())Y.file(`word/fonts/font${Z+1}.odttf`,vK(J,M));return Y}xmlifyFile(B,U){let G=B.Document.Relationships.RelationshipCount+1,Y=(0,w0.default)(this.formatter.format(B.Document.View,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),Q=B.Comments.Relationships.RelationshipCount+1,K=(0,w0.default)(this.formatter.format(B.Comments,{viewWrapper:{View:B.Comments,Relationships:B.Comments.Relationships},file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),Z=B.FootNotes.Relationships.RelationshipCount+1,J=(0,w0.default)(this.formatter.format(B.FootNotes.View,{viewWrapper:B.FootNotes,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),M=this.imageReplacer.getMediaData(Y,B.Media),W=this.imageReplacer.getMediaData(K,B.Media),I=this.imageReplacer.getMediaData(J,B.Media);return L0(L0({Relationships:{data:(()=>{return M.forEach((F,D)=>{B.Document.Relationships.addRelationship(G+D,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${F.fileName}`)}),B.Document.Relationships.addRelationship(B.Document.Relationships.RelationshipCount+1,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable","fontTable.xml"),(0,w0.default)(this.formatter.format(B.Document.Relationships,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/document.xml.rels"},Document:{data:(()=>{let F=this.imageReplacer.replace(Y,M,G);return this.numberingReplacer.replace(F,B.Numbering.ConcreteNumbering)})(),path:"word/document.xml"},Styles:{data:(()=>{let F=(0,w0.default)(this.formatter.format(B.Styles,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}});return this.numberingReplacer.replace(F,B.Numbering.ConcreteNumbering)})(),path:"word/styles.xml"},Properties:{data:(0,w0.default)(this.formatter.format(B.CoreProperties,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/core.xml"},Numbering:{data:(0,w0.default)(this.formatter.format(B.Numbering,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/numbering.xml"},FileRelationships:{data:(0,w0.default)(this.formatter.format(B.FileRelationships,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"_rels/.rels"},HeaderRelationships:B.Headers.map((F,D)=>{let w=(0,w0.default)(this.formatter.format(F.View,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}});return this.imageReplacer.getMediaData(w,B.Media).forEach((P,A)=>{F.Relationships.addRelationship(A,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${P.fileName}`)}),{data:(0,w0.default)(this.formatter.format(F.Relationships,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:`word/_rels/header${D+1}.xml.rels`}}),FooterRelationships:B.Footers.map((F,D)=>{let w=(0,w0.default)(this.formatter.format(F.View,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}});return this.imageReplacer.getMediaData(w,B.Media).forEach((P,A)=>{F.Relationships.addRelationship(A,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${P.fileName}`)}),{data:(0,w0.default)(this.formatter.format(F.Relationships,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:`word/_rels/footer${D+1}.xml.rels`}}),Headers:B.Headers.map((F,D)=>{let w=(0,w0.default)(this.formatter.format(F.View,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),P=this.imageReplacer.getMediaData(w,B.Media),A=this.imageReplacer.replace(w,P,0);return{data:this.numberingReplacer.replace(A,B.Numbering.ConcreteNumbering),path:`word/header${D+1}.xml`}}),Footers:B.Footers.map((F,D)=>{let w=(0,w0.default)(this.formatter.format(F.View,{viewWrapper:F,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),P=this.imageReplacer.getMediaData(w,B.Media),A=this.imageReplacer.replace(w,P,0);return{data:this.numberingReplacer.replace(A,B.Numbering.ConcreteNumbering),path:`word/footer${D+1}.xml`}}),ContentTypes:{data:(0,w0.default)(this.formatter.format(B.ContentTypes,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"[Content_Types].xml"},CustomProperties:{data:(0,w0.default)(this.formatter.format(B.CustomProperties,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/custom.xml"},AppProperties:{data:(0,w0.default)(this.formatter.format(B.AppProperties,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/app.xml"},FootNotes:{data:(()=>{let F=this.imageReplacer.replace(J,I,Z);return this.numberingReplacer.replace(F,B.Numbering.ConcreteNumbering)})(),path:"word/footnotes.xml"},FootNotesRelationships:{data:(()=>{return I.forEach((F,D)=>{B.FootNotes.Relationships.addRelationship(Z+D,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${F.fileName}`)}),(0,w0.default)(this.formatter.format(B.FootNotes.Relationships,{viewWrapper:B.FootNotes,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/footnotes.xml.rels"},Endnotes:{data:(0,w0.default)(this.formatter.format(B.Endnotes.View,{viewWrapper:B.Endnotes,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"word/endnotes.xml"},EndnotesRelationships:{data:(0,w0.default)(this.formatter.format(B.Endnotes.Relationships,{viewWrapper:B.Endnotes,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"word/_rels/endnotes.xml.rels"},Settings:{data:(0,w0.default)(this.formatter.format(B.Settings,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/settings.xml"},Comments:{data:(()=>{let F=this.imageReplacer.replace(K,W,Q);return this.numberingReplacer.replace(F,B.Numbering.ConcreteNumbering)})(),path:"word/comments.xml"},CommentsRelationships:{data:(()=>{return W.forEach((F,D)=>{B.Comments.Relationships.addRelationship(Q+D,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${F.fileName}`)}),(0,w0.default)(this.formatter.format(B.Comments.Relationships,{viewWrapper:{View:B.Comments,Relationships:B.Comments.Relationships},file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/comments.xml.rels"}},B.CommentsExtended?{CommentsExtended:{data:(0,w0.default)(this.formatter.format(B.CommentsExtended,{viewWrapper:{View:B.CommentsExtended,Relationships:B.Comments.Relationships},file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/commentsExtended.xml"}}:{}),{},{FontTable:{data:(0,w0.default)(this.formatter.format(B.FontTable.View,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/fontTable.xml"},FontTableRelationships:{data:(0,w0.default)(this.formatter.format(B.FontTable.Relationships,{viewWrapper:B.Document,file:B,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"word/_rels/fontTable.xml.rels"}})}};function t6(B,U,G,Y,Q,K,Z){try{var J=B[K](Z),M=J.value}catch(W){G(W);return}J.done?U(M):Promise.resolve(M).then(Y,Q)}function M6(B){return function(){var U=this,G=arguments;return new Promise(function(Y,Q){var K=B.apply(U,G);function Z(M){t6(K,Y,Q,Z,J,"next",M)}function J(M){t6(K,Y,Q,Z,J,"throw",M)}Z(void 0)})}}var G5={NONE:"",WITH_2_BLANKS:" ",WITH_4_BLANKS:" ",WITH_TAB:"\t"},e6=(B)=>B===!0?G5.WITH_2_BLANKS:B===!1?void 0:B,Y5=class B{static pack(U,G,Y){var Q=this;return M6(function*(K,Z,J,M=[]){return Q.compiler.compile(K,e6(J),M).generateAsync({type:Z,mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",compression:"DEFLATE"})}).apply(this,arguments)}static toString(U,G,Y=[]){return B.pack(U,"string",G,Y)}static toBuffer(U,G,Y=[]){return B.pack(U,"nodebuffer",G,Y)}static toBase64String(U,G,Y=[]){return B.pack(U,"base64",G,Y)}static toBlob(U,G,Y=[]){return B.pack(U,"blob",G,Y)}static toArrayBuffer(U,G,Y=[]){return B.pack(U,"arraybuffer",G,Y)}static toStream(U,G,Y=[]){let Q=new SK.Stream;return this.compiler.compile(U,e6(G),Y).generateAsync({type:"nodebuffer",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",compression:"DEFLATE"}).then((K)=>{Q.emit("data",K),Q.emit("end")}),Q}};e(Y5,"compiler",new gK);var fK=new q6,l1=(B)=>{return(0,_1.xml2js)(B,{compact:!1,captureSpacesBetweenElements:!0})},Z5=(B)=>{var U;return(U=l1((0,w0.default)(fK.format(new Z1({text:B})))).elements[0].elements)!==null&&U!==void 0?U:[]},Q5=(B)=>L0(L0({},B),{},{attributes:{"xml:space":"preserve"}}),X6=(B,U)=>{var G,Y;return(G=(Y=B.elements)===null||Y===void 0?void 0:Y.filter((Q)=>Q.name===U)[0].elements)!==null&&G!==void 0?G:[]},g2=(B,U,G)=>{let Y=X6(B,"Types");if(Y.some((Q)=>{var K,Z;return Q.type==="element"&&Q.name==="Default"&&(Q===null||Q===void 0||(K=Q.attributes)===null||K===void 0?void 0:K.ContentType)===U&&(Q===null||Q===void 0||(Z=Q.attributes)===null||Z===void 0?void 0:Z.Extension)===G}))return;Y.push({attributes:{ContentType:U,Extension:G},name:"Default",type:"element"})},xK=(B)=>{let U=parseInt(B.substring(3),10);return isNaN(U)?0:U},_K=(B)=>{return X6(B,"Relationships").map((U)=>{var G,Y;return xK((G=(Y=U.attributes)===null||Y===void 0||(Y=Y.Id)===null||Y===void 0?void 0:Y.toString())!==null&&G!==void 0?G:"")}).reduce((U,G)=>Math.max(U,G),0)+1},BB=(B,U,G,Y,Q)=>{let K=X6(B,"Relationships");return K.push({attributes:{Id:`rId${U}`,Type:G,Target:Y,TargetMode:Q},name:"Relationship",type:"element"}),K},hK=class extends Error{constructor(B){super(`Token ${B} not found`);this.name="TokenNotFoundError"}},uK=(B,U)=>{var G;for(let Z=0;Z<((G=B.elements)!==null&&G!==void 0?G:[]).length;Z++){let J=B.elements[Z];if(J.type==="element"&&J.name==="w:r"){var Y;let M=((Y=J.elements)!==null&&Y!==void 0?Y:[]).filter((W)=>W.type==="element"&&W.name==="w:t");for(let W of M){var Q,K;if(!((Q=W.elements)===null||Q===void 0?void 0:Q[0]))continue;if((K=W.elements[0].text)===null||K===void 0?void 0:K.includes(U))return Z}}}throw new hK(U)},dK=(B,U)=>{var G,Y;let Q=-1,K=(G=(Y=B.elements)===null||Y===void 0?void 0:Y.map((Z,J)=>{if(Q!==-1)return Z;if(Z.type==="element"&&Z.name==="w:t"){var M,W;let I=((M=(W=Z.elements)===null||W===void 0||(W=W[0])===null||W===void 0?void 0:W.text)!==null&&M!==void 0?M:"").split(U),F=I.map((D)=>L0(L0(L0({},Z),Q5(Z)),{},{elements:Z5(D)}));if(I.length>1)Q=J;return F}else return Z}).flat())!==null&&G!==void 0?G:[];return{left:L0(L0({},JSON.parse(JSON.stringify(B))),{},{elements:K.slice(0,Q+1)}),right:L0(L0({},JSON.parse(JSON.stringify(B))),{},{elements:K.slice(Q+1)})}},t2={START:0,MIDDLE:1,END:2},cK=({paragraphElement:B,renderedParagraph:U,originalText:G,replacementText:Y})=>{let Q=U.text.indexOf(G),K=Q+G.length-1,Z=t2.START;for(let J of U.runs)for(let{text:M,index:W,start:I,end:F}of J.parts)switch(Z){case t2.START:if(Q>=I&&Q<=F){let D=Q-I,w=Math.min(K,F)-I,P=J.text.substring(D,w+1);if(P==="")continue;let A=M.replace(P,Y);R8(B.elements[J.index].elements[W],A),Z=t2.MIDDLE;continue}break;case t2.MIDDLE:if(K<=F){let D=M.substring(K-I+1);R8(B.elements[J.index].elements[W],D);let w=B.elements[J.index].elements[W];B.elements[J.index].elements[W]=Q5(w),Z=t2.END}else R8(B.elements[J.index].elements[W],"");break;default:}return B},R8=(B,U)=>{return B.elements=Z5(U),B},mK=(B)=>{if(B.element.name!=="w:p")throw Error(`Invalid node type: ${B.element.name}`);if(!B.element.elements)return{text:"",runs:[],index:-1,pathToParagraph:[]};let U=0,G=B.element.elements.map((Y,Q)=>({element:Y,i:Q})).filter(({element:Y})=>Y.name==="w:r").map(({element:Y,i:Q})=>{let K=lK(Y,Q,U);return U+=K.text.length,K}).filter((Y)=>!!Y);return{text:G.reduce((Y,Q)=>Y+Q.text,""),runs:G,index:B.index,pathToParagraph:J5(B)}},lK=(B,U,G)=>{if(!B.elements)return{text:"",parts:[],index:-1,start:G,end:G};let Y=G,Q=B.elements.map((K,Z)=>{var J,M;return K.name==="w:t"&&K.elements&&K.elements.length>0?{text:(J=(M=K.elements[0].text)===null||M===void 0?void 0:M.toString())!==null&&J!==void 0?J:"",index:Z,start:Y,end:(()=>{var W,I;return Y+=((W=(I=K.elements[0].text)===null||I===void 0?void 0:I.toString())!==null&&W!==void 0?W:"").length-1,Y})()}:void 0}).filter((K)=>!!K).map((K)=>K);return{text:Q.reduce((K,Z)=>K+Z.text,""),parts:Q,index:U,start:G,end:Y}},J5=(B)=>B.parent?[...J5(B.parent),B.index]:[B.index],UB=(B)=>{var U,G;return(U=(G=B.element.elements)===null||G===void 0?void 0:G.map((Y,Q)=>({element:Y,index:Q,parent:B})))!==null&&U!==void 0?U:[]},K5=(B)=>{let U=[],G=[...UB({element:B,index:0,parent:void 0})],Y;while(G.length>0){if(Y=G.shift(),Y.element.name==="w:p")U=[...U,mK(Y)];G.push(...UB(Y))}return U},aK=(B,U)=>K5(B).filter((G)=>G.text.includes(U)),pK=new q6,L8="ɵ",rK=({json:B,patch:U,patchText:G,context:Y,keepOriginalStyles:Q=!0})=>{let K=aK(B,G);if(K.length===0)return{element:B,didFindOccurrence:!1};for(let Z of K){let J=U.children.map((M)=>l1((0,w0.default)(pK.format(M,Y)))).map((M)=>M.elements[0]);switch(U.type){case D8.DOCUMENT:{let M=iK(B,Z.pathToParagraph),W=nK(Z.pathToParagraph);M.elements.splice(W,1,...J);break}case D8.PARAGRAPH:default:{let M=V5(B,Z.pathToParagraph);cK({paragraphElement:M,renderedParagraph:Z,originalText:G,replacementText:L8});let W=uK(M,L8),I=M.elements[W],{left:F,right:D}=dK(I,L8),w=J,P=D;if(Q){let A=I.elements.filter((E)=>E.type==="element"&&E.name==="w:rPr");w=J.map((E)=>{var C;return L0(L0({},E),{},{elements:[...A,...(C=E.elements)!==null&&C!==void 0?C:[]]})}),P=L0(L0({},D),{},{elements:[...A,...D.elements]})}M.elements.splice(W,1,F,...w,P);break}}}return{element:B,didFindOccurrence:!0}},V5=(B,U)=>{let G=B;for(let Y=1;YV5(B,U.slice(0,U.length-1)),nK=(B)=>B[B.length-1],D8={DOCUMENT:"file",PARAGRAPH:"paragraph"},GB=new U5,sK=new Uint8Array([255,254]),oK=new Uint8Array([254,255]),YB=(B,U)=>{if(B.length!==U.length)return!1;for(let G=0;GN.name==="w:document");if(x&&x.attributes){for(let N of["mc","wp","r","w15","m"])x.attributes[`xmlns:${N}`]=v1[N];x.attributes["mc:Ignorable"]=`${x.attributes["mc:Ignorable"]||""} w15`.trim()}}if(v.startsWith("word/")&&!v.endsWith(".xml.rels")){let x={file:W,viewWrapper:{Relationships:{addRelationship:(b,c,T,m)=>{D.push({key:v,hyperlink:{id:b,link:T}})}}},stack:[]};if(M.set(v,x),!(K===null||K===void 0?void 0:K.start.trim())||!(K===null||K===void 0?void 0:K.end.trim()))throw Error("Both start and end delimiters must be non-empty strings.");let{start:N,end:a}=K;for(let[b,c]of Object.entries(Y)){let T=`${N}${b}${a}`;while(!0){let{didFindOccurrence:m}=rK({json:$,patch:L0(L0({},c),{},{children:c.children.map((B0)=>{if(B0 instanceof o8){let i=new m2(B0.options.children,O1());return D.push({key:v,hyperlink:{id:i.linkId,link:B0.options.link}}),i}else return B0})}),patchText:T,context:x,keepOriginalStyles:Q});if(!Z||!m)break}}let U0=GB.getMediaData(JSON.stringify($),x.file.Media);if(U0.length>0)w=!0,F.push({key:v,mediaDatas:U0})}I.set(v,$)}for(let{key:v,mediaDatas:S}of F){var E;let H=`word/_rels/${v.split("/").pop()}.rels`,X=(E=I.get(H))!==null&&E!==void 0?E:ZB();I.set(H,X);let $=_K(X),x=GB.replace(JSON.stringify(I.get(v)),S,$);I.set(v,JSON.parse(x));for(let N=0;N{return(0,_1.js2xml)(B,{attributeValueFn:(U)=>String(U).replace(/&(?!amp;|lt;|gt;|quot;|apos;)/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")})},ZB=()=>({declaration:{attributes:{version:"1.0",encoding:"UTF-8",standalone:"yes"}},elements:[{type:"element",name:"Relationships",attributes:{xmlns:"http://schemas.openxmlformats.org/package/2006/relationships"},elements:[]}]}),B7=function(){var B=M6(function*({data:U}){let G=U instanceof h2.default?U:yield h2.default.loadAsync(U),Y=new Set;for(let[Q,K]of Object.entries(G.files)){if(!Q.endsWith(".xml")&&!Q.endsWith(".rels"))continue;if(Q.startsWith("word/")&&!Q.endsWith(".xml.rels"))K5(l1(yield K.async("text"))).forEach((Z)=>U7(Z.text).forEach((J)=>Y.add(J)))}return Array.from(Y)});return function(G){return B.apply(this,arguments)}}(),U7=(B)=>{var U;let G=new RegExp("(?<=\\{\\{).+?(?=\\}\\})","gs");return(U=B.match(G))!==null&&U!==void 0?U:[]};if(typeof globalThis.Buffer>"u")globalThis.Buffer=J0;if(typeof globalThis.process>"u")globalThis.process=G7;globalThis.__bundles=globalThis.__bundles||{};globalThis.__bundles.docx=R6;})(); +(()=>{var F7=Object.create;var{getPrototypeOf:N7,defineProperty:F8,getOwnPropertyNames:R7}=Object;var D7=Object.prototype.hasOwnProperty;function A7($){return this[$]}var P7,T7,C7=($,U,Y)=>{var Z=$!=null&&typeof $==="object";if(Z){var J=U?P7??=new WeakMap:T7??=new WeakMap,G=J.get($);if(G)return G}Y=$!=null?F7(N7($)):{};let X=U||!$||!$.__esModule?F8(Y,"default",{value:$,enumerable:!0}):Y;for(let Q of R7($))if(!D7.call(X,Q))F8(X,Q,{get:A7.bind($,Q),enumerable:!0});if(Z)J.set($,X);return X};var O7=($,U)=>()=>(U||$((U={exports:{}}).exports,U),U.exports);var k7=($)=>$;function E7($,U){this[$]=k7.bind(null,U)}var S7=($,U)=>{for(var Y in U)F8($,Y,{get:U[Y],enumerable:!0,configurable:!0,set:E7.bind(U,Y)})};var iU=O7((hB,pU)=>{var A0=pU.exports={},i0,r0;function S8(){throw Error("setTimeout has not been defined")}function v8(){throw Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function")i0=setTimeout;else i0=S8}catch($){i0=S8}try{if(typeof clearTimeout==="function")r0=clearTimeout;else r0=v8}catch($){r0=v8}})();function mU($){if(i0===setTimeout)return setTimeout($,0);if((i0===S8||!i0)&&setTimeout)return i0=setTimeout,setTimeout($,0);try{return i0($,0)}catch(U){try{return i0.call(null,$,0)}catch(Y){return i0.call(this,$,0)}}}function Xq($){if(r0===clearTimeout)return clearTimeout($);if((r0===v8||!r0)&&clearTimeout)return r0=clearTimeout,clearTimeout($);try{return r0($)}catch(U){try{return r0.call(null,$)}catch(Y){return r0.call(this,$)}}}var X2=[],g2=!1,T2,O1=-1;function Vq(){if(!g2||!T2)return;if(g2=!1,T2.length)X2=T2.concat(X2);else O1=-1;if(X2.length)lU()}function lU(){if(g2)return;var $=mU(Vq);g2=!0;var U=X2.length;while(U){T2=X2,X2=[];while(++O11)for(var Y=1;Y"u")DU.global=globalThis;var a0=[],u0=[],N8="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(A2=0,AU=N8.length;A20)throw Error("Invalid string. Length must be a multiple of 4");var Y=$.indexOf("=");if(Y===-1)Y=U;var Z=Y===U?0:4-Y%4;return[Y,Z]}function _7($,U){return($+U)*3/4-U}function y7($){var U,Y=v7($),Z=Y[0],J=Y[1],G=new Uint8Array(_7(Z,J)),X=0,Q=J>0?Z-4:Z,B;for(B=0;B>16&255,G[X++]=U>>8&255,G[X++]=U&255;if(J===2)U=u0[$.charCodeAt(B)]<<2|u0[$.charCodeAt(B+1)]>>4,G[X++]=U&255;if(J===1)U=u0[$.charCodeAt(B)]<<10|u0[$.charCodeAt(B+1)]<<4|u0[$.charCodeAt(B+2)]>>2,G[X++]=U>>8&255,G[X++]=U&255;return G}function b7($){return a0[$>>18&63]+a0[$>>12&63]+a0[$>>6&63]+a0[$&63]}function g7($,U,Y){var Z,J=[];for(var G=U;GQ?Q:X+G));if(Z===1)U=$[Y-1],J.push(a0[U>>2]+a0[U<<4&63]+"==");else if(Z===2)U=($[Y-2]<<8)+$[Y-1],J.push(a0[U>>10]+a0[U>>4&63]+a0[U<<2&63]+"=");return J.join("")}function T1($,U,Y,Z,J){var G,X,Q=J*8-Z-1,B=(1<>1,z=-7,W=Y?J-1:0,k=Y?-1:1,D=$[U+W];W+=k,G=D&(1<<-z)-1,D>>=-z,z+=Q;for(;z>0;G=G*256+$[U+W],W+=k,z-=8);X=G&(1<<-z)-1,G>>=-z,z+=Z;for(;z>0;X=X*256+$[U+W],W+=k,z-=8);if(G===0)G=1-F;else if(G===B)return X?NaN:(D?-1:1)*(1/0);else X=X+Math.pow(2,Z),G=G-F;return(D?-1:1)*X*Math.pow(2,G-Z)}function EU($,U,Y,Z,J,G){var X,Q,B,F=G*8-J-1,z=(1<>1,k=J===23?Math.pow(2,-24)-Math.pow(2,-77):0,D=Z?0:G-1,C=Z?1:-1,H=U<0||U===0&&1/U<0?1:0;if(U=Math.abs(U),isNaN(U)||U===1/0)Q=isNaN(U)?1:0,X=z;else{if(X=Math.floor(Math.log(U)/Math.LN2),U*(B=Math.pow(2,-X))<1)X--,B*=2;if(X+W>=1)U+=k/B;else U+=k*Math.pow(2,1-W);if(U*B>=2)X++,B/=2;if(X+W>=z)Q=0,X=z;else if(X+W>=1)Q=(U*B-1)*Math.pow(2,J),X=X+W;else Q=U*Math.pow(2,W-1)*Math.pow(2,J),X=0}for(;J>=8;$[Y+D]=Q&255,D+=C,Q/=256,J-=8);X=X<0;$[Y+D]=X&255,D+=C,X/=256,F-=8);$[Y+D-C]|=H*128}var TU=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null,x7=50,R8=2147483647;var{btoa:EB,atob:SB,File:vB,Blob:_B}=globalThis;function q2($){if($>R8)throw RangeError('The value "'+$+'" is invalid for option "size"');let U=new Uint8Array($);return Object.setPrototypeOf(U,G0.prototype),U}function C8($,U,Y){return class extends Y{constructor(){super();Object.defineProperty(this,"message",{value:U.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${$}]`,this.stack,delete this.name}get code(){return $}set code(Z){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:Z,writable:!0})}toString(){return`${this.name} [${$}]: ${this.message}`}}}var f7=C8("ERR_BUFFER_OUT_OF_BOUNDS",function($){if($)return`${$} is outside of buffer bounds`;return"Attempt to access memory outside buffer bounds"},RangeError),h7=C8("ERR_INVALID_ARG_TYPE",function($,U){return`The "${$}" argument must be of type number. Received type ${typeof U}`},TypeError),D8=C8("ERR_OUT_OF_RANGE",function($,U,Y){let Z=`The value of "${$}" is out of range.`,J=Y;if(Number.isInteger(Y)&&Math.abs(Y)>4294967296)J=kU(String(Y));else if(typeof Y==="bigint"){if(J=String(Y),Y>BigInt(2)**BigInt(32)||Y<-(BigInt(2)**BigInt(32)))J=kU(J);J+="n"}return Z+=` It must be ${U}. Received ${J}`,Z},RangeError);function G0($,U,Y){if(typeof $==="number"){if(typeof U==="string")throw TypeError('The "string" argument must be of type string. Received type number');return O8($)}return SU($,U,Y)}Object.defineProperty(G0.prototype,"parent",{enumerable:!0,get:function(){if(!G0.isBuffer(this))return;return this.buffer}});Object.defineProperty(G0.prototype,"offset",{enumerable:!0,get:function(){if(!G0.isBuffer(this))return;return this.byteOffset}});G0.poolSize=8192;function SU($,U,Y){if(typeof $==="string")return d7($,U);if(ArrayBuffer.isView($))return c7($);if($==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof $);if(p0($,ArrayBuffer)||$&&p0($.buffer,ArrayBuffer))return P8($,U,Y);if(typeof SharedArrayBuffer<"u"&&(p0($,SharedArrayBuffer)||$&&p0($.buffer,SharedArrayBuffer)))return P8($,U,Y);if(typeof $==="number")throw TypeError('The "value" argument must not be of type number. Received type number');let Z=$.valueOf&&$.valueOf();if(Z!=null&&Z!==$)return G0.from(Z,U,Y);let J=m7($);if(J)return J;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof $[Symbol.toPrimitive]==="function")return G0.from($[Symbol.toPrimitive]("string"),U,Y);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof $)}G0.from=function($,U,Y){return SU($,U,Y)};Object.setPrototypeOf(G0.prototype,Uint8Array.prototype);Object.setPrototypeOf(G0,Uint8Array);function vU($){if(typeof $!=="number")throw TypeError('"size" argument must be of type number');else if($<0)throw RangeError('The value "'+$+'" is invalid for option "size"')}function u7($,U,Y){if(vU($),$<=0)return q2($);if(U!==void 0)return typeof Y==="string"?q2($).fill(U,Y):q2($).fill(U);return q2($)}G0.alloc=function($,U,Y){return u7($,U,Y)};function O8($){return vU($),q2($<0?0:k8($)|0)}G0.allocUnsafe=function($){return O8($)};G0.allocUnsafeSlow=function($){return O8($)};function d7($,U){if(typeof U!=="string"||U==="")U="utf8";if(!G0.isEncoding(U))throw TypeError("Unknown encoding: "+U);let Y=_U($,U)|0,Z=q2(Y),J=Z.write($,U);if(J!==Y)Z=Z.slice(0,J);return Z}function A8($){let U=$.length<0?0:k8($.length)|0,Y=q2(U);for(let Z=0;Z=R8)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+R8.toString(16)+" bytes");return $|0}G0.isBuffer=function($){return $!=null&&$._isBuffer===!0&&$!==G0.prototype};G0.compare=function($,U){if(p0($,Uint8Array))$=G0.from($,$.offset,$.byteLength);if(p0(U,Uint8Array))U=G0.from(U,U.offset,U.byteLength);if(!G0.isBuffer($)||!G0.isBuffer(U))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if($===U)return 0;let Y=$.length,Z=U.length;for(let J=0,G=Math.min(Y,Z);JZ.length){if(!G0.isBuffer(G))G=G0.from(G);G.copy(Z,J)}else Uint8Array.prototype.set.call(Z,G,J);else if(!G0.isBuffer(G))throw TypeError('"list" argument must be an Array of Buffers');else G.copy(Z,J);J+=G.length}return Z};function _U($,U){if(G0.isBuffer($))return $.length;if(ArrayBuffer.isView($)||p0($,ArrayBuffer))return $.byteLength;if(typeof $!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof $);let Y=$.length,Z=arguments.length>2&&arguments[2]===!0;if(!Z&&Y===0)return 0;let J=!1;for(;;)switch(U){case"ascii":case"latin1":case"binary":return Y;case"utf8":case"utf-8":return T8($).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y*2;case"hex":return Y>>>1;case"base64":return cU($).length;default:if(J)return Z?-1:T8($).length;U=(""+U).toLowerCase(),J=!0}}G0.byteLength=_U;function l7($,U,Y){let Z=!1;if(U===void 0||U<0)U=0;if(U>this.length)return"";if(Y===void 0||Y>this.length)Y=this.length;if(Y<=0)return"";if(Y>>>=0,U>>>=0,Y<=U)return"";if(!$)$="utf8";while(!0)switch($){case"hex":return $q(this,U,Y);case"utf8":case"utf-8":return bU(this,U,Y);case"ascii":return t7(this,U,Y);case"latin1":case"binary":return e7(this,U,Y);case"base64":return n7(this,U,Y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Uq(this,U,Y);default:if(Z)throw TypeError("Unknown encoding: "+$);$=($+"").toLowerCase(),Z=!0}}G0.prototype._isBuffer=!0;function P2($,U,Y){let Z=$[U];$[U]=$[Y],$[Y]=Z}G0.prototype.swap16=function(){let $=this.length;if($%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let U=0;U<$;U+=2)P2(this,U,U+1);return this};G0.prototype.swap32=function(){let $=this.length;if($%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let U=0;U<$;U+=4)P2(this,U,U+3),P2(this,U+1,U+2);return this};G0.prototype.swap64=function(){let $=this.length;if($%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let U=0;U<$;U+=8)P2(this,U,U+7),P2(this,U+1,U+6),P2(this,U+2,U+5),P2(this,U+3,U+4);return this};G0.prototype.toString=function(){let $=this.length;if($===0)return"";if(arguments.length===0)return bU(this,0,$);return l7.apply(this,arguments)};G0.prototype.toLocaleString=G0.prototype.toString;G0.prototype.equals=function($){if(!G0.isBuffer($))throw TypeError("Argument must be a Buffer");if(this===$)return!0;return G0.compare(this,$)===0};G0.prototype.inspect=function(){let $="",U=x7;if($=this.toString("hex",0,U).replace(/(.{2})/g,"$1 ").trim(),this.length>U)$+=" ... ";return""};if(TU)G0.prototype[TU]=G0.prototype.inspect;G0.prototype.compare=function($,U,Y,Z,J){if(p0($,Uint8Array))$=G0.from($,$.offset,$.byteLength);if(!G0.isBuffer($))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof $);if(U===void 0)U=0;if(Y===void 0)Y=$?$.length:0;if(Z===void 0)Z=0;if(J===void 0)J=this.length;if(U<0||Y>$.length||Z<0||J>this.length)throw RangeError("out of range index");if(Z>=J&&U>=Y)return 0;if(Z>=J)return-1;if(U>=Y)return 1;if(U>>>=0,Y>>>=0,Z>>>=0,J>>>=0,this===$)return 0;let G=J-Z,X=Y-U,Q=Math.min(G,X),B=this.slice(Z,J),F=$.slice(U,Y);for(let z=0;z2147483647)Y=2147483647;else if(Y<-2147483648)Y=-2147483648;if(Y=+Y,Number.isNaN(Y))Y=J?0:$.length-1;if(Y<0)Y=$.length+Y;if(Y>=$.length)if(J)return-1;else Y=$.length-1;else if(Y<0)if(J)Y=0;else return-1;if(typeof U==="string")U=G0.from(U,Z);if(G0.isBuffer(U)){if(U.length===0)return-1;return CU($,U,Y,Z,J)}else if(typeof U==="number"){if(U=U&255,typeof Uint8Array.prototype.indexOf==="function")if(J)return Uint8Array.prototype.indexOf.call($,U,Y);else return Uint8Array.prototype.lastIndexOf.call($,U,Y);return CU($,[U],Y,Z,J)}throw TypeError("val must be string, number or Buffer")}function CU($,U,Y,Z,J){let G=1,X=$.length,Q=U.length;if(Z!==void 0){if(Z=String(Z).toLowerCase(),Z==="ucs2"||Z==="ucs-2"||Z==="utf16le"||Z==="utf-16le"){if($.length<2||U.length<2)return-1;G=2,X/=2,Q/=2,Y/=2}}function B(z,W){if(G===1)return z[W];else return z.readUInt16BE(W*G)}let F;if(J){let z=-1;for(F=Y;FX)Y=X-Q;for(F=Y;F>=0;F--){let z=!0;for(let W=0;WJ)Z=J;let G=U.length;if(Z>G/2)Z=G/2;let X;for(X=0;X>>0,isFinite(Y)){if(Y=Y>>>0,Z===void 0)Z="utf8"}else Z=Y,Y=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let J=this.length-U;if(Y===void 0||Y>J)Y=J;if($.length>0&&(Y<0||U<0)||U>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!Z)Z="utf8";let G=!1;for(;;)switch(Z){case"hex":return a7(this,$,U,Y);case"utf8":case"utf-8":return p7(this,$,U,Y);case"ascii":case"latin1":case"binary":return i7(this,$,U,Y);case"base64":return r7(this,$,U,Y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return s7(this,$,U,Y);default:if(G)throw TypeError("Unknown encoding: "+Z);Z=(""+Z).toLowerCase(),G=!0}};G0.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function n7($,U,Y){if(U===0&&Y===$.length)return PU($);else return PU($.slice(U,Y))}function bU($,U,Y){Y=Math.min($.length,Y);let Z=[],J=U;while(J239?4:G>223?3:G>191?2:1;if(J+Q<=Y){let B,F,z,W;switch(Q){case 1:if(G<128)X=G;break;case 2:if(B=$[J+1],(B&192)===128){if(W=(G&31)<<6|B&63,W>127)X=W}break;case 3:if(B=$[J+1],F=$[J+2],(B&192)===128&&(F&192)===128){if(W=(G&15)<<12|(B&63)<<6|F&63,W>2047&&(W<55296||W>57343))X=W}break;case 4:if(B=$[J+1],F=$[J+2],z=$[J+3],(B&192)===128&&(F&192)===128&&(z&192)===128){if(W=(G&15)<<18|(B&63)<<12|(F&63)<<6|z&63,W>65535&&W<1114112)X=W}}}if(X===null)X=65533,Q=1;else if(X>65535)X-=65536,Z.push(X>>>10&1023|55296),X=56320|X&1023;Z.push(X),J+=Q}return o7(Z)}var OU=4096;function o7($){let U=$.length;if(U<=OU)return String.fromCharCode.apply(String,$);let Y="",Z=0;while(ZZ)Y=Z;let J="";for(let G=U;GY)$=Y;if(U<0){if(U+=Y,U<0)U=0}else if(U>Y)U=Y;if(U<$)U=$;let Z=this.subarray($,U);return Object.setPrototypeOf(Z,G0.prototype),Z};function E0($,U,Y){if($%1!==0||$<0)throw RangeError("offset is not uint");if($+U>Y)throw RangeError("Trying to access beyond buffer length")}G0.prototype.readUintLE=G0.prototype.readUIntLE=function($,U,Y){if($=$>>>0,U=U>>>0,!Y)E0($,U,this.length);let Z=this[$],J=1,G=0;while(++G>>0,U=U>>>0,!Y)E0($,U,this.length);let Z=this[$+--U],J=1;while(U>0&&(J*=256))Z+=this[$+--U]*J;return Z};G0.prototype.readUint8=G0.prototype.readUInt8=function($,U){if($=$>>>0,!U)E0($,1,this.length);return this[$]};G0.prototype.readUint16LE=G0.prototype.readUInt16LE=function($,U){if($=$>>>0,!U)E0($,2,this.length);return this[$]|this[$+1]<<8};G0.prototype.readUint16BE=G0.prototype.readUInt16BE=function($,U){if($=$>>>0,!U)E0($,2,this.length);return this[$]<<8|this[$+1]};G0.prototype.readUint32LE=G0.prototype.readUInt32LE=function($,U){if($=$>>>0,!U)E0($,4,this.length);return(this[$]|this[$+1]<<8|this[$+2]<<16)+this[$+3]*16777216};G0.prototype.readUint32BE=G0.prototype.readUInt32BE=function($,U){if($=$>>>0,!U)E0($,4,this.length);return this[$]*16777216+(this[$+1]<<16|this[$+2]<<8|this[$+3])};G0.prototype.readBigUInt64LE=z2(function($){$=$>>>0,b2($,"offset");let U=this[$],Y=this[$+7];if(U===void 0||Y===void 0)$1($,this.length-8);let Z=U+this[++$]*256+this[++$]*65536+this[++$]*16777216,J=this[++$]+this[++$]*256+this[++$]*65536+Y*16777216;return BigInt(Z)+(BigInt(J)<>>0,b2($,"offset");let U=this[$],Y=this[$+7];if(U===void 0||Y===void 0)$1($,this.length-8);let Z=U*16777216+this[++$]*65536+this[++$]*256+this[++$],J=this[++$]*16777216+this[++$]*65536+this[++$]*256+Y;return(BigInt(Z)<>>0,U=U>>>0,!Y)E0($,U,this.length);let Z=this[$],J=1,G=0;while(++G=J)Z-=Math.pow(2,8*U);return Z};G0.prototype.readIntBE=function($,U,Y){if($=$>>>0,U=U>>>0,!Y)E0($,U,this.length);let Z=U,J=1,G=this[$+--Z];while(Z>0&&(J*=256))G+=this[$+--Z]*J;if(J*=128,G>=J)G-=Math.pow(2,8*U);return G};G0.prototype.readInt8=function($,U){if($=$>>>0,!U)E0($,1,this.length);if(!(this[$]&128))return this[$];return(255-this[$]+1)*-1};G0.prototype.readInt16LE=function($,U){if($=$>>>0,!U)E0($,2,this.length);let Y=this[$]|this[$+1]<<8;return Y&32768?Y|4294901760:Y};G0.prototype.readInt16BE=function($,U){if($=$>>>0,!U)E0($,2,this.length);let Y=this[$+1]|this[$]<<8;return Y&32768?Y|4294901760:Y};G0.prototype.readInt32LE=function($,U){if($=$>>>0,!U)E0($,4,this.length);return this[$]|this[$+1]<<8|this[$+2]<<16|this[$+3]<<24};G0.prototype.readInt32BE=function($,U){if($=$>>>0,!U)E0($,4,this.length);return this[$]<<24|this[$+1]<<16|this[$+2]<<8|this[$+3]};G0.prototype.readBigInt64LE=z2(function($){$=$>>>0,b2($,"offset");let U=this[$],Y=this[$+7];if(U===void 0||Y===void 0)$1($,this.length-8);let Z=this[$+4]+this[$+5]*256+this[$+6]*65536+(Y<<24);return(BigInt(Z)<>>0,b2($,"offset");let U=this[$],Y=this[$+7];if(U===void 0||Y===void 0)$1($,this.length-8);let Z=(U<<24)+this[++$]*65536+this[++$]*256+this[++$];return(BigInt(Z)<>>0,!U)E0($,4,this.length);return T1(this,$,!0,23,4)};G0.prototype.readFloatBE=function($,U){if($=$>>>0,!U)E0($,4,this.length);return T1(this,$,!1,23,4)};G0.prototype.readDoubleLE=function($,U){if($=$>>>0,!U)E0($,8,this.length);return T1(this,$,!0,52,8)};G0.prototype.readDoubleBE=function($,U){if($=$>>>0,!U)E0($,8,this.length);return T1(this,$,!1,52,8)};function b0($,U,Y,Z,J,G){if(!G0.isBuffer($))throw TypeError('"buffer" argument must be a Buffer instance');if(U>J||U$.length)throw RangeError("Index out of range")}G0.prototype.writeUintLE=G0.prototype.writeUIntLE=function($,U,Y,Z){if($=+$,U=U>>>0,Y=Y>>>0,!Z){let X=Math.pow(2,8*Y)-1;b0(this,$,U,Y,X,0)}let J=1,G=0;this[U]=$&255;while(++G>>0,Y=Y>>>0,!Z){let X=Math.pow(2,8*Y)-1;b0(this,$,U,Y,X,0)}let J=Y-1,G=1;this[U+J]=$&255;while(--J>=0&&(G*=256))this[U+J]=$/G&255;return U+Y};G0.prototype.writeUint8=G0.prototype.writeUInt8=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,1,255,0);return this[U]=$&255,U+1};G0.prototype.writeUint16LE=G0.prototype.writeUInt16LE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,2,65535,0);return this[U]=$&255,this[U+1]=$>>>8,U+2};G0.prototype.writeUint16BE=G0.prototype.writeUInt16BE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,2,65535,0);return this[U]=$>>>8,this[U+1]=$&255,U+2};G0.prototype.writeUint32LE=G0.prototype.writeUInt32LE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,4,4294967295,0);return this[U+3]=$>>>24,this[U+2]=$>>>16,this[U+1]=$>>>8,this[U]=$&255,U+4};G0.prototype.writeUint32BE=G0.prototype.writeUInt32BE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,4,4294967295,0);return this[U]=$>>>24,this[U+1]=$>>>16,this[U+2]=$>>>8,this[U+3]=$&255,U+4};function gU($,U,Y,Z,J){dU(U,Z,J,$,Y,7);let G=Number(U&BigInt(4294967295));$[Y++]=G,G=G>>8,$[Y++]=G,G=G>>8,$[Y++]=G,G=G>>8,$[Y++]=G;let X=Number(U>>BigInt(32)&BigInt(4294967295));return $[Y++]=X,X=X>>8,$[Y++]=X,X=X>>8,$[Y++]=X,X=X>>8,$[Y++]=X,Y}function xU($,U,Y,Z,J){dU(U,Z,J,$,Y,7);let G=Number(U&BigInt(4294967295));$[Y+7]=G,G=G>>8,$[Y+6]=G,G=G>>8,$[Y+5]=G,G=G>>8,$[Y+4]=G;let X=Number(U>>BigInt(32)&BigInt(4294967295));return $[Y+3]=X,X=X>>8,$[Y+2]=X,X=X>>8,$[Y+1]=X,X=X>>8,$[Y]=X,Y+8}G0.prototype.writeBigUInt64LE=z2(function($,U=0){return gU(this,$,U,BigInt(0),BigInt("0xffffffffffffffff"))});G0.prototype.writeBigUInt64BE=z2(function($,U=0){return xU(this,$,U,BigInt(0),BigInt("0xffffffffffffffff"))});G0.prototype.writeIntLE=function($,U,Y,Z){if($=+$,U=U>>>0,!Z){let Q=Math.pow(2,8*Y-1);b0(this,$,U,Y,Q-1,-Q)}let J=0,G=1,X=0;this[U]=$&255;while(++J>0)-X&255}return U+Y};G0.prototype.writeIntBE=function($,U,Y,Z){if($=+$,U=U>>>0,!Z){let Q=Math.pow(2,8*Y-1);b0(this,$,U,Y,Q-1,-Q)}let J=Y-1,G=1,X=0;this[U+J]=$&255;while(--J>=0&&(G*=256)){if($<0&&X===0&&this[U+J+1]!==0)X=1;this[U+J]=($/G>>0)-X&255}return U+Y};G0.prototype.writeInt8=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,1,127,-128);if($<0)$=255+$+1;return this[U]=$&255,U+1};G0.prototype.writeInt16LE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,2,32767,-32768);return this[U]=$&255,this[U+1]=$>>>8,U+2};G0.prototype.writeInt16BE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,2,32767,-32768);return this[U]=$>>>8,this[U+1]=$&255,U+2};G0.prototype.writeInt32LE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,4,2147483647,-2147483648);return this[U]=$&255,this[U+1]=$>>>8,this[U+2]=$>>>16,this[U+3]=$>>>24,U+4};G0.prototype.writeInt32BE=function($,U,Y){if($=+$,U=U>>>0,!Y)b0(this,$,U,4,2147483647,-2147483648);if($<0)$=4294967295+$+1;return this[U]=$>>>24,this[U+1]=$>>>16,this[U+2]=$>>>8,this[U+3]=$&255,U+4};G0.prototype.writeBigInt64LE=z2(function($,U=0){return gU(this,$,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});G0.prototype.writeBigInt64BE=z2(function($,U=0){return xU(this,$,U,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function fU($,U,Y,Z,J,G){if(Y+Z>$.length)throw RangeError("Index out of range");if(Y<0)throw RangeError("Index out of range")}function hU($,U,Y,Z,J){if(U=+U,Y=Y>>>0,!J)fU($,U,Y,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return EU($,U,Y,Z,23,4),Y+4}G0.prototype.writeFloatLE=function($,U,Y){return hU(this,$,U,!0,Y)};G0.prototype.writeFloatBE=function($,U,Y){return hU(this,$,U,!1,Y)};function uU($,U,Y,Z,J){if(U=+U,Y=Y>>>0,!J)fU($,U,Y,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return EU($,U,Y,Z,52,8),Y+8}G0.prototype.writeDoubleLE=function($,U,Y){return uU(this,$,U,!0,Y)};G0.prototype.writeDoubleBE=function($,U,Y){return uU(this,$,U,!1,Y)};G0.prototype.copy=function($,U,Y,Z){if(!G0.isBuffer($))throw TypeError("argument should be a Buffer");if(!Y)Y=0;if(!Z&&Z!==0)Z=this.length;if(U>=$.length)U=$.length;if(!U)U=0;if(Z>0&&Z=this.length)throw RangeError("Index out of range");if(Z<0)throw RangeError("sourceEnd out of bounds");if(Z>this.length)Z=this.length;if($.length-U>>0,Y=Y===void 0?this.length:Y>>>0,!$)$=0;let J;if(typeof $==="number")for(J=U;J=Z+4;Y-=3)U=`_${$.slice(Y-3,Y)}${U}`;return`${$.slice(0,Y)}${U}`}function Yq($,U,Y){if(b2(U,"offset"),$[U]===void 0||$[U+Y]===void 0)$1(U,$.length-(Y+1))}function dU($,U,Y,Z,J,G){if($>Y||$3)if(U===0||U===BigInt(0))Q=`>= 0${X} and < 2${X} ** ${(G+1)*8}${X}`;else Q=`>= -(2${X} ** ${(G+1)*8-1}${X}) and < 2 ** ${(G+1)*8-1}${X}`;else Q=`>= ${U}${X} and <= ${Y}${X}`;throw new D8("value",Q,$)}Yq(Z,J,G)}function b2($,U){if(typeof $!=="number")throw new h7(U,"number",$)}function $1($,U,Y){if(Math.floor($)!==$)throw b2($,Y),new D8(Y||"offset","an integer",$);if(U<0)throw new f7;throw new D8(Y||"offset",`>= ${Y?1:0} and <= ${U}`,$)}var Zq=/[^+/0-9A-Za-z-_]/g;function Qq($){if($=$.split("=")[0],$=$.trim().replace(Zq,""),$.length<2)return"";while($.length%4!==0)$=$+"=";return $}function T8($,U){U=U||1/0;let Y,Z=$.length,J=null,G=[];for(let X=0;X55295&&Y<57344){if(!J){if(Y>56319){if((U-=3)>-1)G.push(239,191,189);continue}else if(X+1===Z){if((U-=3)>-1)G.push(239,191,189);continue}J=Y;continue}if(Y<56320){if((U-=3)>-1)G.push(239,191,189);J=Y;continue}Y=(J-55296<<10|Y-56320)+65536}else if(J){if((U-=3)>-1)G.push(239,191,189)}if(J=null,Y<128){if((U-=1)<0)break;G.push(Y)}else if(Y<2048){if((U-=2)<0)break;G.push(Y>>6|192,Y&63|128)}else if(Y<65536){if((U-=3)<0)break;G.push(Y>>12|224,Y>>6&63|128,Y&63|128)}else if(Y<1114112){if((U-=4)<0)break;G.push(Y>>18|240,Y>>12&63|128,Y>>6&63|128,Y&63|128)}else throw Error("Invalid code point")}return G}function Jq($){let U=[];for(let Y=0;Y<$.length;++Y)U.push($.charCodeAt(Y)&255);return U}function Gq($,U){let Y,Z,J,G=[];for(let X=0;X<$.length;++X){if((U-=2)<0)break;Y=$.charCodeAt(X),Z=Y>>8,J=Y%256,G.push(J),G.push(Z)}return G}function cU($){return y7(Qq($))}function C1($,U,Y,Z){let J;for(J=0;J=U.length||J>=$.length)break;U[J+Y]=$[J]}return J}function p0($,U){return $ instanceof U||$!=null&&$.constructor!=null&&$.constructor.name!=null&&$.constructor.name===U.name}var Kq=function(){let $=Array(256);for(let U=0;U<16;++U){let Y=U*16;for(let Z=0;Z<16;++Z)$[Y+Z]="0123456789abcdef"[U]+"0123456789abcdef"[Z]}return $}();function z2($){return typeof BigInt>"u"?qq:$}function qq(){throw Error("BigInt not supported")}function E8($){return()=>{throw Error($+" is not implemented for node:buffer browser polyfill")}}var yB=E8("resolveObjectURL"),bB=E8("isUtf8");var gB=E8("transcode");var OB=C7(iU(),1);var FU={};S7(FU,{unsignedDecimalNumber:()=>W1,universalMeasureValue:()=>H1,uniqueUuid:()=>tQ,uniqueNumericIdCreator:()=>N1,uniqueId:()=>R1,uCharHexNumber:()=>D9,twipsMeasureValue:()=>T0,standardizeData:()=>mJ,signedTwipsMeasureValue:()=>e0,signedHpsMeasureValue:()=>LX,shortHexNumber:()=>DQ,sectionPageSizeDefaults:()=>h1,sectionMarginDefaults:()=>F2,positiveUniversalMeasureValue:()=>r9,pointMeasureValue:()=>CQ,percentageValue:()=>PQ,patchDocument:()=>AB,patchDetector:()=>TB,measurementOrPercentValue:()=>s9,longHexNumber:()=>BX,hpsMeasureValue:()=>AQ,hexColorValue:()=>S2,hashedId:()=>A9,encodeUtf8:()=>X1,eighthPointMeasureValue:()=>TQ,docPropertiesUniqueNumericIdGen:()=>nQ,decimalNumber:()=>S0,dateTimeValue:()=>OQ,createWrapTopAndBottom:()=>bJ,createWrapTight:()=>yJ,createWrapSquare:()=>_J,createWrapNone:()=>C9,createVerticalPosition:()=>JJ,createVerticalAlign:()=>f$,createUnderline:()=>mQ,createTransformation:()=>B$,createTableWidthElement:()=>M1,createTableRowHeight:()=>EK,createTableLook:()=>CK,createTableLayout:()=>PK,createTableFloatProperties:()=>AK,createTabStopItem:()=>PG,createTabStop:()=>TG,createStringElement:()=>u2,createSpacing:()=>AG,createSimplePos:()=>UJ,createShading:()=>j1,createSectionType:()=>nK,createRunFonts:()=>g1,createParagraphStyle:()=>K1,createPageSize:()=>rK,createPageNumberType:()=>iK,createPageMargin:()=>pK,createOutlineLevel:()=>yG,createMathSuperScriptProperties:()=>iG,createMathSuperScriptElement:()=>n2,createMathSubSuperScriptProperties:()=>oG,createMathSubScriptProperties:()=>sG,createMathSubScriptElement:()=>s2,createMathPreSubSuperScriptProperties:()=>eG,createMathNAryProperties:()=>T$,createMathLimitLocation:()=>cG,createMathBase:()=>y0,createMathAccentCharacter:()=>dG,createLineNumberType:()=>aK,createIndent:()=>EQ,createHorizontalPosition:()=>QJ,createHeaderFooterReference:()=>f1,createFrameProperties:()=>xG,createEmphasisMark:()=>Y$,createDotEmphasisMark:()=>HX,createDocumentGrid:()=>lK,createColumns:()=>mK,createBorderElement:()=>N0,createBodyProperties:()=>KJ,createAlignment:()=>n9,convertToXmlComponent:()=>U8,convertMillimetersToTwip:()=>bX,convertInchesToTwip:()=>d0,concreteNumUniqueNumericIdGen:()=>sQ,bookmarkUniqueNumericIdGen:()=>oQ,abstractNumUniqueNumericIdGen:()=>rQ,YearShort:()=>qG,YearLong:()=>BG,XmlComponent:()=>o,XmlAttributeComponent:()=>I0,WpsShapeRun:()=>aJ,WpgGroupRun:()=>pJ,WidthType:()=>l1,WORKAROUND4:()=>HV,WORKAROUND3:()=>VX,WORKAROUND2:()=>lV,VerticalPositionRelativeFrom:()=>$J,VerticalPositionAlign:()=>IX,VerticalMergeType:()=>d$,VerticalMergeRevisionType:()=>NV,VerticalMerge:()=>a1,VerticalAnchor:()=>GJ,VerticalAlignTable:()=>HK,VerticalAlignSection:()=>jK,VerticalAlign:()=>RV,UnderlineType:()=>Z$,ThematicBreak:()=>t9,Textbox:()=>G7,TextWrappingType:()=>G1,TextWrappingSide:()=>vJ,TextRun:()=>p2,TextEffect:()=>NX,TextDirection:()=>PV,TableRowPropertiesChange:()=>l$,TableRowProperties:()=>M8,TableRow:()=>SK,TableProperties:()=>L8,TableOfContents:()=>e5,TableLayoutType:()=>SV,TableCellBorders:()=>h$,TableCell:()=>V8,TableBorders:()=>B8,TableAnchorType:()=>TV,Table:()=>kK,TabStopType:()=>O9,TabStopPosition:()=>ZV,Tab:()=>w$,TDirection:()=>c$,SymbolRun:()=>G$,Styles:()=>B1,StyleLevel:()=>$7,StyleForParagraph:()=>y2,StyleForCharacter:()=>D2,StringValueElement:()=>Y2,StringEnumValueElement:()=>kQ,StringContainer:()=>L2,SpaceType:()=>g0,SoftHyphen:()=>JG,SimpleMailMergeField:()=>nJ,SimpleField:()=>J8,ShadingType:()=>WX,SequentialIdentifier:()=>rJ,Separator:()=>IG,SectionType:()=>dV,SectionPropertiesChange:()=>i$,SectionProperties:()=>I8,RunPropertiesDefaults:()=>XU,RunPropertiesChange:()=>J$,RunProperties:()=>J2,Run:()=>C0,RelativeVerticalPosition:()=>OV,RelativeHorizontalPosition:()=>CV,PrettifyType:()=>X7,PositionalTabRelativeTo:()=>eX,PositionalTabLeader:()=>$V,PositionalTabAlignment:()=>tX,PositionalTab:()=>FG,PatchType:()=>y9,ParagraphRunProperties:()=>Q$,ParagraphPropertiesDefaults:()=>qU,ParagraphPropertiesChange:()=>D$,ParagraphProperties:()=>Z2,Paragraph:()=>h0,PageTextDirectionType:()=>uV,PageTextDirection:()=>p$,PageReference:()=>gG,PageOrientation:()=>i1,PageNumberSeparator:()=>hV,PageNumberElement:()=>WG,PageNumber:()=>N2,PageBreakBefore:()=>H$,PageBreak:()=>RG,PageBorders:()=>a$,PageBorderZOrder:()=>fV,PageBorderOffsetFrom:()=>xV,PageBorderDisplay:()=>gV,Packer:()=>qB,OverlapType:()=>kV,OnOffElement:()=>X0,Numbering:()=>JU,NumberedItemReferenceFormat:()=>vG,NumberedItemReference:()=>_G,NumberValueElement:()=>k2,NumberProperties:()=>V1,NumberFormat:()=>wX,NoBreakHyphen:()=>QG,NextAttributeComponent:()=>n1,MonthShort:()=>KG,MonthLong:()=>VG,Media:()=>w8,MathSuperScript:()=>rG,MathSum:()=>mG,MathSubSuperScript:()=>tG,MathSubScript:()=>nG,MathSquareBrackets:()=>GK,MathRun:()=>hG,MathRoundBrackets:()=>JK,MathRadicalProperties:()=>O$,MathRadical:()=>ZK,MathPreSubSuperScript:()=>$K,MathNumerator:()=>P$,MathLimitUpper:()=>aG,MathLimitLower:()=>pG,MathLimit:()=>q8,MathIntegral:()=>lG,MathFunctionProperties:()=>E$,MathFunctionName:()=>k$,MathFunction:()=>QK,MathFraction:()=>uG,MathDenominator:()=>A$,MathDegree:()=>C$,MathCurlyBrackets:()=>KK,MathAngledBrackets:()=>qK,Math:()=>IV,LineRuleType:()=>v2,LineNumberRestartFormat:()=>bV,LevelSuffix:()=>aV,LevelOverride:()=>QU,LevelFormat:()=>n0,LevelForOverride:()=>F5,LevelBase:()=>W8,Level:()=>ZU,LeaderType:()=>YV,LastRenderedPageBreak:()=>jG,InternalHyperlink:()=>j$,InsertedTextRun:()=>BK,InsertedTableRow:()=>v$,InsertedTableCell:()=>y$,InitializableXmlComponent:()=>Y8,ImportedXmlComponent:()=>p9,ImportedRootElementAttributes:()=>i9,ImageRun:()=>lJ,IgnoreIfEmptyXmlComponent:()=>Q2,HyperlinkType:()=>QV,HpsMeasureElement:()=>q1,HorizontalPositionRelativeFrom:()=>eQ,HorizontalPositionAlign:()=>MX,HighlightColor:()=>RX,HeightRule:()=>_V,HeadingLevel:()=>UV,HeaderWrapper:()=>YU,HeaderFooterType:()=>S9,HeaderFooterReferenceType:()=>E2,Header:()=>U7,GridSpan:()=>u$,FrameWrap:()=>MV,FrameAnchorType:()=>LV,FootnoteReferenceRun:()=>Z7,FootnoteReferenceElement:()=>MG,FootnoteReference:()=>IU,FooterWrapper:()=>$U,Footer:()=>Y7,FootNotes:()=>UU,FootNoteReferenceRunAttributes:()=>MU,FileChild:()=>r2,File:()=>o5,ExternalHyperlink:()=>K8,Endnotes:()=>e$,EndnoteReferenceRunAttributes:()=>wU,EndnoteReferenceRun:()=>Q7,EndnoteReference:()=>I$,EndnoteIdReference:()=>WU,EmptyElement:()=>k0,EmphasisMarkType:()=>U$,EMPTY_OBJECT:()=>tZ,DropCapType:()=>BV,Drawing:()=>D1,DocumentGridType:()=>yV,DocumentDefaults:()=>VU,DocumentBackgroundAttributes:()=>s$,DocumentBackground:()=>n$,DocumentAttributes:()=>o2,DocumentAttributeNamespaces:()=>p1,Document:()=>o5,DeletedTextRun:()=>wK,DeletedTableRow:()=>_$,DeletedTableCell:()=>b$,DayShort:()=>GG,DayLong:()=>XG,ContinuationSeparator:()=>wG,ConcreteNumbering:()=>s1,ConcreteHyperlink:()=>_2,Comments:()=>M$,CommentReference:()=>ZG,CommentRangeStart:()=>UG,CommentRangeEnd:()=>YG,Comment:()=>L$,ColumnBreak:()=>DG,Column:()=>tK,CheckBoxUtil:()=>HU,CheckBoxSymbolElement:()=>L1,CheckBox:()=>J7,CharacterSet:()=>GV,CellMergeAttributes:()=>g$,CellMerge:()=>x$,CarriageReturn:()=>HG,BuilderElement:()=>B0,BorderStyle:()=>Q8,Border:()=>o9,BookmarkStart:()=>F$,BookmarkEnd:()=>N$,Bookmark:()=>z$,Body:()=>r$,BaseXmlComponent:()=>m2,Attributes:()=>O0,AnnotationReference:()=>LG,AlignmentType:()=>m0,AbstractNumbering:()=>r1});var{defineProperty:Bq,defineProperties:Lq,getOwnPropertyDescriptors:Mq,getOwnPropertySymbols:m1}=Object,sZ=Object.prototype.hasOwnProperty,nZ=Object.prototype.propertyIsEnumerable,z9=($,U,Y)=>(U in $)?Bq($,U,{enumerable:!0,configurable:!0,writable:!0,value:Y}):$[U]=Y,W0=($,U)=>{for(var Y in U||(U={}))if(sZ.call(U,Y))z9($,Y,U[Y]);if(m1){for(var Y of m1(U))if(nZ.call(U,Y))z9($,Y,U[Y])}return $},R0=($,U)=>Lq($,Mq(U)),oZ=($,U)=>{var Y={};for(var Z in $)if(sZ.call($,Z)&&U.indexOf(Z)<0)Y[Z]=$[Z];if($!=null&&m1){for(var Z of m1($))if(U.indexOf(Z)<0&&nZ.call($,Z))Y[Z]=$[Z]}return Y},Y0=($,U,Y)=>z9($,typeof U!=="symbol"?U+"":U,Y),b9=($,U,Y)=>{return new Promise((Z,J)=>{var G=(B)=>{try{Q(Y.next(B))}catch(F){J(F)}},X=(B)=>{try{Q(Y.throw(B))}catch(F){J(F)}},Q=(B)=>B.done?Z(B.value):Promise.resolve(B.value).then(G,X);Q((Y=Y.apply($,U)).next())})};class m2{constructor($){Y0(this,"rootKey"),this.rootKey=$}}var tZ=Object.seal({});class o extends m2{constructor($){super($);Y0(this,"root"),this.root=[]}prepForXml($){var U;$.stack.push(this);let Y=this.root.map((Z)=>{if(Z instanceof m2)return Z.prepForXml($);return Z}).filter((Z)=>Z!==void 0);return $.stack.pop(),{[this.rootKey]:Y.length?Y.length===1&&((U=Y[0])==null?void 0:U._attr)?Y[0]:Y:tZ}}addChildElement($){return this.root.push($),this}}class Q2 extends o{constructor($,U){super($);Y0(this,"includeIfEmpty"),this.includeIfEmpty=U}prepForXml($){let U=super.prepForXml($);if(this.includeIfEmpty)return U;if(U&&(typeof U[this.rootKey]!=="object"||Object.keys(U[this.rootKey]).length))return U;return}}class I0 extends m2{constructor($){super("_attr");Y0(this,"xmlKeys"),this.root=$}prepForXml($){let U={};return Object.entries(this.root).forEach(([Y,Z])=>{if(Z!==void 0){let J=this.xmlKeys&&this.xmlKeys[Y]||Y;U[J]=Z}}),{_attr:U}}}class n1 extends m2{constructor($){super("_attr");this.root=$}prepForXml($){return{_attr:Object.values(this.root).filter(({value:Y})=>Y!==void 0).reduce((Y,{key:Z,value:J})=>R0(W0({},Y),{[Z]:J}),{})}}}class O0 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val",color:"w:color",fill:"w:fill",space:"w:space",sz:"w:sz",type:"w:type",rsidR:"w:rsidR",rsidRPr:"w:rsidRPr",rsidSect:"w:rsidSect",w:"w:w",h:"w:h",top:"w:top",right:"w:right",bottom:"w:bottom",left:"w:left",header:"w:header",footer:"w:footer",gutter:"w:gutter",linePitch:"w:linePitch",pos:"w:pos"})}}var c0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function g9($){return $&&$.__esModule&&Object.prototype.hasOwnProperty.call($,"default")?$.default:$}var _8={},k1={exports:{}},rU;function x9(){if(rU)return k1.exports;rU=1;var $=typeof Reflect==="object"?Reflect:null,U=$&&typeof $.apply==="function"?$.apply:function(A,y,g){return Function.prototype.apply.call(A,y,g)},Y;if($&&typeof $.ownKeys==="function")Y=$.ownKeys;else if(Object.getOwnPropertySymbols)Y=function(A){return Object.getOwnPropertyNames(A).concat(Object.getOwnPropertySymbols(A))};else Y=function(A){return Object.getOwnPropertyNames(A)};function Z(L){if(console&&console.warn)console.warn(L)}var J=Number.isNaN||function(A){return A!==A};function G(){G.init.call(this)}k1.exports=G,k1.exports.once=V,G.EventEmitter=G,G.prototype._events=void 0,G.prototype._eventsCount=0,G.prototype._maxListeners=void 0;var X=10;function Q(L){if(typeof L!=="function")throw TypeError('The "listener" argument must be of type Function. Received type '+typeof L)}Object.defineProperty(G,"defaultMaxListeners",{enumerable:!0,get:function(){return X},set:function(L){if(typeof L!=="number"||L<0||J(L))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+L+".");X=L}}),G.init=function(){if(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)this._events=Object.create(null),this._eventsCount=0;this._maxListeners=this._maxListeners||void 0},G.prototype.setMaxListeners=function(A){if(typeof A!=="number"||A<0||J(A))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+A+".");return this._maxListeners=A,this};function B(L){if(L._maxListeners===void 0)return G.defaultMaxListeners;return L._maxListeners}G.prototype.getMaxListeners=function(){return B(this)},G.prototype.emit=function(A){var y=[];for(var g=1;g0)s=y[0];if(s instanceof Error)throw s;var V0=Error("Unhandled error."+(s?" ("+s.message+")":""));throw V0.context=s,V0}var S=E[A];if(S===void 0)return!1;if(typeof S==="function")U(S,this,y);else{var h=S.length,N=C(S,h);for(var g=0;g0&&s.length>d&&!s.warned){s.warned=!0;var V0=Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(A)+" listeners added. Use emitter.setMaxListeners() to increase limit");V0.name="MaxListenersExceededWarning",V0.emitter=L,V0.type=A,V0.count=s.length,Z(V0)}}return L}G.prototype.addListener=function(A,y){return F(this,A,y,!1)},G.prototype.on=G.prototype.addListener,G.prototype.prependListener=function(A,y){return F(this,A,y,!0)};function z(){if(!this.fired){if(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function W(L,A,y){var g={fired:!1,wrapFn:void 0,target:L,type:A,listener:y},d=z.bind(g);return d.listener=y,g.wrapFn=d,d}G.prototype.once=function(A,y){return Q(y),this.on(A,W(this,A,y)),this},G.prototype.prependOnceListener=function(A,y){return Q(y),this.prependListener(A,W(this,A,y)),this},G.prototype.removeListener=function(A,y){var g,d,E,s,V0;if(Q(y),d=this._events,d===void 0)return this;if(g=d[A],g===void 0)return this;if(g===y||g.listener===y){if(--this._eventsCount===0)this._events=Object.create(null);else if(delete d[A],d.removeListener)this.emit("removeListener",A,g.listener||y)}else if(typeof g!=="function"){E=-1;for(s=g.length-1;s>=0;s--)if(g[s]===y||g[s].listener===y){V0=g[s].listener,E=s;break}if(E<0)return this;if(E===0)g.shift();else H(g,E);if(g.length===1)d[A]=g[0];if(d.removeListener!==void 0)this.emit("removeListener",A,V0||y)}return this},G.prototype.off=G.prototype.removeListener,G.prototype.removeAllListeners=function(A){var y,g,d;if(g=this._events,g===void 0)return this;if(g.removeListener===void 0){if(arguments.length===0)this._events=Object.create(null),this._eventsCount=0;else if(g[A]!==void 0)if(--this._eventsCount===0)this._events=Object.create(null);else delete g[A];return this}if(arguments.length===0){var E=Object.keys(g),s;for(d=0;d=0;d--)this.removeListener(A,y[d]);return this};function k(L,A,y){var g=L._events;if(g===void 0)return[];var d=g[A];if(d===void 0)return[];if(typeof d==="function")return y?[d.listener||d]:[d];return y?O(d):C(d,d.length)}G.prototype.listeners=function(A){return k(this,A,!0)},G.prototype.rawListeners=function(A){return k(this,A,!1)},G.listenerCount=function(L,A){if(typeof L.listenerCount==="function")return L.listenerCount(A);else return D.call(L,A)},G.prototype.listenerCount=D;function D(L){var A=this._events;if(A!==void 0){var y=A[L];if(typeof y==="function")return 1;else if(y!==void 0)return y.length}return 0}G.prototype.eventNames=function(){return this._eventsCount>0?Y(this._events):[]};function C(L,A){var y=Array(A);for(var g=0;g1)for(var Y=1;Y0)throw Error("Invalid string. Length must be a multiple of 4");var H=D.indexOf("=");if(H===-1)H=C;var O=H===C?0:4-H%4;return[H,O]}function Q(D){var C=X(D),H=C[0],O=C[1];return(H+O)*3/4-O}function B(D,C,H){return(C+H)*3/4-H}function F(D){var C,H=X(D),O=H[0],V=H[1],j=new Y(B(D,O,V)),M=0,L=V>0?O-4:O,A;for(A=0;A>16&255,j[M++]=C>>8&255,j[M++]=C&255;if(V===2)C=U[D.charCodeAt(A)]<<2|U[D.charCodeAt(A+1)]>>4,j[M++]=C&255;if(V===1)C=U[D.charCodeAt(A)]<<10|U[D.charCodeAt(A+1)]<<4|U[D.charCodeAt(A+2)]>>2,j[M++]=C>>8&255,j[M++]=C&255;return j}function z(D){return $[D>>18&63]+$[D>>12&63]+$[D>>6&63]+$[D&63]}function W(D,C,H){var O,V=[];for(var j=C;jL?L:M+j));if(O===1)C=D[H-1],V.push($[C>>2]+$[C<<4&63]+"==");else if(O===2)C=(D[H-2]<<8)+D[H-1],V.push($[C>>10]+$[C>>4&63]+$[C<<2&63]+"=");return V.join("")}return U1}var S1={},tU;function zq(){if(tU)return S1;return tU=1,S1.read=function($,U,Y,Z,J){var G,X,Q=J*8-Z-1,B=(1<>1,z=-7,W=Y?J-1:0,k=Y?-1:1,D=$[U+W];W+=k,G=D&(1<<-z)-1,D>>=-z,z+=Q;for(;z>0;G=G*256+$[U+W],W+=k,z-=8);X=G&(1<<-z)-1,G>>=-z,z+=Z;for(;z>0;X=X*256+$[U+W],W+=k,z-=8);if(G===0)G=1-F;else if(G===B)return X?NaN:(D?-1:1)*(1/0);else X=X+Math.pow(2,Z),G=G-F;return(D?-1:1)*X*Math.pow(2,G-Z)},S1.write=function($,U,Y,Z,J,G){var X,Q,B,F=G*8-J-1,z=(1<>1,k=J===23?Math.pow(2,-24)-Math.pow(2,-77):0,D=Z?0:G-1,C=Z?1:-1,H=U<0||U===0&&1/U<0?1:0;if(U=Math.abs(U),isNaN(U)||U===1/0)Q=isNaN(U)?1:0,X=z;else{if(X=Math.floor(Math.log(U)/Math.LN2),U*(B=Math.pow(2,-X))<1)X--,B*=2;if(X+W>=1)U+=k/B;else U+=k*Math.pow(2,1-W);if(U*B>=2)X++,B/=2;if(X+W>=z)Q=0,X=z;else if(X+W>=1)Q=(U*B-1)*Math.pow(2,J),X=X+W;else Q=U*Math.pow(2,W-1)*Math.pow(2,J),X=0}for(;J>=8;$[Y+D]=Q&255,D+=C,Q/=256,J-=8);X=X<0;$[Y+D]=X&255,D+=C,X/=256,F-=8);$[Y+D-C]|=H*128},S1}var eU;function o1(){if(eU)return b8;return eU=1,function($){var U=jq(),Y=zq(),Z=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;$.Buffer=Q,$.SlowBuffer=j,$.INSPECT_MAX_BYTES=50;var J=2147483647;if($.kMaxLength=J,Q.TYPED_ARRAY_SUPPORT=G(),!Q.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function G(){try{var T=new Uint8Array(1),K={foo:function(){return 42}};return Object.setPrototypeOf(K,Uint8Array.prototype),Object.setPrototypeOf(T,K),T.foo()===42}catch(q){return!1}}Object.defineProperty(Q.prototype,"parent",{enumerable:!0,get:function(){if(!Q.isBuffer(this))return;return this.buffer}}),Object.defineProperty(Q.prototype,"offset",{enumerable:!0,get:function(){if(!Q.isBuffer(this))return;return this.byteOffset}});function X(T){if(T>J)throw RangeError('The value "'+T+'" is invalid for option "size"');var K=new Uint8Array(T);return Object.setPrototypeOf(K,Q.prototype),K}function Q(T,K,q){if(typeof T==="number"){if(typeof K==="string")throw TypeError('The "string" argument must be of type string. Received type number');return W(T)}return B(T,K,q)}Q.poolSize=8192;function B(T,K,q){if(typeof T==="string")return k(T,K);if(ArrayBuffer.isView(T))return C(T);if(T==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T);if(e(T,ArrayBuffer)||T&&e(T.buffer,ArrayBuffer))return H(T,K,q);if(typeof SharedArrayBuffer<"u"&&(e(T,SharedArrayBuffer)||T&&e(T.buffer,SharedArrayBuffer)))return H(T,K,q);if(typeof T==="number")throw TypeError('The "value" argument must not be of type number. Received type number');var w=T.valueOf&&T.valueOf();if(w!=null&&w!==T)return Q.from(w,K,q);var x=O(T);if(x)return x;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof T[Symbol.toPrimitive]==="function")return Q.from(T[Symbol.toPrimitive]("string"),K,q);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof T)}Q.from=function(T,K,q){return B(T,K,q)},Object.setPrototypeOf(Q.prototype,Uint8Array.prototype),Object.setPrototypeOf(Q,Uint8Array);function F(T){if(typeof T!=="number")throw TypeError('"size" argument must be of type number');else if(T<0)throw RangeError('The value "'+T+'" is invalid for option "size"')}function z(T,K,q){if(F(T),T<=0)return X(T);if(K!==void 0)return typeof q==="string"?X(T).fill(K,q):X(T).fill(K);return X(T)}Q.alloc=function(T,K,q){return z(T,K,q)};function W(T){return F(T),X(T<0?0:V(T)|0)}Q.allocUnsafe=function(T){return W(T)},Q.allocUnsafeSlow=function(T){return W(T)};function k(T,K){if(typeof K!=="string"||K==="")K="utf8";if(!Q.isEncoding(K))throw TypeError("Unknown encoding: "+K);var q=M(T,K)|0,w=X(q),x=w.write(T,K);if(x!==q)w=w.slice(0,x);return w}function D(T){var K=T.length<0?0:V(T.length)|0,q=X(K);for(var w=0;w=J)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+J.toString(16)+" bytes");return T|0}function j(T){if(+T!=T)T=0;return Q.alloc(+T)}Q.isBuffer=function(K){return K!=null&&K._isBuffer===!0&&K!==Q.prototype},Q.compare=function(K,q){if(e(K,Uint8Array))K=Q.from(K,K.offset,K.byteLength);if(e(q,Uint8Array))q=Q.from(q,q.offset,q.byteLength);if(!Q.isBuffer(K)||!Q.isBuffer(q))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(K===q)return 0;var w=K.length,x=q.length;for(var l=0,u=Math.min(w,x);lx.length)Q.from(u).copy(x,l);else Uint8Array.prototype.set.call(x,u,l);else if(!Q.isBuffer(u))throw TypeError('"list" argument must be an Array of Buffers');else u.copy(x,l);l+=u.length}return x};function M(T,K){if(Q.isBuffer(T))return T.length;if(ArrayBuffer.isView(T)||e(T,ArrayBuffer))return T.byteLength;if(typeof T!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof T);var q=T.length,w=arguments.length>2&&arguments[2]===!0;if(!w&&q===0)return 0;var x=!1;for(;;)switch(K){case"ascii":case"latin1":case"binary":return q;case"utf8":case"utf-8":return R(T).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q*2;case"hex":return q>>>1;case"base64":return v(T).length;default:if(x)return w?-1:R(T).length;K=(""+K).toLowerCase(),x=!0}}Q.byteLength=M;function L(T,K,q){var w=!1;if(K===void 0||K<0)K=0;if(K>this.length)return"";if(q===void 0||q>this.length)q=this.length;if(q<=0)return"";if(q>>>=0,K>>>=0,q<=K)return"";if(!T)T="utf8";while(!0)switch(T){case"hex":return U0(this,K,q);case"utf8":case"utf-8":return N(this,K,q);case"ascii":return m(this,K,q);case"latin1":case"binary":return J0(this,K,q);case"base64":return h(this,K,q);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L0(this,K,q);default:if(w)throw TypeError("Unknown encoding: "+T);T=(T+"").toLowerCase(),w=!0}}Q.prototype._isBuffer=!0;function A(T,K,q){var w=T[K];T[K]=T[q],T[q]=w}if(Q.prototype.swap16=function(){var K=this.length;if(K%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var q=0;qq)K+=" ... ";return""},Z)Q.prototype[Z]=Q.prototype.inspect;Q.prototype.compare=function(K,q,w,x,l){if(e(K,Uint8Array))K=Q.from(K,K.offset,K.byteLength);if(!Q.isBuffer(K))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof K);if(q===void 0)q=0;if(w===void 0)w=K?K.length:0;if(x===void 0)x=0;if(l===void 0)l=this.length;if(q<0||w>K.length||x<0||l>this.length)throw RangeError("out of range index");if(x>=l&&q>=w)return 0;if(x>=l)return-1;if(q>=w)return 1;if(q>>>=0,w>>>=0,x>>>=0,l>>>=0,this===K)return 0;var u=l-x,Q0=w-q,q0=Math.min(u,Q0),K0=this.slice(x,l),M0=K.slice(q,w);for(var w0=0;w02147483647)q=2147483647;else if(q<-2147483648)q=-2147483648;if(q=+q,I(q))q=x?0:T.length-1;if(q<0)q=T.length+q;if(q>=T.length)if(x)return-1;else q=T.length-1;else if(q<0)if(x)q=0;else return-1;if(typeof K==="string")K=Q.from(K,w);if(Q.isBuffer(K)){if(K.length===0)return-1;return g(T,K,q,w,x)}else if(typeof K==="number"){if(K=K&255,typeof Uint8Array.prototype.indexOf==="function")if(x)return Uint8Array.prototype.indexOf.call(T,K,q);else return Uint8Array.prototype.lastIndexOf.call(T,K,q);return g(T,[K],q,w,x)}throw TypeError("val must be string, number or Buffer")}function g(T,K,q,w,x){var l=1,u=T.length,Q0=K.length;if(w!==void 0){if(w=String(w).toLowerCase(),w==="ucs2"||w==="ucs-2"||w==="utf16le"||w==="utf-16le"){if(T.length<2||K.length<2)return-1;l=2,u/=2,Q0/=2,q/=2}}function q0(v0,j2){if(l===1)return v0[j2];else return v0.readUInt16BE(j2*l)}var K0;if(x){var M0=-1;for(K0=q;K0u)q=u-Q0;for(K0=q;K0>=0;K0--){var w0=!0;for(var H0=0;H0x)w=x;var l=K.length;if(w>l/2)w=l/2;for(var u=0;u>>0,isFinite(w)){if(w=w>>>0,x===void 0)x="utf8"}else x=w,w=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var l=this.length-q;if(w===void 0||w>l)w=l;if(K.length>0&&(w<0||q<0)||q>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!x)x="utf8";var u=!1;for(;;)switch(x){case"hex":return d(this,K,q,w);case"utf8":case"utf-8":return E(this,K,q,w);case"ascii":case"latin1":case"binary":return s(this,K,q,w);case"base64":return V0(this,K,q,w);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,K,q,w);default:if(u)throw TypeError("Unknown encoding: "+x);x=(""+x).toLowerCase(),u=!0}},Q.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function h(T,K,q){if(K===0&&q===T.length)return U.fromByteArray(T);else return U.fromByteArray(T.slice(K,q))}function N(T,K,q){q=Math.min(T.length,q);var w=[],x=K;while(x239?4:l>223?3:l>191?2:1;if(x+Q0<=q){var q0,K0,M0,w0;switch(Q0){case 1:if(l<128)u=l;break;case 2:if(q0=T[x+1],(q0&192)===128){if(w0=(l&31)<<6|q0&63,w0>127)u=w0}break;case 3:if(q0=T[x+1],K0=T[x+2],(q0&192)===128&&(K0&192)===128){if(w0=(l&15)<<12|(q0&63)<<6|K0&63,w0>2047&&(w0<55296||w0>57343))u=w0}break;case 4:if(q0=T[x+1],K0=T[x+2],M0=T[x+3],(q0&192)===128&&(K0&192)===128&&(M0&192)===128){if(w0=(l&15)<<18|(q0&63)<<12|(K0&63)<<6|M0&63,w0>65535&&w0<1114112)u=w0}}}if(u===null)u=65533,Q0=1;else if(u>65535)u-=65536,w.push(u>>>10&1023|55296),u=56320|u&1023;w.push(u),x+=Q0}return $0(w)}var a=4096;function $0(T){var K=T.length;if(K<=a)return String.fromCharCode.apply(String,T);var q="",w=0;while(ww)q=w;var x="";for(var l=K;lw)K=w;if(q<0){if(q+=w,q<0)q=0}else if(q>w)q=w;if(qq)throw RangeError("Trying to access beyond buffer length")}Q.prototype.readUintLE=Q.prototype.readUIntLE=function(K,q,w){if(K=K>>>0,q=q>>>0,!w)i(K,q,this.length);var x=this[K],l=1,u=0;while(++u>>0,q=q>>>0,!w)i(K,q,this.length);var x=this[K+--q],l=1;while(q>0&&(l*=256))x+=this[K+--q]*l;return x},Q.prototype.readUint8=Q.prototype.readUInt8=function(K,q){if(K=K>>>0,!q)i(K,1,this.length);return this[K]},Q.prototype.readUint16LE=Q.prototype.readUInt16LE=function(K,q){if(K=K>>>0,!q)i(K,2,this.length);return this[K]|this[K+1]<<8},Q.prototype.readUint16BE=Q.prototype.readUInt16BE=function(K,q){if(K=K>>>0,!q)i(K,2,this.length);return this[K]<<8|this[K+1]},Q.prototype.readUint32LE=Q.prototype.readUInt32LE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return(this[K]|this[K+1]<<8|this[K+2]<<16)+this[K+3]*16777216},Q.prototype.readUint32BE=Q.prototype.readUInt32BE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return this[K]*16777216+(this[K+1]<<16|this[K+2]<<8|this[K+3])},Q.prototype.readIntLE=function(K,q,w){if(K=K>>>0,q=q>>>0,!w)i(K,q,this.length);var x=this[K],l=1,u=0;while(++u=l)x-=Math.pow(2,8*q);return x},Q.prototype.readIntBE=function(K,q,w){if(K=K>>>0,q=q>>>0,!w)i(K,q,this.length);var x=q,l=1,u=this[K+--x];while(x>0&&(l*=256))u+=this[K+--x]*l;if(l*=128,u>=l)u-=Math.pow(2,8*q);return u},Q.prototype.readInt8=function(K,q){if(K=K>>>0,!q)i(K,1,this.length);if(!(this[K]&128))return this[K];return(255-this[K]+1)*-1},Q.prototype.readInt16LE=function(K,q){if(K=K>>>0,!q)i(K,2,this.length);var w=this[K]|this[K+1]<<8;return w&32768?w|4294901760:w},Q.prototype.readInt16BE=function(K,q){if(K=K>>>0,!q)i(K,2,this.length);var w=this[K+1]|this[K]<<8;return w&32768?w|4294901760:w},Q.prototype.readInt32LE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return this[K]|this[K+1]<<8|this[K+2]<<16|this[K+3]<<24},Q.prototype.readInt32BE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return this[K]<<24|this[K+1]<<16|this[K+2]<<8|this[K+3]},Q.prototype.readFloatLE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return Y.read(this,K,!0,23,4)},Q.prototype.readFloatBE=function(K,q){if(K=K>>>0,!q)i(K,4,this.length);return Y.read(this,K,!1,23,4)},Q.prototype.readDoubleLE=function(K,q){if(K=K>>>0,!q)i(K,8,this.length);return Y.read(this,K,!0,52,8)},Q.prototype.readDoubleBE=function(K,q){if(K=K>>>0,!q)i(K,8,this.length);return Y.read(this,K,!1,52,8)};function _(T,K,q,w,x,l){if(!Q.isBuffer(T))throw TypeError('"buffer" argument must be a Buffer instance');if(K>x||KT.length)throw RangeError("Index out of range")}Q.prototype.writeUintLE=Q.prototype.writeUIntLE=function(K,q,w,x){if(K=+K,q=q>>>0,w=w>>>0,!x){var l=Math.pow(2,8*w)-1;_(this,K,q,w,l,0)}var u=1,Q0=0;this[q]=K&255;while(++Q0>>0,w=w>>>0,!x){var l=Math.pow(2,8*w)-1;_(this,K,q,w,l,0)}var u=w-1,Q0=1;this[q+u]=K&255;while(--u>=0&&(Q0*=256))this[q+u]=K/Q0&255;return q+w},Q.prototype.writeUint8=Q.prototype.writeUInt8=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,1,255,0);return this[q]=K&255,q+1},Q.prototype.writeUint16LE=Q.prototype.writeUInt16LE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,2,65535,0);return this[q]=K&255,this[q+1]=K>>>8,q+2},Q.prototype.writeUint16BE=Q.prototype.writeUInt16BE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,2,65535,0);return this[q]=K>>>8,this[q+1]=K&255,q+2},Q.prototype.writeUint32LE=Q.prototype.writeUInt32LE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,4,4294967295,0);return this[q+3]=K>>>24,this[q+2]=K>>>16,this[q+1]=K>>>8,this[q]=K&255,q+4},Q.prototype.writeUint32BE=Q.prototype.writeUInt32BE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,4,4294967295,0);return this[q]=K>>>24,this[q+1]=K>>>16,this[q+2]=K>>>8,this[q+3]=K&255,q+4},Q.prototype.writeIntLE=function(K,q,w,x){if(K=+K,q=q>>>0,!x){var l=Math.pow(2,8*w-1);_(this,K,q,w,l-1,-l)}var u=0,Q0=1,q0=0;this[q]=K&255;while(++u>0)-q0&255}return q+w},Q.prototype.writeIntBE=function(K,q,w,x){if(K=+K,q=q>>>0,!x){var l=Math.pow(2,8*w-1);_(this,K,q,w,l-1,-l)}var u=w-1,Q0=1,q0=0;this[q+u]=K&255;while(--u>=0&&(Q0*=256)){if(K<0&&q0===0&&this[q+u+1]!==0)q0=1;this[q+u]=(K/Q0>>0)-q0&255}return q+w},Q.prototype.writeInt8=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,1,127,-128);if(K<0)K=255+K+1;return this[q]=K&255,q+1},Q.prototype.writeInt16LE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,2,32767,-32768);return this[q]=K&255,this[q+1]=K>>>8,q+2},Q.prototype.writeInt16BE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,2,32767,-32768);return this[q]=K>>>8,this[q+1]=K&255,q+2},Q.prototype.writeInt32LE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,4,2147483647,-2147483648);return this[q]=K&255,this[q+1]=K>>>8,this[q+2]=K>>>16,this[q+3]=K>>>24,q+4},Q.prototype.writeInt32BE=function(K,q,w){if(K=+K,q=q>>>0,!w)_(this,K,q,4,2147483647,-2147483648);if(K<0)K=4294967295+K+1;return this[q]=K>>>24,this[q+1]=K>>>16,this[q+2]=K>>>8,this[q+3]=K&255,q+4};function r(T,K,q,w,x,l){if(q+w>T.length)throw RangeError("Index out of range");if(q<0)throw RangeError("Index out of range")}function n(T,K,q,w,x){if(K=+K,q=q>>>0,!x)r(T,K,q,4);return Y.write(T,K,q,w,23,4),q+4}Q.prototype.writeFloatLE=function(K,q,w){return n(this,K,q,!0,w)},Q.prototype.writeFloatBE=function(K,q,w){return n(this,K,q,!1,w)};function Z0(T,K,q,w,x){if(K=+K,q=q>>>0,!x)r(T,K,q,8);return Y.write(T,K,q,w,52,8),q+8}Q.prototype.writeDoubleLE=function(K,q,w){return Z0(this,K,q,!0,w)},Q.prototype.writeDoubleBE=function(K,q,w){return Z0(this,K,q,!1,w)},Q.prototype.copy=function(K,q,w,x){if(!Q.isBuffer(K))throw TypeError("argument should be a Buffer");if(!w)w=0;if(!x&&x!==0)x=this.length;if(q>=K.length)q=K.length;if(!q)q=0;if(x>0&&x=this.length)throw RangeError("Index out of range");if(x<0)throw RangeError("sourceEnd out of bounds");if(x>this.length)x=this.length;if(K.length-q>>0,w=w===void 0?this.length:w>>>0,!K)K=0;var u;if(typeof K==="number")for(u=q;u55295&&q<57344){if(!x){if(q>56319){if((K-=3)>-1)l.push(239,191,189);continue}else if(u+1===w){if((K-=3)>-1)l.push(239,191,189);continue}x=q;continue}if(q<56320){if((K-=3)>-1)l.push(239,191,189);x=q;continue}q=(x-55296<<10|q-56320)+65536}else if(x){if((K-=3)>-1)l.push(239,191,189)}if(x=null,q<128){if((K-=1)<0)break;l.push(q)}else if(q<2048){if((K-=2)<0)break;l.push(q>>6|192,q&63|128)}else if(q<65536){if((K-=3)<0)break;l.push(q>>12|224,q>>6&63|128,q&63|128)}else if(q<1114112){if((K-=4)<0)break;l.push(q>>18|240,q>>12&63|128,q>>6&63|128,q&63|128)}else throw Error("Invalid code point")}return l}function c(T){var K=[];for(var q=0;q>8,x=q%256,l.push(x),l.push(w)}return l}function v(T){return U.toByteArray(P(T))}function b(T,K,q,w){for(var x=0;x=K.length||x>=T.length)break;K[x+q]=T[x]}return x}function e(T,K){return T instanceof K||T!=null&&T.constructor!=null&&T.constructor.name!=null&&T.constructor.name===K.name}function I(T){return T!==T}var t=function(){var T="0123456789abcdef",K=Array(256);for(var q=0;q<16;++q){var w=q*16;for(var x=0;x<16;++x)K[w+x]=T[q]+T[x]}return K}()}(b8),b8}var g8={},x8={},f8,$Y;function QQ(){if($Y)return f8;return $Y=1,f8=function(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function")return!1;if(typeof Symbol.iterator==="symbol")return!0;var U={},Y=Symbol("test"),Z=Object(Y);if(typeof Y==="string")return!1;if(Object.prototype.toString.call(Y)!=="[object Symbol]")return!1;if(Object.prototype.toString.call(Z)!=="[object Symbol]")return!1;var J=42;U[Y]=J;for(var G in U)return!1;if(typeof Object.keys==="function"&&Object.keys(U).length!==0)return!1;if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(U).length!==0)return!1;var X=Object.getOwnPropertySymbols(U);if(X.length!==1||X[0]!==Y)return!1;if(!Object.prototype.propertyIsEnumerable.call(U,Y))return!1;if(typeof Object.getOwnPropertyDescriptor==="function"){var Q=Object.getOwnPropertyDescriptor(U,Y);if(Q.value!==J||Q.enumerable!==!0)return!1}return!0},f8}var h8,UY;function f9(){if(UY)return h8;UY=1;var $=QQ();return h8=function(){return $()&&!!Symbol.toStringTag},h8}var u8,YY;function JQ(){if(YY)return u8;return YY=1,u8=Object,u8}var d8,ZY;function Fq(){if(ZY)return d8;return ZY=1,d8=Error,d8}var c8,QY;function Nq(){if(QY)return c8;return QY=1,c8=EvalError,c8}var m8,JY;function Rq(){if(JY)return m8;return JY=1,m8=RangeError,m8}var l8,GY;function Dq(){if(GY)return l8;return GY=1,l8=ReferenceError,l8}var a8,KY;function GQ(){if(KY)return a8;return KY=1,a8=SyntaxError,a8}var p8,qY;function t1(){if(qY)return p8;return qY=1,p8=TypeError,p8}var i8,XY;function Aq(){if(XY)return i8;return XY=1,i8=URIError,i8}var r8,VY;function Pq(){if(VY)return r8;return VY=1,r8=Math.abs,r8}var s8,BY;function Tq(){if(BY)return s8;return BY=1,s8=Math.floor,s8}var n8,LY;function Cq(){if(LY)return n8;return LY=1,n8=Math.max,n8}var o8,MY;function Oq(){if(MY)return o8;return MY=1,o8=Math.min,o8}var t8,IY;function kq(){if(IY)return t8;return IY=1,t8=Math.pow,t8}var e8,wY;function Eq(){if(wY)return e8;return wY=1,e8=Math.round,e8}var $6,WY;function Sq(){if(WY)return $6;return WY=1,$6=Number.isNaN||function(U){return U!==U},$6}var U6,HY;function vq(){if(HY)return U6;HY=1;var $=Sq();return U6=function(Y){if($(Y)||Y===0)return Y;return Y<0?-1:1},U6}var Y6,jY;function _q(){if(jY)return Y6;return jY=1,Y6=Object.getOwnPropertyDescriptor,Y6}var Z6,zY;function I1(){if(zY)return Z6;zY=1;var $=_q();if($)try{$([],"length")}catch(U){$=null}return Z6=$,Z6}var Q6,FY;function e1(){if(FY)return Q6;FY=1;var $=Object.defineProperty||!1;if($)try{$({},"a",{value:1})}catch(U){$=!1}return Q6=$,Q6}var J6,NY;function yq(){if(NY)return J6;NY=1;var $=typeof Symbol<"u"&&Symbol,U=QQ();return J6=function(){if(typeof $!=="function")return!1;if(typeof Symbol!=="function")return!1;if(typeof $("foo")!=="symbol")return!1;if(typeof Symbol("bar")!=="symbol")return!1;return U()},J6}var G6,RY;function KQ(){if(RY)return G6;return RY=1,G6=typeof Reflect<"u"&&Reflect.getPrototypeOf||null,G6}var K6,DY;function qQ(){if(DY)return K6;DY=1;var $=JQ();return K6=$.getPrototypeOf||null,K6}var q6,AY;function bq(){if(AY)return q6;AY=1;var $="Function.prototype.bind called on incompatible ",U=Object.prototype.toString,Y=Math.max,Z="[object Function]",J=function(B,F){var z=[];for(var W=0;W"u"||!g?$:g(Uint8Array),N={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?$:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?$:ArrayBuffer,"%ArrayIteratorPrototype%":y&&g?g([][Symbol.iterator]()):$,"%AsyncFromSyncIteratorPrototype%":$,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":typeof Atomics>"u"?$:Atomics,"%BigInt%":typeof BigInt>"u"?$:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?$:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?$:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?$:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Y,"%eval%":eval,"%EvalError%":Z,"%Float16Array%":typeof Float16Array>"u"?$:Float16Array,"%Float32Array%":typeof Float32Array>"u"?$:Float32Array,"%Float64Array%":typeof Float64Array>"u"?$:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?$:FinalizationRegistry,"%Function%":O,"%GeneratorFunction%":S,"%Int8Array%":typeof Int8Array>"u"?$:Int8Array,"%Int16Array%":typeof Int16Array>"u"?$:Int16Array,"%Int32Array%":typeof Int32Array>"u"?$:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&g?g(g([][Symbol.iterator]())):$,"%JSON%":typeof JSON==="object"?JSON:$,"%Map%":typeof Map>"u"?$:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!g?$:g(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":U,"%Object.getOwnPropertyDescriptor%":j,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?$:Promise,"%Proxy%":typeof Proxy>"u"?$:Proxy,"%RangeError%":J,"%ReferenceError%":G,"%Reflect%":typeof Reflect>"u"?$:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?$:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!g?$:g(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?$:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&g?g(""[Symbol.iterator]()):$,"%Symbol%":y?Symbol:$,"%SyntaxError%":X,"%ThrowTypeError%":A,"%TypedArray%":h,"%TypeError%":Q,"%Uint8Array%":typeof Uint8Array>"u"?$:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?$:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?$:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?$:Uint32Array,"%URIError%":B,"%WeakMap%":typeof WeakMap>"u"?$:WeakMap,"%WeakRef%":typeof WeakRef>"u"?$:WeakRef,"%WeakSet%":typeof WeakSet>"u"?$:WeakSet,"%Function.prototype.call%":V0,"%Function.prototype.apply%":s,"%Object.defineProperty%":M,"%Object.getPrototypeOf%":d,"%Math.abs%":F,"%Math.floor%":z,"%Math.max%":W,"%Math.min%":k,"%Math.pow%":D,"%Math.round%":C,"%Math.sign%":H,"%Reflect.getPrototypeOf%":E};if(g)try{null.error}catch(c){var a=g(g(c));N["%Error.prototype%"]=a}var $0=function c(f){var v;if(f==="%AsyncFunction%")v=V("async function () {}");else if(f==="%GeneratorFunction%")v=V("function* () {}");else if(f==="%AsyncGeneratorFunction%")v=V("async function* () {}");else if(f==="%AsyncGenerator%"){var b=c("%AsyncGeneratorFunction%");if(b)v=b.prototype}else if(f==="%AsyncIteratorPrototype%"){var e=c("%AsyncGenerator%");if(e&&g)v=g(e.prototype)}return N[f]=v,v},m={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},J0=w1(),U0=fq(),L0=J0.call(V0,Array.prototype.concat),i=J0.call(s,Array.prototype.splice),_=J0.call(V0,String.prototype.replace),r=J0.call(V0,String.prototype.slice),n=J0.call(V0,RegExp.prototype.exec),Z0=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,p=/\\(\\)?/g,P=function(f){var v=r(f,0,1),b=r(f,-1);if(v==="%"&&b!=="%")throw new X("invalid intrinsic syntax, expected closing `%`");else if(b==="%"&&v!=="%")throw new X("invalid intrinsic syntax, expected opening `%`");var e=[];return _(f,Z0,function(I,t,T,K){e[e.length]=T?_(K,p,"$1"):t||I}),e},R=function(f,v){var b=f,e;if(U0(m,b))e=m[b],b="%"+e[0]+"%";if(U0(N,b)){var I=N[b];if(I===S)I=$0(b);if(typeof I>"u"&&!v)throw new Q("intrinsic "+f+" exists, but is not available. Please file an issue!");return{alias:e,name:b,value:I}}throw new X("intrinsic "+f+" does not exist!")};return j6=function(f,v){if(typeof f!=="string"||f.length===0)throw new Q("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof v!=="boolean")throw new Q('"allowMissing" argument must be a boolean');if(n(/^%?[^%]*%?$/,f)===null)throw new X("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var b=P(f),e=b.length>0?b[0]:"",I=R("%"+e+"%",v),t=I.name,T=I.value,K=!1,q=I.alias;if(q)e=q[0],i(b,L0([0,1],q));for(var w=1,x=!0;w=b.length){var q0=j(T,l);if(x=!!q0,x&&"get"in q0&&!("originalValue"in q0.get))T=q0.get;else T=T[l]}else x=U0(T,l),T=T[l];if(x&&!K)N[t]=T}}return T},j6}var z6,bY;function LQ(){if(bY)return z6;bY=1;var $=BQ(),U=d9(),Y=U([$("%String.prototype.indexOf%")]);return z6=function(J,G){var X=$(J,!!G);if(typeof X==="function"&&Y(J,".prototype.")>-1)return U([X]);return X},z6}var F6,gY;function hq(){if(gY)return F6;gY=1;var $=f9()(),U=LQ(),Y=U("Object.prototype.toString"),Z=function(Q){if($&&Q&&typeof Q==="object"&&Symbol.toStringTag in Q)return!1;return Y(Q)==="[object Arguments]"},J=function(Q){if(Z(Q))return!0;return Q!==null&&typeof Q==="object"&&"length"in Q&&typeof Q.length==="number"&&Q.length>=0&&Y(Q)!=="[object Array]"&&"callee"in Q&&Y(Q.callee)==="[object Function]"},G=function(){return Z(arguments)}();return Z.isLegacyArguments=J,F6=G?Z:J,F6}var N6,xY;function uq(){if(xY)return N6;xY=1;var $=Object.prototype.toString,U=Function.prototype.toString,Y=/^\s*(?:function)?\*/,Z=f9()(),J=Object.getPrototypeOf,G=function(){if(!Z)return!1;try{return Function("return function*() {}")()}catch(Q){}},X;return N6=function(B){if(typeof B!=="function")return!1;if(Y.test(U.call(B)))return!0;if(!Z){var F=$.call(B);return F==="[object GeneratorFunction]"}if(!J)return!1;if(typeof X>"u"){var z=G();X=z?J(z):!1}return J(B)===X},N6}var R6,fY;function dq(){if(fY)return R6;fY=1;var $=Function.prototype.toString,U=typeof Reflect==="object"&&Reflect!==null&&Reflect.apply,Y,Z;if(typeof U==="function"&&typeof Object.defineProperty==="function")try{Y=Object.defineProperty({},"length",{get:function(){throw Z}}),Z={},U(function(){throw 42},null,Y)}catch(j){if(j!==Z)U=null}else U=null;var J=/^\s*class\b/,G=function(M){try{var L=$.call(M);return J.test(L)}catch(A){return!1}},X=function(M){try{if(G(M))return!1;return $.call(M),!0}catch(L){return!1}},Q=Object.prototype.toString,B="[object Object]",F="[object Function]",z="[object GeneratorFunction]",W="[object HTMLAllCollection]",k="[object HTML document.all class]",D="[object HTMLCollection]",C=typeof Symbol==="function"&&!!Symbol.toStringTag,H=!(0 in[,]),O=function(){return!1};if(typeof document==="object"){var V=document.all;if(Q.call(V)===Q.call(document.all))O=function(M){if((H||!M)&&(typeof M>"u"||typeof M==="object"))try{var L=Q.call(M);return(L===W||L===k||L===D||L===B)&&M("")==null}catch(A){}return!1}}return R6=U?function(M){if(O(M))return!0;if(!M)return!1;if(typeof M!=="function"&&typeof M!=="object")return!1;try{U(M,null,Y)}catch(L){if(L!==Z)return!1}return!G(M)&&X(M)}:function(M){if(O(M))return!0;if(!M)return!1;if(typeof M!=="function"&&typeof M!=="object")return!1;if(C)return X(M);if(G(M))return!1;var L=Q.call(M);if(L!==F&&L!==z&&!/^\[object HTML/.test(L))return!1;return X(M)},R6}var D6,hY;function cq(){if(hY)return D6;hY=1;var $=dq(),U=Object.prototype.toString,Y=Object.prototype.hasOwnProperty,Z=function(B,F,z){for(var W=0,k=B.length;W=3)W=z;if(X(B))Z(B,F,W);else if(typeof B==="string")J(B,F,W);else G(B,F,W)},D6}var A6,uY;function mq(){if(uY)return A6;return uY=1,A6=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"],A6}var P6,dY;function lq(){if(dY)return P6;dY=1;var $=mq(),U=typeof globalThis>"u"?c0:globalThis;return P6=function(){var Z=[];for(var J=0;J<$.length;J++)if(typeof U[$[J]]==="function")Z[Z.length]=$[J];return Z},P6}var T6={exports:{}},C6,cY;function aq(){if(cY)return C6;cY=1;var $=e1(),U=GQ(),Y=t1(),Z=I1();return C6=function(G,X,Q){if(!G||typeof G!=="object"&&typeof G!=="function")throw new Y("`obj` must be an object or a function`");if(typeof X!=="string"&&typeof X!=="symbol")throw new Y("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=="boolean"&&arguments[3]!==null)throw new Y("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=="boolean"&&arguments[4]!==null)throw new Y("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=="boolean"&&arguments[5]!==null)throw new Y("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=="boolean")throw new Y("`loose`, if provided, must be a boolean");var B=arguments.length>3?arguments[3]:null,F=arguments.length>4?arguments[4]:null,z=arguments.length>5?arguments[5]:null,W=arguments.length>6?arguments[6]:!1,k=!!Z&&Z(G,X);if($)$(G,X,{configurable:z===null&&k?k.configurable:!z,enumerable:B===null&&k?k.enumerable:!B,value:Q,writable:F===null&&k?k.writable:!F});else if(W||!B&&!F&&!z)G[X]=Q;else throw new U("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},C6}var O6,mY;function pq(){if(mY)return O6;mY=1;var $=e1(),U=function(){return!!$};return U.hasArrayLengthDefineBug=function(){if(!$)return null;try{return $([],"length",{value:1}).length!==1}catch(Z){return!0}},O6=U,O6}var k6,lY;function iq(){if(lY)return k6;lY=1;var $=BQ(),U=aq(),Y=pq()(),Z=I1(),J=t1(),G=$("%Math.floor%");return k6=function(Q,B){if(typeof Q!=="function")throw new J("`fn` is not a function");if(typeof B!=="number"||B<0||B>4294967295||G(B)!==B)throw new J("`length` must be a positive 32-bit integer");var F=arguments.length>2&&!!arguments[2],z=!0,W=!0;if("length"in Q&&Z){var k=Z(Q,"length");if(k&&!k.configurable)z=!1;if(k&&!k.writable)W=!1}if(z||W||!F)if(Y)U(Q,"length",B,!0,!0);else U(Q,"length",B);return Q},k6}var E6,aY;function rq(){if(aY)return E6;aY=1;var $=w1(),U=u9(),Y=XQ();return E6=function(){return Y($,U,arguments)},E6}var pY;function sq(){if(pY)return T6.exports;return pY=1,function($){var U=iq(),Y=e1(),Z=d9(),J=rq();if($.exports=function(X){var Q=Z(arguments),B=X.length-(arguments.length-1);return U(Q,1+(B>0?B:0),!0)},Y)Y($.exports,"apply",{value:J});else $.exports.apply=J}(T6),T6.exports}var S6,iY;function MQ(){if(iY)return S6;iY=1;var $=cq(),U=lq(),Y=sq(),Z=LQ(),J=I1(),G=VQ(),X=Z("Object.prototype.toString"),Q=f9()(),B=typeof globalThis>"u"?c0:globalThis,F=U(),z=Z("String.prototype.slice"),W=Z("Array.prototype.indexOf",!0)||function(O,V){for(var j=0;j-1)return V;if(V!=="Object")return!1;return C(O)}if(!J)return null;return D(O)},S6}var v6,rY;function nq(){if(rY)return v6;rY=1;var $=MQ();return v6=function(Y){return!!$(Y)},v6}var sY;function oq(){if(sY)return x8;return sY=1,function($){var U=hq(),Y=uq(),Z=MQ(),J=nq();function G(w){return w.call.bind(w)}var X=typeof BigInt<"u",Q=typeof Symbol<"u",B=G(Object.prototype.toString),F=G(Number.prototype.valueOf),z=G(String.prototype.valueOf),W=G(Boolean.prototype.valueOf);if(X)var k=G(BigInt.prototype.valueOf);if(Q)var D=G(Symbol.prototype.valueOf);function C(w,x){if(typeof w!=="object")return!1;try{return x(w),!0}catch(l){return!1}}$.isArgumentsObject=U,$.isGeneratorFunction=Y,$.isTypedArray=J;function H(w){return typeof Promise<"u"&&w instanceof Promise||w!==null&&typeof w==="object"&&typeof w.then==="function"&&typeof w.catch==="function"}$.isPromise=H;function O(w){if(typeof ArrayBuffer<"u"&&ArrayBuffer.isView)return ArrayBuffer.isView(w);return J(w)||r(w)}$.isArrayBufferView=O;function V(w){return Z(w)==="Uint8Array"}$.isUint8Array=V;function j(w){return Z(w)==="Uint8ClampedArray"}$.isUint8ClampedArray=j;function M(w){return Z(w)==="Uint16Array"}$.isUint16Array=M;function L(w){return Z(w)==="Uint32Array"}$.isUint32Array=L;function A(w){return Z(w)==="Int8Array"}$.isInt8Array=A;function y(w){return Z(w)==="Int16Array"}$.isInt16Array=y;function g(w){return Z(w)==="Int32Array"}$.isInt32Array=g;function d(w){return Z(w)==="Float32Array"}$.isFloat32Array=d;function E(w){return Z(w)==="Float64Array"}$.isFloat64Array=E;function s(w){return Z(w)==="BigInt64Array"}$.isBigInt64Array=s;function V0(w){return Z(w)==="BigUint64Array"}$.isBigUint64Array=V0;function S(w){return B(w)==="[object Map]"}S.working=typeof Map<"u"&&S(new Map);function h(w){if(typeof Map>"u")return!1;return S.working?S(w):w instanceof Map}$.isMap=h;function N(w){return B(w)==="[object Set]"}N.working=typeof Set<"u"&&N(new Set);function a(w){if(typeof Set>"u")return!1;return N.working?N(w):w instanceof Set}$.isSet=a;function $0(w){return B(w)==="[object WeakMap]"}$0.working=typeof WeakMap<"u"&&$0(new WeakMap);function m(w){if(typeof WeakMap>"u")return!1;return $0.working?$0(w):w instanceof WeakMap}$.isWeakMap=m;function J0(w){return B(w)==="[object WeakSet]"}J0.working=typeof WeakSet<"u"&&J0(new WeakSet);function U0(w){return J0(w)}$.isWeakSet=U0;function L0(w){return B(w)==="[object ArrayBuffer]"}L0.working=typeof ArrayBuffer<"u"&&L0(new ArrayBuffer);function i(w){if(typeof ArrayBuffer>"u")return!1;return L0.working?L0(w):w instanceof ArrayBuffer}$.isArrayBuffer=i;function _(w){return B(w)==="[object DataView]"}_.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&_(new DataView(new ArrayBuffer(1),0,1));function r(w){if(typeof DataView>"u")return!1;return _.working?_(w):w instanceof DataView}$.isDataView=r;var n=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function Z0(w){return B(w)==="[object SharedArrayBuffer]"}function p(w){if(typeof n>"u")return!1;if(typeof Z0.working>"u")Z0.working=Z0(new n);return Z0.working?Z0(w):w instanceof n}$.isSharedArrayBuffer=p;function P(w){return B(w)==="[object AsyncFunction]"}$.isAsyncFunction=P;function R(w){return B(w)==="[object Map Iterator]"}$.isMapIterator=R;function c(w){return B(w)==="[object Set Iterator]"}$.isSetIterator=c;function f(w){return B(w)==="[object Generator]"}$.isGeneratorObject=f;function v(w){return B(w)==="[object WebAssembly.Module]"}$.isWebAssemblyCompiledModule=v;function b(w){return C(w,F)}$.isNumberObject=b;function e(w){return C(w,z)}$.isStringObject=e;function I(w){return C(w,W)}$.isBooleanObject=I;function t(w){return X&&C(w,k)}$.isBigIntObject=t;function T(w){return Q&&C(w,D)}$.isSymbolObject=T;function K(w){return b(w)||e(w)||I(w)||t(w)||T(w)}$.isBoxedPrimitive=K;function q(w){return typeof Uint8Array<"u"&&(i(w)||p(w))}$.isAnyArrayBuffer=q,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(w){Object.defineProperty($,w,{enumerable:!1,value:function(){throw Error(w+" is not supported in userland")}})})}(x8),x8}var _6,nY;function tq(){if(nY)return _6;return nY=1,_6=function(U){return U&&typeof U==="object"&&typeof U.copy==="function"&&typeof U.fill==="function"&&typeof U.readUInt8==="function"},_6}var oY;function IQ(){if(oY)return g8;return oY=1,function($){var U=Object.getOwnPropertyDescriptors||function(r){var n=Object.keys(r),Z0={};for(var p=0;p=p)return c;switch(c){case"%s":return String(Z0[n++]);case"%d":return Number(Z0[n++]);case"%j":try{return JSON.stringify(Z0[n++])}catch(f){return"[Circular]"}default:return c}});for(var R=Z0[n];n"u")return function(){return $.deprecate(_,r).apply(this,arguments)};var n=!1;function Z0(){if(!n){if(j0.throwDeprecation)throw Error(r);else if(j0.traceDeprecation)console.trace(r);else console.error(r);n=!0}return _.apply(this,arguments)}return Z0};var Z={},J=/^$/;if(j0.env.NODE_DEBUG){var G=j0.env.NODE_DEBUG;G=G.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),J=new RegExp("^"+G+"$","i")}$.debuglog=function(_){if(_=_.toUpperCase(),!Z[_])if(J.test(_)){var r=j0.pid;Z[_]=function(){var n=$.format.apply($,arguments);console.error("%s %d: %s",_,r,n)}}else Z[_]=function(){};return Z[_]};function X(_,r){var n={seen:[],stylize:B};if(arguments.length>=3)n.depth=arguments[2];if(arguments.length>=4)n.colors=arguments[3];if(V(r))n.showHidden=r;else if(r)$._extend(n,r);if(g(n.showHidden))n.showHidden=!1;if(g(n.depth))n.depth=2;if(g(n.colors))n.colors=!1;if(g(n.customInspect))n.customInspect=!0;if(n.colors)n.stylize=Q;return z(n,_,n.depth)}$.inspect=X,X.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},X.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Q(_,r){var n=X.styles[r];if(n)return"\x1B["+X.colors[n][0]+"m"+_+"\x1B["+X.colors[n][1]+"m";else return _}function B(_,r){return _}function F(_){var r={};return _.forEach(function(n,Z0){r[n]=!0}),r}function z(_,r,n){if(_.customInspect&&r&&S(r.inspect)&&r.inspect!==$.inspect&&!(r.constructor&&r.constructor.prototype===r)){var Z0=r.inspect(n,_);if(!A(Z0))Z0=z(_,Z0,n);return Z0}var p=W(_,r);if(p)return p;var P=Object.keys(r),R=F(P);if(_.showHidden)P=Object.getOwnPropertyNames(r);if(V0(r)&&(P.indexOf("message")>=0||P.indexOf("description")>=0))return k(r);if(P.length===0){if(S(r)){var c=r.name?": "+r.name:"";return _.stylize("[Function"+c+"]","special")}if(d(r))return _.stylize(RegExp.prototype.toString.call(r),"regexp");if(s(r))return _.stylize(Date.prototype.toString.call(r),"date");if(V0(r))return k(r)}var f="",v=!1,b=["{","}"];if(O(r))v=!0,b=["[","]"];if(S(r)){var e=r.name?": "+r.name:"";f=" [Function"+e+"]"}if(d(r))f=" "+RegExp.prototype.toString.call(r);if(s(r))f=" "+Date.prototype.toUTCString.call(r);if(V0(r))f=" "+k(r);if(P.length===0&&(!v||r.length==0))return b[0]+f+b[1];if(n<0)if(d(r))return _.stylize(RegExp.prototype.toString.call(r),"regexp");else return _.stylize("[Object]","special");_.seen.push(r);var I;if(v)I=D(_,r,n,R,P);else I=P.map(function(t){return C(_,r,n,R,t,v)});return _.seen.pop(),H(I,f,b)}function W(_,r){if(g(r))return _.stylize("undefined","undefined");if(A(r)){var n="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return _.stylize(n,"string")}if(L(r))return _.stylize(""+r,"number");if(V(r))return _.stylize(""+r,"boolean");if(j(r))return _.stylize("null","null")}function k(_){return"["+Error.prototype.toString.call(_)+"]"}function D(_,r,n,Z0,p){var P=[];for(var R=0,c=r.length;R-1)if(P)c=c.split(` +`).map(function(v){return" "+v}).join(` +`).slice(2);else c=` +`+c.split(` +`).map(function(v){return" "+v}).join(` +`)}else c=_.stylize("[Circular]","special");if(g(R)){if(P&&p.match(/^\d+$/))return c;if(R=JSON.stringify(""+p),R.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/))R=R.slice(1,-1),R=_.stylize(R,"name");else R=R.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),R=_.stylize(R,"string")}return R+": "+c}function H(_,r,n){var Z0=_.reduce(function(p,P){if(P.indexOf(` +`)>=0);return p+P.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(Z0>60)return n[0]+(r===""?"":r+` + `)+" "+_.join(`, + `)+" "+n[1];return n[0]+r+" "+_.join(", ")+" "+n[1]}$.types=oq();function O(_){return Array.isArray(_)}$.isArray=O;function V(_){return typeof _==="boolean"}$.isBoolean=V;function j(_){return _===null}$.isNull=j;function M(_){return _==null}$.isNullOrUndefined=M;function L(_){return typeof _==="number"}$.isNumber=L;function A(_){return typeof _==="string"}$.isString=A;function y(_){return typeof _==="symbol"}$.isSymbol=y;function g(_){return _===void 0}$.isUndefined=g;function d(_){return E(_)&&N(_)==="[object RegExp]"}$.isRegExp=d,$.types.isRegExp=d;function E(_){return typeof _==="object"&&_!==null}$.isObject=E;function s(_){return E(_)&&N(_)==="[object Date]"}$.isDate=s,$.types.isDate=s;function V0(_){return E(_)&&(N(_)==="[object Error]"||_ instanceof Error)}$.isError=V0,$.types.isNativeError=V0;function S(_){return typeof _==="function"}$.isFunction=S;function h(_){return _===null||typeof _==="boolean"||typeof _==="number"||typeof _==="string"||typeof _==="symbol"||typeof _>"u"}$.isPrimitive=h,$.isBuffer=tq();function N(_){return Object.prototype.toString.call(_)}function a(_){return _<10?"0"+_.toString(10):_.toString(10)}var $0=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function m(){var _=new Date,r=[a(_.getHours()),a(_.getMinutes()),a(_.getSeconds())].join(":");return[_.getDate(),$0[_.getMonth()],r].join(" ")}$.log=function(){console.log("%s - %s",m(),$.format.apply($,arguments))},$.inherits=R2(),$._extend=function(_,r){if(!r||!E(r))return _;var n=Object.keys(r),Z0=n.length;while(Z0--)_[n[Z0]]=r[n[Z0]];return _};function J0(_,r){return Object.prototype.hasOwnProperty.call(_,r)}var U0=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;$.promisify=function(r){if(typeof r!=="function")throw TypeError('The "original" argument must be of type Function');if(U0&&r[U0]){var n=r[U0];if(typeof n!=="function")throw TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(n,U0,{value:n,enumerable:!1,writable:!1,configurable:!0}),n}function n(){var Z0,p,P=new Promise(function(f,v){Z0=f,p=v}),R=[];for(var c=0;c0)this.tail.next=V;else this.head=V;this.tail=V,++this.length}},{key:"unshift",value:function(O){var V={data:O,next:this.head};if(this.length===0)this.tail=V;this.head=V,++this.length}},{key:"shift",value:function(){if(this.length===0)return;var O=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,O}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(O){if(this.length===0)return"";var V=this.head,j=""+V.data;while(V=V.next)j+=O+V.data;return j}},{key:"concat",value:function(O){if(this.length===0)return F.alloc(0);var V=F.allocUnsafe(O>>>0),j=this.head,M=0;while(j)D(j.data,V,M),M+=j.data.length,j=j.next;return V}},{key:"consume",value:function(O,V){var j;if(OL.length?L.length:O;if(A===L.length)M+=L;else M+=L.slice(0,O);if(O-=A,O===0){if(A===L.length)if(++j,V.next)this.head=V.next;else this.head=this.tail=null;else this.head=V,V.data=L.slice(A);break}++j}return this.length-=j,M}},{key:"_getBuffer",value:function(O){var V=F.allocUnsafe(O),j=this.head,M=1;j.data.copy(V),O-=j.data.length;while(j=j.next){var L=j.data,A=O>L.length?L.length:O;if(L.copy(V,V.length-O,0,A),O-=A,O===0){if(A===L.length)if(++M,j.next)this.head=j.next;else this.head=this.tail=null;else this.head=j,j.data=L.slice(A);break}++M}return this.length-=M,V}},{key:k,value:function(O,V){return W(this,U(U({},V),{},{depth:0,customInspect:!1}))}}]),C}(),y6}var b6,eY;function wQ(){if(eY)return b6;eY=1;function $(X,Q){var B=this,F=this._readableState&&this._readableState.destroyed,z=this._writableState&&this._writableState.destroyed;if(F||z){if(Q)Q(X);else if(X){if(!this._writableState)j0.nextTick(J,this,X);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,j0.nextTick(J,this,X)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy(X||null,function(W){if(!Q&&W)if(!B._writableState)j0.nextTick(U,B,W);else if(!B._writableState.errorEmitted)B._writableState.errorEmitted=!0,j0.nextTick(U,B,W);else j0.nextTick(Y,B);else if(Q)j0.nextTick(Y,B),Q(W);else j0.nextTick(Y,B)}),this}function U(X,Q){J(X,Q),Y(X)}function Y(X){if(X._writableState&&!X._writableState.emitClose)return;if(X._readableState&&!X._readableState.emitClose)return;X.emit("close")}function Z(){if(this._readableState)this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1;if(this._writableState)this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1}function J(X,Q){X.emit("error",Q)}function G(X,Q){var{_readableState:B,_writableState:F}=X;if(B&&B.autoDestroy||F&&F.autoDestroy)X.destroy(Q);else X.emit("error",Q)}return b6={destroy:$,undestroy:Z,errorOrDestroy:G},b6}var g6={},$Z;function i2(){if($Z)return g6;$Z=1;function $(Q,B){Q.prototype=Object.create(B.prototype),Q.prototype.constructor=Q,Q.__proto__=B}var U={};function Y(Q,B,F){if(!F)F=Error;function z(k,D,C){if(typeof B==="string")return B;else return B(k,D,C)}var W=function(k){$(D,k);function D(C,H,O){return k.call(this,z(C,H,O))||this}return D}(F);W.prototype.name=F.name,W.prototype.code=Q,U[Q]=W}function Z(Q,B){if(Array.isArray(Q)){var F=Q.length;if(Q=Q.map(function(z){return String(z)}),F>2)return"one of ".concat(B," ").concat(Q.slice(0,F-1).join(", "),", or ")+Q[F-1];else if(F===2)return"one of ".concat(B," ").concat(Q[0]," or ").concat(Q[1]);else return"of ".concat(B," ").concat(Q[0])}else return"of ".concat(B," ").concat(String(Q))}function J(Q,B,F){return Q.substr(0,B.length)===B}function G(Q,B,F){if(F===void 0||F>Q.length)F=Q.length;return Q.substring(F-B.length,F)===B}function X(Q,B,F){if(typeof F!=="number")F=0;if(F+B.length>Q.length)return!1;else return Q.indexOf(B,F)!==-1}return Y("ERR_INVALID_OPT_VALUE",function(Q,B){return'The value "'+B+'" is invalid for option "'+Q+'"'},TypeError),Y("ERR_INVALID_ARG_TYPE",function(Q,B,F){var z;if(typeof B==="string"&&J(B,"not "))z="must not be",B=B.replace(/^not /,"");else z="must be";var W;if(G(Q," argument"))W="The ".concat(Q," ").concat(z," ").concat(Z(B,"type"));else{var k=X(Q,".")?"property":"argument";W='The "'.concat(Q,'" ').concat(k," ").concat(z," ").concat(Z(B,"type"))}return W+=". Received type ".concat(typeof F),W},TypeError),Y("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),Y("ERR_METHOD_NOT_IMPLEMENTED",function(Q){return"The "+Q+" method is not implemented"}),Y("ERR_STREAM_PREMATURE_CLOSE","Premature close"),Y("ERR_STREAM_DESTROYED",function(Q){return"Cannot call "+Q+" after a stream was destroyed"}),Y("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),Y("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),Y("ERR_STREAM_WRITE_AFTER_END","write after end"),Y("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),Y("ERR_UNKNOWN_ENCODING",function(Q){return"Unknown encoding: "+Q},TypeError),Y("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),g6.codes=U,g6}var x6,UZ;function WQ(){if(UZ)return x6;UZ=1;var $=i2().codes.ERR_INVALID_OPT_VALUE;function U(Z,J,G){return Z.highWaterMark!=null?Z.highWaterMark:J?Z[G]:null}function Y(Z,J,G,X){var Q=U(J,X,G);if(Q!=null){if(!(isFinite(Q)&&Math.floor(Q)===Q)||Q<0){var B=X?G:"highWaterMark";throw new $(B,Q)}return Math.floor(Q)}return Z.objectMode?16:16384}return x6={getHighWaterMark:Y},x6}var f6,YZ;function $X(){if(YZ)return f6;YZ=1,f6=$;function $(Y,Z){if(U("noDeprecation"))return Y;var J=!1;function G(){if(!J){if(U("throwDeprecation"))throw Error(Z);else if(U("traceDeprecation"))console.trace(Z);else console.warn(Z);J=!0}return Y.apply(this,arguments)}return G}function U(Y){try{if(!c0.localStorage)return!1}catch(J){return!1}var Z=c0.localStorage[Y];if(Z==null)return!1;return String(Z).toLowerCase()==="true"}return f6}var h6,ZZ;function HQ(){if(ZZ)return h6;ZZ=1,h6=d;function $(p){var P=this;this.next=null,this.entry=null,this.finish=function(){Z0(P,p)}}var U;d.WritableState=y;var Y={deprecate:$X()},Z=ZQ(),J=o1().Buffer,G=(typeof c0<"u"?c0:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function X(p){return J.from(p)}function Q(p){return J.isBuffer(p)||p instanceof G}var B=wQ(),F=WQ(),z=F.getHighWaterMark,W=i2().codes,k=W.ERR_INVALID_ARG_TYPE,D=W.ERR_METHOD_NOT_IMPLEMENTED,C=W.ERR_MULTIPLE_CALLBACK,H=W.ERR_STREAM_CANNOT_PIPE,O=W.ERR_STREAM_DESTROYED,V=W.ERR_STREAM_NULL_VALUES,j=W.ERR_STREAM_WRITE_AFTER_END,M=W.ERR_UNKNOWN_ENCODING,L=B.errorOrDestroy;R2()(d,Z);function A(){}function y(p,P,R){if(U=U||l2(),p=p||{},typeof R!=="boolean")R=P instanceof U;if(this.objectMode=!!p.objectMode,R)this.objectMode=this.objectMode||!!p.writableObjectMode;this.highWaterMark=z(this,p,"writableHighWaterMark",R),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var c=p.decodeStrings===!1;this.decodeStrings=!c,this.defaultEncoding=p.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(f){$0(P,f)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=p.emitClose!==!1,this.autoDestroy=!!p.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $(this)}y.prototype.getBuffer=function(){var P=this.bufferedRequest,R=[];while(P)R.push(P),P=P.next;return R},function(){try{Object.defineProperty(y.prototype,"buffer",{get:Y.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(p){}}();var g;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function")g=Function.prototype[Symbol.hasInstance],Object.defineProperty(d,Symbol.hasInstance,{value:function(P){if(g.call(this,P))return!0;if(this!==d)return!1;return P&&P._writableState instanceof y}});else g=function(P){return P instanceof this};function d(p){U=U||l2();var P=this instanceof U;if(!P&&!g.call(d,this))return new d(p);if(this._writableState=new y(p,this,P),this.writable=!0,p){if(typeof p.write==="function")this._write=p.write;if(typeof p.writev==="function")this._writev=p.writev;if(typeof p.destroy==="function")this._destroy=p.destroy;if(typeof p.final==="function")this._final=p.final}Z.call(this)}d.prototype.pipe=function(){L(this,new H)};function E(p,P){var R=new j;L(p,R),j0.nextTick(P,R)}function s(p,P,R,c){var f;if(R===null)f=new V;else if(typeof R!=="string"&&!P.objectMode)f=new k("chunk",["string","Buffer"],R);if(f)return L(p,f),j0.nextTick(c,f),!1;return!0}d.prototype.write=function(p,P,R){var c=this._writableState,f=!1,v=!c.objectMode&&Q(p);if(v&&!J.isBuffer(p))p=X(p);if(typeof P==="function")R=P,P=null;if(v)P="buffer";else if(!P)P=c.defaultEncoding;if(typeof R!=="function")R=A;if(c.ending)E(this,R);else if(v||s(this,c,p,R))c.pendingcb++,f=S(this,c,v,p,P,R);return f},d.prototype.cork=function(){this._writableState.corked++},d.prototype.uncork=function(){var p=this._writableState;if(p.corked){if(p.corked--,!p.writing&&!p.corked&&!p.bufferProcessing&&p.bufferedRequest)U0(this,p)}},d.prototype.setDefaultEncoding=function(P){if(typeof P==="string")P=P.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((P+"").toLowerCase())>-1))throw new M(P);return this._writableState.defaultEncoding=P,this},Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function V0(p,P,R){if(!p.objectMode&&p.decodeStrings!==!1&&typeof P==="string")P=J.from(P,R);return P}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function S(p,P,R,c,f,v){if(!R){var b=V0(P,c,f);if(c!==b)R=!0,f="buffer",c=b}var e=P.objectMode?1:c.length;P.length+=e;var I=P.length>5===6)return 2;else if(V>>4===14)return 3;else if(V>>3===30)return 4;return V>>6===2?-1:-2}function X(V,j,M){var L=j.length-1;if(L=0){if(A>0)V.lastNeed=A-1;return A}if(--L=0){if(A>0)V.lastNeed=A-2;return A}if(--L=0){if(A>0)if(A===2)A=0;else V.lastNeed=A-3;return A}return 0}function Q(V,j,M){if((j[0]&192)!==128)return V.lastNeed=0,"�";if(V.lastNeed>1&&j.length>1){if((j[1]&192)!==128)return V.lastNeed=1,"�";if(V.lastNeed>2&&j.length>2){if((j[2]&192)!==128)return V.lastNeed=2,"�"}}}function B(V){var j=this.lastTotal-this.lastNeed,M=Q(this,V);if(M!==void 0)return M;if(this.lastNeed<=V.length)return V.copy(this.lastChar,j,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);V.copy(this.lastChar,j,0,V.length),this.lastNeed-=V.length}function F(V,j){var M=X(this,V,j);if(!this.lastNeed)return V.toString("utf8",j);this.lastTotal=M;var L=V.length-(M-this.lastNeed);return V.copy(this.lastChar,0,L),V.toString("utf8",j,L)}function z(V){var j=V&&V.length?this.write(V):"";if(this.lastNeed)return j+"�";return j}function W(V,j){if((V.length-j)%2===0){var M=V.toString("utf16le",j);if(M){var L=M.charCodeAt(M.length-1);if(L>=55296&&L<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=V[V.length-2],this.lastChar[1]=V[V.length-1],M.slice(0,-1)}return M}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=V[V.length-1],V.toString("utf16le",j,V.length-1)}function k(V){var j=V&&V.length?this.write(V):"";if(this.lastNeed){var M=this.lastTotal-this.lastNeed;return j+this.lastChar.toString("utf16le",0,M)}return j}function D(V,j){var M=(V.length-j)%3;if(M===0)return V.toString("base64",j);if(this.lastNeed=3-M,this.lastTotal=3,M===1)this.lastChar[0]=V[V.length-1];else this.lastChar[0]=V[V.length-2],this.lastChar[1]=V[V.length-1];return V.toString("base64",j,V.length-M)}function C(V){var j=V&&V.length?this.write(V):"";if(this.lastNeed)return j+this.lastChar.toString("base64",0,3-this.lastNeed);return j}function H(V){return V.toString(this.encoding)}function O(V){return V&&V.length?this.write(V):""}return d6}var c6,KZ;function c9(){if(KZ)return c6;KZ=1;var $=i2().codes.ERR_STREAM_PREMATURE_CLOSE;function U(G){var X=!1;return function(){if(X)return;X=!0;for(var Q=arguments.length,B=Array(Q),F=0;F0){if(typeof b!=="string"&&!T.objectMode&&Object.getPrototypeOf(b)!==Z.prototype)b=G(b);if(I)if(T.endEmitted)A(v,new V);else V0(v,T,b,!0);else if(T.ended)A(v,new H);else if(T.destroyed)return!1;else if(T.reading=!1,T.decoder&&!e)if(b=T.decoder.write(b),T.objectMode||b.length!==0)V0(v,T,b,!1);else U0(v,T);else V0(v,T,b,!1)}else if(!I)T.reading=!1,U0(v,T)}return!T.ended&&(T.length=h)v=h;else v--,v|=v>>>1,v|=v>>>2,v|=v>>>4,v|=v>>>8,v|=v>>>16,v++;return v}function a(v,b){if(v<=0||b.length===0&&b.ended)return 0;if(b.objectMode)return 1;if(v!==v)if(b.flowing&&b.length)return b.buffer.head.data.length;else return b.length;if(v>b.highWaterMark)b.highWaterMark=N(v);if(v<=b.length)return v;if(!b.ended)return b.needReadable=!0,0;return b.length}E.prototype.read=function(v){B("read",v),v=parseInt(v,10);var b=this._readableState,e=v;if(v!==0)b.emittedReadable=!1;if(v===0&&b.needReadable&&((b.highWaterMark!==0?b.length>=b.highWaterMark:b.length>0)||b.ended)){if(B("read: emitReadable",b.length,b.ended),b.length===0&&b.ended)R(this);else m(this);return null}if(v=a(v,b),v===0&&b.ended){if(b.length===0)R(this);return null}var I=b.needReadable;if(B("need readable",I),b.length===0||b.length-v0)t=P(v,b);else t=null;if(t===null)b.needReadable=b.length<=b.highWaterMark,v=0;else b.length-=v,b.awaitDrain=0;if(b.length===0){if(!b.ended)b.needReadable=!0;if(e!==v&&b.ended)R(this)}if(t!==null)this.emit("data",t);return t};function $0(v,b){if(B("onEofChunk"),b.ended)return;if(b.decoder){var e=b.decoder.end();if(e&&e.length)b.buffer.push(e),b.length+=b.objectMode?1:e.length}if(b.ended=!0,b.sync)m(v);else if(b.needReadable=!1,!b.emittedReadable)b.emittedReadable=!0,J0(v)}function m(v){var b=v._readableState;if(B("emitReadable",b.needReadable,b.emittedReadable),b.needReadable=!1,!b.emittedReadable)B("emitReadable",b.flowing),b.emittedReadable=!0,j0.nextTick(J0,v)}function J0(v){var b=v._readableState;if(B("emitReadable_",b.destroyed,b.length,b.ended),!b.destroyed&&(b.length||b.ended))v.emit("readable"),b.emittedReadable=!1;b.needReadable=!b.flowing&&!b.ended&&b.length<=b.highWaterMark,p(v)}function U0(v,b){if(!b.readingMore)b.readingMore=!0,j0.nextTick(L0,v,b)}function L0(v,b){while(!b.reading&&!b.ended&&(b.length1&&f(I.pipes,v)!==-1)&&!x)B("false write response, pause",I.awaitDrain),I.awaitDrain++;e.pause()}}function Q0(w0){if(B("onerror",w0),M0(),v.removeListener("error",Q0),U(v,"error")===0)A(v,w0)}g(v,"error",Q0);function q0(){v.removeListener("finish",K0),M0()}v.once("close",q0);function K0(){B("onfinish"),v.removeListener("close",q0),M0()}v.once("finish",K0);function M0(){B("unpipe"),e.unpipe(v)}if(v.emit("pipe",e),!I.flowing)B("pipe resume"),e.resume();return v};function i(v){return function(){var e=v._readableState;if(B("pipeOnDrain",e.awaitDrain),e.awaitDrain)e.awaitDrain--;if(e.awaitDrain===0&&U(v,"data"))e.flowing=!0,p(v)}}E.prototype.unpipe=function(v){var b=this._readableState,e={hasUnpiped:!1};if(b.pipesCount===0)return this;if(b.pipesCount===1){if(v&&v!==b.pipes)return this;if(!v)v=b.pipes;if(b.pipes=null,b.pipesCount=0,b.flowing=!1,v)v.emit("unpipe",this,e);return this}if(!v){var{pipes:I,pipesCount:t}=b;b.pipes=null,b.pipesCount=0,b.flowing=!1;for(var T=0;T0,I.flowing!==!1)this.resume()}else if(v==="readable"){if(!I.endEmitted&&!I.readableListening){if(I.readableListening=I.needReadable=!0,I.flowing=!1,I.emittedReadable=!1,B("on readable",I.length,I.reading),I.length)m(this);else if(!I.reading)j0.nextTick(r,this)}}return e},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(v,b){var e=Y.prototype.removeListener.call(this,v,b);if(v==="readable")j0.nextTick(_,this);return e},E.prototype.removeAllListeners=function(v){var b=Y.prototype.removeAllListeners.apply(this,arguments);if(v==="readable"||v===void 0)j0.nextTick(_,this);return b};function _(v){var b=v._readableState;if(b.readableListening=v.listenerCount("readable")>0,b.resumeScheduled&&!b.paused)b.flowing=!0;else if(v.listenerCount("data")>0)v.resume()}function r(v){B("readable nexttick read 0"),v.read(0)}E.prototype.resume=function(){var v=this._readableState;if(!v.flowing)B("resume"),v.flowing=!v.readableListening,n(this,v);return v.paused=!1,this};function n(v,b){if(!b.resumeScheduled)b.resumeScheduled=!0,j0.nextTick(Z0,v,b)}function Z0(v,b){if(B("resume",b.reading),!b.reading)v.read(0);if(b.resumeScheduled=!1,v.emit("resume"),p(v),b.flowing&&!b.reading)v.read(0)}E.prototype.pause=function(){if(B("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)B("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState.paused=!0,this};function p(v){var b=v._readableState;B("flow",b.flowing);while(b.flowing&&v.read()!==null);}if(E.prototype.wrap=function(v){var b=this,e=this._readableState,I=!1;v.on("end",function(){if(B("wrapped end"),e.decoder&&!e.ended){var K=e.decoder.end();if(K&&K.length)b.push(K)}b.push(null)}),v.on("data",function(K){if(B("wrapped data"),e.decoder)K=e.decoder.write(K);if(e.objectMode&&(K===null||K===void 0))return;else if(!e.objectMode&&(!K||!K.length))return;var q=b.push(K);if(!q)I=!0,v.pause()});for(var t in v)if(this[t]===void 0&&typeof v[t]==="function")this[t]=function(q){return function(){return v[q].apply(v,arguments)}}(t);for(var T=0;T=b.length){if(b.decoder)e=b.buffer.join("");else if(b.buffer.length===1)e=b.buffer.first();else e=b.buffer.concat(b.length);b.buffer.clear()}else e=b.buffer.consume(v,b.decoder);return e}function R(v){var b=v._readableState;if(B("endReadable",b.endEmitted),!b.endEmitted)b.ended=!0,j0.nextTick(c,b,v)}function c(v,b){if(B("endReadableNT",v.endEmitted,v.length),!v.endEmitted&&v.length===0){if(v.endEmitted=!0,b.readable=!1,b.emit("end"),v.autoDestroy){var e=b._writableState;if(!e||e.autoDestroy&&e.finished)b.destroy()}}}if(typeof Symbol==="function")E.from=function(v,b){if(L===void 0)L=ZX();return L(E,v,b)};function f(v,b){for(var e=0,I=v.length;e0;return Q(j,L,A,function(y){if(!O)O=y;if(y)V.forEach(B);if(L)return;V.forEach(B),H(O)})});return D.reduce(F)}return r6=W,r6}var s6,IZ;function m9(){if(IZ)return s6;IZ=1,s6=Y;var $=x9().EventEmitter,U=R2();U(Y,$),Y.Readable=jQ(),Y.Writable=HQ(),Y.Duplex=l2(),Y.Transform=zQ(),Y.PassThrough=QX(),Y.finished=c9(),Y.pipeline=JX(),Y.Stream=Y;function Y(){$.call(this)}return Y.prototype.pipe=function(Z,J){var G=this;function X(D){if(Z.writable){if(Z.write(D)===!1&&G.pause)G.pause()}}G.on("data",X);function Q(){if(G.readable&&G.resume)G.resume()}if(Z.on("drain",Q),!Z._isStdio&&(!J||J.end!==!1))G.on("end",F),G.on("close",z);var B=!1;function F(){if(B)return;B=!0,Z.end()}function z(){if(B)return;if(B=!0,typeof Z.destroy==="function")Z.destroy()}function W(D){if(k(),$.listenerCount(this,"error")===0)throw D}G.on("error",W),Z.on("error",W);function k(){G.removeListener("data",X),Z.removeListener("drain",Q),G.removeListener("end",F),G.removeListener("close",z),G.removeListener("error",W),Z.removeListener("error",W),G.removeListener("end",k),G.removeListener("close",k),Z.removeListener("close",k)}return G.on("end",k),G.on("close",k),Z.on("close",k),Z.emit("pipe",G),Z},s6}var wZ;function GX(){if(wZ)return _8;return wZ=1,function($){(function(U){U.parser=function(P,R){return new Z(P,R)},U.SAXParser=Z,U.SAXStream=z,U.createStream=F,U.MAX_BUFFER_LENGTH=65536;var Y=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];U.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function Z(P,R){if(!(this instanceof Z))return new Z(P,R);var c=this;if(G(c),c.q=c.c="",c.bufferCheckPosition=U.MAX_BUFFER_LENGTH,c.opt=R||{},c.opt.lowercase=c.opt.lowercase||c.opt.lowercasetags,c.looseCase=c.opt.lowercase?"toLowerCase":"toUpperCase",c.tags=[],c.closed=c.closedRoot=c.sawRoot=!1,c.tag=c.error=null,c.strict=!!P,c.noscript=!!(P||c.opt.noscript),c.state=E.BEGIN,c.strictEntities=c.opt.strictEntities,c.ENTITIES=c.strictEntities?Object.create(U.XML_ENTITIES):Object.create(U.ENTITIES),c.attribList=[],c.opt.xmlns)c.ns=Object.create(H);if(c.trackPosition=c.opt.position!==!1,c.trackPosition)c.position=c.line=c.column=0;V0(c,"onready")}if(!Object.create)Object.create=function(P){function R(){}R.prototype=P;var c=new R;return c};if(!Object.keys)Object.keys=function(P){var R=[];for(var c in P)if(P.hasOwnProperty(c))R.push(c);return R};function J(P){var R=Math.max(U.MAX_BUFFER_LENGTH,10),c=0;for(var f=0,v=Y.length;fR)switch(Y[f]){case"textNode":h(P);break;case"cdata":S(P,"oncdata",P.cdata),P.cdata="";break;case"script":S(P,"onscript",P.script),P.script="";break;default:a(P,"Max buffer length exceeded: "+Y[f])}c=Math.max(c,b)}var e=U.MAX_BUFFER_LENGTH-c;P.bufferCheckPosition=e+P.position}function G(P){for(var R=0,c=Y.length;R"||L(P)}function g(P,R){return P.test(R)}function d(P,R){return!g(P,R)}var E=0;U.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},U.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},U.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(U.ENTITIES).forEach(function(P){var R=U.ENTITIES[P],c=typeof R==="number"?String.fromCharCode(R):R;U.ENTITIES[P]=c});for(var s in U.STATE)U.STATE[U.STATE[s]]=s;E=U.STATE;function V0(P,R,c){P[R]&&P[R](c)}function S(P,R,c){if(P.textNode)h(P);V0(P,R,c)}function h(P){if(P.textNode=N(P.opt,P.textNode),P.textNode)V0(P,"ontext",P.textNode);P.textNode=""}function N(P,R){if(P.trim)R=R.trim();if(P.normalize)R=R.replace(/\s+/g," ");return R}function a(P,R){if(h(P),P.trackPosition)R+=` +Line: `+P.line+` +Column: `+P.column+` +Char: `+P.c;return R=Error(R),P.error=R,V0(P,"onerror",R),P}function $0(P){if(P.sawRoot&&!P.closedRoot)m(P,"Unclosed root tag");if(P.state!==E.BEGIN&&P.state!==E.BEGIN_WHITESPACE&&P.state!==E.TEXT)a(P,"Unexpected end");return h(P),P.c="",P.closed=!0,V0(P,"onend"),Z.call(P,P.strict,P.opt),P}function m(P,R){if(typeof P!=="object"||!(P instanceof Z))throw Error("bad call to strictFail");if(P.strict)a(P,R)}function J0(P){if(!P.strict)P.tagName=P.tagName[P.looseCase]();var R=P.tags[P.tags.length-1]||P,c=P.tag={name:P.tagName,attributes:{}};if(P.opt.xmlns)c.ns=R.ns;P.attribList.length=0,S(P,"onopentagstart",c)}function U0(P,R){var c=P.indexOf(":"),f=c<0?["",P]:P.split(":"),v=f[0],b=f[1];if(R&&P==="xmlns")v="xmlns",b="";return{prefix:v,local:b}}function L0(P){if(!P.strict)P.attribName=P.attribName[P.looseCase]();if(P.attribList.indexOf(P.attribName)!==-1||P.tag.attributes.hasOwnProperty(P.attribName)){P.attribName=P.attribValue="";return}if(P.opt.xmlns){var R=U0(P.attribName,!0),c=R.prefix,f=R.local;if(c==="xmlns")if(f==="xml"&&P.attribValue!==D)m(P,"xml: prefix must be bound to "+D+` +Actual: `+P.attribValue);else if(f==="xmlns"&&P.attribValue!==C)m(P,"xmlns: prefix must be bound to "+C+` +Actual: `+P.attribValue);else{var v=P.tag,b=P.tags[P.tags.length-1]||P;if(v.ns===b.ns)v.ns=Object.create(b.ns);v.ns[f]=P.attribValue}P.attribList.push([P.attribName,P.attribValue])}else P.tag.attributes[P.attribName]=P.attribValue,S(P,"onattribute",{name:P.attribName,value:P.attribValue});P.attribName=P.attribValue=""}function i(P,R){if(P.opt.xmlns){var c=P.tag,f=U0(P.tagName);if(c.prefix=f.prefix,c.local=f.local,c.uri=c.ns[f.prefix]||"",c.prefix&&!c.uri)m(P,"Unbound namespace prefix: "+JSON.stringify(P.tagName)),c.uri=f.prefix;var v=P.tags[P.tags.length-1]||P;if(c.ns&&v.ns!==c.ns)Object.keys(c.ns).forEach(function(u){S(P,"onopennamespace",{prefix:u,uri:c.ns[u]})});for(var b=0,e=P.attribList.length;b",P.tagName="",P.state=E.SCRIPT;return}S(P,"onscript",P.script),P.script=""}var R=P.tags.length,c=P.tagName;if(!P.strict)c=c[P.looseCase]();var f=c;while(R--){var v=P.tags[R];if(v.name!==f)m(P,"Unexpected close tag");else break}if(R<0){m(P,"Unmatched closing tag: "+P.tagName),P.textNode+="",P.state=E.TEXT;return}P.tagName=c;var b=P.tags.length;while(b-- >R){var e=P.tag=P.tags.pop();P.tagName=P.tag.name,S(P,"onclosetag",P.tagName);var I={};for(var t in e.ns)I[t]=e.ns[t];var T=P.tags[P.tags.length-1]||P;if(P.opt.xmlns&&e.ns!==T.ns)Object.keys(e.ns).forEach(function(K){var q=e.ns[K];S(P,"onclosenamespace",{prefix:K,uri:q})})}if(R===0)P.closedRoot=!0;P.tagName=P.attribValue=P.attribName="",P.attribList.length=0,P.state=E.TEXT}function r(P){var R=P.entity,c=R.toLowerCase(),f,v="";if(P.ENTITIES[R])return P.ENTITIES[R];if(P.ENTITIES[c])return P.ENTITIES[c];if(R=c,R.charAt(0)==="#")if(R.charAt(1)==="x")R=R.slice(2),f=parseInt(R,16),v=f.toString(16);else R=R.slice(1),f=parseInt(R,10),v=f.toString(10);if(R=R.replace(/^0+/,""),isNaN(f)||v.toLowerCase()!==R)return m(P,"Invalid character entity"),"&"+P.entity+";";return String.fromCodePoint(f)}function n(P,R){if(R==="<")P.state=E.OPEN_WAKA,P.startTagPosition=P.position;else if(!L(R))m(P,"Non-whitespace before first tag."),P.textNode=R,P.state=E.TEXT}function Z0(P,R){var c="";if(R")S(R,"onsgmldeclaration",R.sgmlDecl),R.sgmlDecl="",R.state=E.TEXT;else if(A(f))R.state=E.SGML_DECL_QUOTED,R.sgmlDecl+=f;else R.sgmlDecl+=f;continue;case E.SGML_DECL_QUOTED:if(f===R.q)R.state=E.SGML_DECL,R.q="";R.sgmlDecl+=f;continue;case E.DOCTYPE:if(f===">")R.state=E.TEXT,S(R,"ondoctype",R.doctype),R.doctype=!0;else if(R.doctype+=f,f==="[")R.state=E.DOCTYPE_DTD;else if(A(f))R.state=E.DOCTYPE_QUOTED,R.q=f;continue;case E.DOCTYPE_QUOTED:if(R.doctype+=f,f===R.q)R.q="",R.state=E.DOCTYPE;continue;case E.DOCTYPE_DTD:if(R.doctype+=f,f==="]")R.state=E.DOCTYPE;else if(A(f))R.state=E.DOCTYPE_DTD_QUOTED,R.q=f;continue;case E.DOCTYPE_DTD_QUOTED:if(R.doctype+=f,f===R.q)R.state=E.DOCTYPE_DTD,R.q="";continue;case E.COMMENT:if(f==="-")R.state=E.COMMENT_ENDING;else R.comment+=f;continue;case E.COMMENT_ENDING:if(f==="-"){if(R.state=E.COMMENT_ENDED,R.comment=N(R.opt,R.comment),R.comment)S(R,"oncomment",R.comment);R.comment=""}else R.comment+="-"+f,R.state=E.COMMENT;continue;case E.COMMENT_ENDED:if(f!==">")m(R,"Malformed comment"),R.comment+="--"+f,R.state=E.COMMENT;else R.state=E.TEXT;continue;case E.CDATA:if(f==="]")R.state=E.CDATA_ENDING;else R.cdata+=f;continue;case E.CDATA_ENDING:if(f==="]")R.state=E.CDATA_ENDING_2;else R.cdata+="]"+f,R.state=E.CDATA;continue;case E.CDATA_ENDING_2:if(f===">"){if(R.cdata)S(R,"oncdata",R.cdata);S(R,"onclosecdata"),R.cdata="",R.state=E.TEXT}else if(f==="]")R.cdata+="]";else R.cdata+="]]"+f,R.state=E.CDATA;continue;case E.PROC_INST:if(f==="?")R.state=E.PROC_INST_ENDING;else if(L(f))R.state=E.PROC_INST_BODY;else R.procInstName+=f;continue;case E.PROC_INST_BODY:if(!R.procInstBody&&L(f))continue;else if(f==="?")R.state=E.PROC_INST_ENDING;else R.procInstBody+=f;continue;case E.PROC_INST_ENDING:if(f===">")S(R,"onprocessinginstruction",{name:R.procInstName,body:R.procInstBody}),R.procInstName=R.procInstBody="",R.state=E.TEXT;else R.procInstBody+="?"+f,R.state=E.PROC_INST_BODY;continue;case E.OPEN_TAG:if(g(V,f))R.tagName+=f;else if(J0(R),f===">")i(R);else if(f==="/")R.state=E.OPEN_TAG_SLASH;else{if(!L(f))m(R,"Invalid character in tag name");R.state=E.ATTRIB}continue;case E.OPEN_TAG_SLASH:if(f===">")i(R,!0),_(R);else m(R,"Forward-slash in opening tag not followed by >"),R.state=E.ATTRIB;continue;case E.ATTRIB:if(L(f))continue;else if(f===">")i(R);else if(f==="/")R.state=E.OPEN_TAG_SLASH;else if(g(O,f))R.attribName=f,R.attribValue="",R.state=E.ATTRIB_NAME;else m(R,"Invalid attribute name");continue;case E.ATTRIB_NAME:if(f==="=")R.state=E.ATTRIB_VALUE;else if(f===">")m(R,"Attribute without value"),R.attribValue=R.attribName,L0(R),i(R);else if(L(f))R.state=E.ATTRIB_NAME_SAW_WHITE;else if(g(V,f))R.attribName+=f;else m(R,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if(f==="=")R.state=E.ATTRIB_VALUE;else if(L(f))continue;else if(m(R,"Attribute without value"),R.tag.attributes[R.attribName]="",R.attribValue="",S(R,"onattribute",{name:R.attribName,value:""}),R.attribName="",f===">")i(R);else if(g(O,f))R.attribName=f,R.state=E.ATTRIB_NAME;else m(R,"Invalid attribute name"),R.state=E.ATTRIB;continue;case E.ATTRIB_VALUE:if(L(f))continue;else if(A(f))R.q=f,R.state=E.ATTRIB_VALUE_QUOTED;else m(R,"Unquoted attribute value"),R.state=E.ATTRIB_VALUE_UNQUOTED,R.attribValue=f;continue;case E.ATTRIB_VALUE_QUOTED:if(f!==R.q){if(f==="&")R.state=E.ATTRIB_VALUE_ENTITY_Q;else R.attribValue+=f;continue}L0(R),R.q="",R.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:if(L(f))R.state=E.ATTRIB;else if(f===">")i(R);else if(f==="/")R.state=E.OPEN_TAG_SLASH;else if(g(O,f))m(R,"No whitespace between attributes"),R.attribName=f,R.attribValue="",R.state=E.ATTRIB_NAME;else m(R,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!y(f)){if(f==="&")R.state=E.ATTRIB_VALUE_ENTITY_U;else R.attribValue+=f;continue}if(L0(R),f===">")i(R);else R.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(!R.tagName)if(L(f))continue;else if(d(O,f))if(R.script)R.script+="")_(R);else if(g(V,f))R.tagName+=f;else if(R.script)R.script+="")_(R);else m(R,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var e,I;switch(R.state){case E.TEXT_ENTITY:e=E.TEXT,I="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:e=E.ATTRIB_VALUE_QUOTED,I="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:e=E.ATTRIB_VALUE_UNQUOTED,I="attribValue";break}if(f===";")R[I]+=r(R),R.entity="",R.state=e;else if(g(R.entity.length?M:j,f))R.entity+=f;else m(R,"Invalid character in entity name"),R[I]+="&"+R.entity+f,R.entity="",R.state=e;continue;default:throw Error(R,"Unknown state: "+R.state)}}if(R.position>=R.bufferCheckPosition)J(R);return R}if(!String.fromCodePoint)(function(){var P=String.fromCharCode,R=Math.floor,c=function(){var f=16384,v=[],b,e,I=-1,t=arguments.length;if(!t)return"";var T="";while(++I1114111||R(K)!==K)throw RangeError("Invalid code point: "+K);if(K<=65535)v.push(K);else K-=65536,b=(K>>10)+55296,e=K%1024+56320,v.push(b,e);if(I+1===t||v.length>f)T+=P.apply(null,v),v.length=0}return T};if(Object.defineProperty)Object.defineProperty(String,"fromCodePoint",{value:c,configurable:!0,writable:!0});else String.fromCodePoint=c})()})($)}(_8),_8}var n6,WZ;function l9(){if(WZ)return n6;return WZ=1,n6={isArray:function($){if(Array.isArray)return Array.isArray($);return Object.prototype.toString.call($)==="[object Array]"}},n6}var o6,HZ;function a9(){if(HZ)return o6;HZ=1;var $=l9().isArray;return o6={copyOptions:function(U){var Y,Z={};for(Y in U)if(U.hasOwnProperty(Y))Z[Y]=U[Y];return Z},ensureFlagExists:function(U,Y){if(!(U in Y)||typeof Y[U]!=="boolean")Y[U]=!1},ensureSpacesExists:function(U){if(!("spaces"in U)||typeof U.spaces!=="number"&&typeof U.spaces!=="string")U.spaces=0},ensureAlwaysArrayExists:function(U){if(!("alwaysArray"in U)||typeof U.alwaysArray!=="boolean"&&!$(U.alwaysArray))U.alwaysArray=!1},ensureKeyExists:function(U,Y){if(!(U+"Key"in Y)||typeof Y[U+"Key"]!=="string")Y[U+"Key"]=Y.compact?"_"+U:U},checkFnExists:function(U,Y){return U+"Fn"in Y}},o6}var t6,jZ;function FQ(){if(jZ)return t6;jZ=1;var $=GX(),U=a9(),Y=l9().isArray,Z,J;function G(V){return Z=U.copyOptions(V),U.ensureFlagExists("ignoreDeclaration",Z),U.ensureFlagExists("ignoreInstruction",Z),U.ensureFlagExists("ignoreAttributes",Z),U.ensureFlagExists("ignoreText",Z),U.ensureFlagExists("ignoreComment",Z),U.ensureFlagExists("ignoreCdata",Z),U.ensureFlagExists("ignoreDoctype",Z),U.ensureFlagExists("compact",Z),U.ensureFlagExists("alwaysChildren",Z),U.ensureFlagExists("addParent",Z),U.ensureFlagExists("trim",Z),U.ensureFlagExists("nativeType",Z),U.ensureFlagExists("nativeTypeAttributes",Z),U.ensureFlagExists("sanitize",Z),U.ensureFlagExists("instructionHasAttributes",Z),U.ensureFlagExists("captureSpacesBetweenElements",Z),U.ensureAlwaysArrayExists(Z),U.ensureKeyExists("declaration",Z),U.ensureKeyExists("instruction",Z),U.ensureKeyExists("attributes",Z),U.ensureKeyExists("text",Z),U.ensureKeyExists("comment",Z),U.ensureKeyExists("cdata",Z),U.ensureKeyExists("doctype",Z),U.ensureKeyExists("type",Z),U.ensureKeyExists("name",Z),U.ensureKeyExists("elements",Z),U.ensureKeyExists("parent",Z),U.checkFnExists("doctype",Z),U.checkFnExists("instruction",Z),U.checkFnExists("cdata",Z),U.checkFnExists("comment",Z),U.checkFnExists("text",Z),U.checkFnExists("instructionName",Z),U.checkFnExists("elementName",Z),U.checkFnExists("attributeName",Z),U.checkFnExists("attributeValue",Z),U.checkFnExists("attributes",Z),Z}function X(V){var j=Number(V);if(!isNaN(j))return j;var M=V.toLowerCase();if(M==="true")return!0;else if(M==="false")return!1;return V}function Q(V,j){var M;if(Z.compact){if(!J[Z[V+"Key"]]&&(Y(Z.alwaysArray)?Z.alwaysArray.indexOf(Z[V+"Key"])!==-1:Z.alwaysArray))J[Z[V+"Key"]]=[];if(J[Z[V+"Key"]]&&!Y(J[Z[V+"Key"]]))J[Z[V+"Key"]]=[J[Z[V+"Key"]]];if(V+"Fn"in Z&&typeof j==="string")j=Z[V+"Fn"](j,J);if(V==="instruction"&&(("instructionFn"in Z)||("instructionNameFn"in Z))){for(M in j)if(j.hasOwnProperty(M))if("instructionFn"in Z)j[M]=Z.instructionFn(j[M],M,J);else{var L=j[M];delete j[M],j[Z.instructionNameFn(M,L,J)]=L}}if(Y(J[Z[V+"Key"]]))J[Z[V+"Key"]].push(j);else J[Z[V+"Key"]]=j}else{if(!J[Z.elementsKey])J[Z.elementsKey]=[];var A={};if(A[Z.typeKey]=V,V==="instruction"){for(M in j)if(j.hasOwnProperty(M))break;if(A[Z.nameKey]="instructionNameFn"in Z?Z.instructionNameFn(M,j,J):M,Z.instructionHasAttributes){if(A[Z.attributesKey]=j[M][Z.attributesKey],"instructionFn"in Z)A[Z.attributesKey]=Z.instructionFn(A[Z.attributesKey],M,J)}else{if("instructionFn"in Z)j[M]=Z.instructionFn(j[M],M,J);A[Z.instructionKey]=j[M]}}else{if(V+"Fn"in Z)j=Z[V+"Fn"](j,J);A[Z[V+"Key"]]=j}if(Z.addParent)A[Z.parentKey]=J;J[Z.elementsKey].push(A)}}function B(V){if("attributesFn"in Z&&V)V=Z.attributesFn(V,J);if((Z.trim||("attributeValueFn"in Z)||("attributeNameFn"in Z)||Z.nativeTypeAttributes)&&V){var j;for(j in V)if(V.hasOwnProperty(j)){if(Z.trim)V[j]=V[j].trim();if(Z.nativeTypeAttributes)V[j]=X(V[j]);if("attributeValueFn"in Z)V[j]=Z.attributeValueFn(V[j],j,J);if("attributeNameFn"in Z){var M=V[j];delete V[j],V[Z.attributeNameFn(j,V[j],J)]=M}}}return V}function F(V){var j={};if(V.body&&(V.name.toLowerCase()==="xml"||Z.instructionHasAttributes)){var M=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g,L;while((L=M.exec(V.body))!==null)j[L[1]]=L[2]||L[3]||L[4];j=B(j)}if(V.name.toLowerCase()==="xml"){if(Z.ignoreDeclaration)return;if(J[Z.declarationKey]={},Object.keys(j).length)J[Z.declarationKey][Z.attributesKey]=j;if(Z.addParent)J[Z.declarationKey][Z.parentKey]=J}else{if(Z.ignoreInstruction)return;if(Z.trim)V.body=V.body.trim();var A={};if(Z.instructionHasAttributes&&Object.keys(j).length)A[V.name]={},A[V.name][Z.attributesKey]=j;else A[V.name]=V.body;Q("instruction",A)}}function z(V,j){var M;if(typeof V==="object")j=V.attributes,V=V.name;if(j=B(j),"elementNameFn"in Z)V=Z.elementNameFn(V,J);if(Z.compact){if(M={},!Z.ignoreAttributes&&j&&Object.keys(j).length){M[Z.attributesKey]={};var L;for(L in j)if(j.hasOwnProperty(L))M[Z.attributesKey][L]=j[L]}if(!(V in J)&&(Y(Z.alwaysArray)?Z.alwaysArray.indexOf(V)!==-1:Z.alwaysArray))J[V]=[];if(J[V]&&!Y(J[V]))J[V]=[J[V]];if(Y(J[V]))J[V].push(M);else J[V]=M}else{if(!J[Z.elementsKey])J[Z.elementsKey]=[];if(M={},M[Z.typeKey]="element",M[Z.nameKey]=V,!Z.ignoreAttributes&&j&&Object.keys(j).length)M[Z.attributesKey]=j;if(Z.alwaysChildren)M[Z.elementsKey]=[];J[Z.elementsKey].push(M)}M[Z.parentKey]=J,J=M}function W(V){if(Z.ignoreText)return;if(!V.trim()&&!Z.captureSpacesBetweenElements)return;if(Z.trim)V=V.trim();if(Z.nativeType)V=X(V);if(Z.sanitize)V=V.replace(/&/g,"&").replace(//g,">");Q("text",V)}function k(V){if(Z.ignoreComment)return;if(Z.trim)V=V.trim();Q("comment",V)}function D(V){var j=J[Z.parentKey];if(!Z.addParent)delete J[Z.parentKey];J=j}function C(V){if(Z.ignoreCdata)return;if(Z.trim)V=V.trim();Q("cdata",V)}function H(V){if(Z.ignoreDoctype)return;if(V=V.replace(/^ /,""),Z.trim)V=V.trim();Q("doctype",V)}function O(V){V.note=V}return t6=function(V,j){var M=$.parser(!0,{}),L={};if(J=L,Z=G(j),M.opt={strictEntities:!0},M.onopentag=z,M.ontext=W,M.oncomment=k,M.onclosetag=D,M.onerror=O,M.oncdata=C,M.ondoctype=H,M.onprocessinginstruction=F,M.write(V).close(),L[Z.elementsKey]){var A=L[Z.elementsKey];delete L[Z.elementsKey],L[Z.elementsKey]=A,delete L.text}return L},t6}var e6,zZ;function KX(){if(zZ)return e6;zZ=1;var $=a9(),U=FQ();function Y(Z){var J=$.copyOptions(Z);return $.ensureSpacesExists(J),J}return e6=function(Z,J){var G,X,Q,B;if(G=Y(J),X=U(Z,G),B="compact"in G&&G.compact?"_parent":"parent","addParent"in G&&G.addParent)Q=JSON.stringify(X,function(F,z){return F===B?"_":z},G.spaces);else Q=JSON.stringify(X,null,G.spaces);return Q.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")},e6}var $9,FZ;function NQ(){if(FZ)return $9;FZ=1;var $=a9(),U=l9().isArray,Y,Z;function J(M){var L=$.copyOptions(M);if($.ensureFlagExists("ignoreDeclaration",L),$.ensureFlagExists("ignoreInstruction",L),$.ensureFlagExists("ignoreAttributes",L),$.ensureFlagExists("ignoreText",L),$.ensureFlagExists("ignoreComment",L),$.ensureFlagExists("ignoreCdata",L),$.ensureFlagExists("ignoreDoctype",L),$.ensureFlagExists("compact",L),$.ensureFlagExists("indentText",L),$.ensureFlagExists("indentCdata",L),$.ensureFlagExists("indentAttributes",L),$.ensureFlagExists("indentInstruction",L),$.ensureFlagExists("fullTagEmptyElement",L),$.ensureFlagExists("noQuotesForNativeAttributes",L),$.ensureSpacesExists(L),typeof L.spaces==="number")L.spaces=Array(L.spaces+1).join(" ");return $.ensureKeyExists("declaration",L),$.ensureKeyExists("instruction",L),$.ensureKeyExists("attributes",L),$.ensureKeyExists("text",L),$.ensureKeyExists("comment",L),$.ensureKeyExists("cdata",L),$.ensureKeyExists("doctype",L),$.ensureKeyExists("type",L),$.ensureKeyExists("name",L),$.ensureKeyExists("elements",L),$.checkFnExists("doctype",L),$.checkFnExists("instruction",L),$.checkFnExists("cdata",L),$.checkFnExists("comment",L),$.checkFnExists("text",L),$.checkFnExists("instructionName",L),$.checkFnExists("elementName",L),$.checkFnExists("attributeName",L),$.checkFnExists("attributeValue",L),$.checkFnExists("attributes",L),$.checkFnExists("fullTagEmptyElement",L),L}function G(M,L,A){return(!A&&M.spaces?` +`:"")+Array(L+1).join(M.spaces)}function X(M,L,A){if(L.ignoreAttributes)return"";if("attributesFn"in L)M=L.attributesFn(M,Z,Y);var y,g,d,E,s=[];for(y in M)if(M.hasOwnProperty(y)&&M[y]!==null&&M[y]!==void 0)E=L.noQuotesForNativeAttributes&&typeof M[y]!=="string"?"":'"',g=""+M[y],g=g.replace(/"/g,"""),d="attributeNameFn"in L?L.attributeNameFn(y,g,Z,Y):y,s.push(L.spaces&&L.indentAttributes?G(L,A+1,!1):" "),s.push(d+"="+E+("attributeValueFn"in L?L.attributeValueFn(g,y,Z,Y):g)+E);if(M&&Object.keys(M).length&&L.spaces&&L.indentAttributes)s.push(G(L,A,!1));return s.join("")}function Q(M,L,A){return Y=M,Z="xml",L.ignoreDeclaration?"":""}function B(M,L,A){if(L.ignoreInstruction)return"";var y;for(y in M)if(M.hasOwnProperty(y))break;var g="instructionNameFn"in L?L.instructionNameFn(y,M[y],Z,Y):y;if(typeof M[y]==="object")return Y=M,Z=g,"";else{var d=M[y]?M[y]:"";if("instructionFn"in L)d=L.instructionFn(d,y,Z,Y);return""}}function F(M,L){return L.ignoreComment?"":""}function z(M,L){return L.ignoreCdata?"":"","]]]]>"))+"]]>"}function W(M,L){return L.ignoreDoctype?"":""}function k(M,L){if(L.ignoreText)return"";return M=""+M,M=M.replace(/&/g,"&"),M=M.replace(/&/g,"&").replace(//g,">"),"textFn"in L?L.textFn(M,Z,Y):M}function D(M,L){var A;if(M.elements&&M.elements.length)for(A=0;A"),M[L.elementsKey]&&M[L.elementsKey].length)y.push(H(M[L.elementsKey],L,A+1)),Y=M,Z=M.name;y.push(L.spaces&&D(M,L)?` +`+Array(A+1).join(L.spaces):""),y.push("")}else y.push("/>");return y.join("")}function H(M,L,A,y){return M.reduce(function(g,d){var E=G(L,A,y&&!g);switch(d.type){case"element":return g+E+C(d,L,A);case"comment":return g+E+F(d[L.commentKey],L);case"doctype":return g+E+W(d[L.doctypeKey],L);case"cdata":return g+(L.indentCdata?E:"")+z(d[L.cdataKey],L);case"text":return g+(L.indentText?E:"")+k(d[L.textKey],L);case"instruction":var s={};return s[d[L.nameKey]]=d[L.attributesKey]?d:d[L.instructionKey],g+(L.indentInstruction?E:"")+B(s,L,A)}},"")}function O(M,L,A){var y;for(y in M)if(M.hasOwnProperty(y))switch(y){case L.parentKey:case L.attributesKey:break;case L.textKey:if(L.indentText||A)return!0;break;case L.cdataKey:if(L.indentCdata||A)return!0;break;case L.instructionKey:if(L.indentInstruction||A)return!0;break;case L.doctypeKey:case L.commentKey:return!0;default:return!0}return!1}function V(M,L,A,y,g){Y=M,Z=L;var d="elementNameFn"in A?A.elementNameFn(L,M):L;if(typeof M>"u"||M===null||M==="")return"fullTagEmptyElementFn"in A&&A.fullTagEmptyElementFn(L,M)||A.fullTagEmptyElement?"<"+d+">":"<"+d+"/>";var E=[];if(L){if(E.push("<"+d),typeof M!=="object")return E.push(">"+k(M,A)+""),E.join("");if(M[A.attributesKey])E.push(X(M[A.attributesKey],A,y));var s=O(M,A,!0)||M[A.attributesKey]&&M[A.attributesKey]["xml:space"]==="preserve";if(!s)if("fullTagEmptyElementFn"in A)s=A.fullTagEmptyElementFn(L,M);else s=A.fullTagEmptyElement;if(s)E.push(">");else return E.push("/>"),E.join("")}if(E.push(j(M,A,y+1,!1)),Y=M,Z=L,L)E.push((g?G(A,y,!1):"")+"");return E.join("")}function j(M,L,A,y){var g,d,E,s=[];for(d in M)if(M.hasOwnProperty(d)){E=U(M[d])?M[d]:[M[d]];for(g=0;g{switch($.type){case void 0:case"element":let U=new p9($.name,$.attributes),Y=$.elements||[];for(let Z of Y){let J=U8(Z);if(J!==void 0)U.push(J)}return U;case"text":return $.text;default:return}};class RQ extends I0{}class p9 extends o{static fromXmlString($){let U=$8.xml2js($,{compact:!1});return U8(U)}constructor($,U){super($);if(U)this.root.push(new RQ(U))}push($){this.root.push($)}}class i9 extends o{constructor($){super("");this._attr=$}prepForXml($){return{_attr:this._attr}}}var VX="";class Y8 extends o{constructor($,U){super($);if(U)this.root=U.root}}var S0=($)=>{if(isNaN($))throw Error(`Invalid value '${$}' specified. Must be an integer.`);return Math.floor($)},W1=($)=>{let U=S0($);if(U<0)throw Error(`Invalid value '${$}' specified. Must be a positive integer.`);return U},Z8=($,U)=>{let Y=U*2;if($.length!==Y||isNaN(Number(`0x${$}`)))throw Error(`Invalid hex value '${$}'. Expected ${Y} digit hex value`);return $},BX=($)=>Z8($,4),DQ=($)=>Z8($,2),D9=($)=>Z8($,1),H1=($)=>{let U=$.slice(-2),Y=$.substring(0,$.length-2);return`${Number(Y)}${U}`},r9=($)=>{let U=H1($);if(parseFloat(U)<0)throw Error(`Invalid value '${U}' specified. Expected a positive number.`);return U},S2=($)=>{if($==="auto")return $;let U=$.charAt(0)==="#"?$.substring(1):$;return Z8(U,3)},e0=($)=>typeof $==="string"?H1($):S0($),AQ=($)=>typeof $==="string"?r9($):W1($),LX=($)=>typeof $==="string"?H1($):S0($),T0=($)=>typeof $==="string"?r9($):W1($),PQ=($)=>{let U=$.substring(0,$.length-1);return`${Number(U)}%`},s9=($)=>{if(typeof $==="number")return S0($);if($.slice(-1)==="%")return PQ($);return H1($)},TQ=W1,CQ=W1,OQ=($)=>$.toISOString();class X0 extends o{constructor($,U=!0){super($);if(U!==!0)this.root.push(new O0({val:U}))}}class q1 extends o{constructor($,U){super($);this.root.push(new O0({val:AQ(U)}))}}class k0 extends o{}class Y2 extends o{constructor($,U){super($);this.root.push(new O0({val:U}))}}var u2=($,U)=>new B0({name:$,attributes:{value:{key:"w:val",value:U}}});class k2 extends o{constructor($,U){super($);this.root.push(new O0({val:U}))}}class kQ extends o{constructor($,U){super($);this.root.push(new O0({val:U}))}}class L2 extends o{constructor($,U){super($);this.root.push(U)}}class B0 extends o{constructor({name:$,attributes:U,children:Y}){super($);if(U)this.root.push(new n1(U));if(Y)this.root.push(...Y)}}var m0={START:"start",CENTER:"center",END:"end",BOTH:"both",MEDIUM_KASHIDA:"mediumKashida",DISTRIBUTE:"distribute",NUM_TAB:"numTab",HIGH_KASHIDA:"highKashida",LOW_KASHIDA:"lowKashida",THAI_DISTRIBUTE:"thaiDistribute",LEFT:"left",RIGHT:"right",JUSTIFIED:"both"},n9=($)=>new B0({name:"w:jc",attributes:{val:{key:"w:val",value:$}}}),N0=($,{color:U,size:Y,space:Z,style:J})=>new B0({name:$,attributes:{style:{key:"w:val",value:J},color:{key:"w:color",value:U===void 0?void 0:S2(U)},size:{key:"w:sz",value:Y===void 0?void 0:TQ(Y)},space:{key:"w:space",value:Z===void 0?void 0:CQ(Z)}}}),Q8={SINGLE:"single",DASH_DOT_STROKED:"dashDotStroked",DASHED:"dashed",DASH_SMALL_GAP:"dashSmallGap",DOT_DASH:"dotDash",DOT_DOT_DASH:"dotDotDash",DOTTED:"dotted",DOUBLE:"double",DOUBLE_WAVE:"doubleWave",INSET:"inset",NIL:"nil",NONE:"none",OUTSET:"outset",THICK:"thick",THICK_THIN_LARGE_GAP:"thickThinLargeGap",THICK_THIN_MEDIUM_GAP:"thickThinMediumGap",THICK_THIN_SMALL_GAP:"thickThinSmallGap",THIN_THICK_LARGE_GAP:"thinThickLargeGap",THIN_THICK_MEDIUM_GAP:"thinThickMediumGap",THIN_THICK_SMALL_GAP:"thinThickSmallGap",THIN_THICK_THIN_LARGE_GAP:"thinThickThinLargeGap",THIN_THICK_THIN_MEDIUM_GAP:"thinThickThinMediumGap",THIN_THICK_THIN_SMALL_GAP:"thinThickThinSmallGap",THREE_D_EMBOSS:"threeDEmboss",THREE_D_ENGRAVE:"threeDEngrave",TRIPLE:"triple",WAVE:"wave"};class o9 extends Q2{constructor($){super("w:pBdr");if($.top)this.root.push(N0("w:top",$.top));if($.bottom)this.root.push(N0("w:bottom",$.bottom));if($.left)this.root.push(N0("w:left",$.left));if($.right)this.root.push(N0("w:right",$.right));if($.between)this.root.push(N0("w:between",$.between))}}class t9 extends o{constructor(){super("w:pBdr");let $=N0("w:bottom",{color:"auto",space:1,style:Q8.SINGLE,size:6});this.root.push($)}}var EQ=({start:$,end:U,left:Y,right:Z,hanging:J,firstLine:G})=>new B0({name:"w:ind",attributes:{start:{key:"w:start",value:$===void 0?void 0:e0($)},end:{key:"w:end",value:U===void 0?void 0:e0(U)},left:{key:"w:left",value:Y===void 0?void 0:e0(Y)},right:{key:"w:right",value:Z===void 0?void 0:e0(Z)},hanging:{key:"w:hanging",value:J===void 0?void 0:T0(J)},firstLine:{key:"w:firstLine",value:G===void 0?void 0:T0(G)}}}),SQ=()=>new B0({name:"w:br"}),e9={BEGIN:"begin",END:"end",SEPARATE:"separate"},$$=($,U)=>new B0({name:"w:fldChar",attributes:{type:{key:"w:fldCharType",value:$},dirty:{key:"w:dirty",value:U}}}),$2=($)=>$$(e9.BEGIN,$),I2=($)=>$$(e9.SEPARATE,$),U2=($)=>$$(e9.END,$),MX={CENTER:"center",INSIDE:"inside",LEFT:"left",OUTSIDE:"outside",RIGHT:"right"},IX={BOTTOM:"bottom",CENTER:"center",INSIDE:"inside",OUTSIDE:"outside",TOP:"top"},wX={DECIMAL:"decimal",UPPER_ROMAN:"upperRoman",LOWER_ROMAN:"lowerRoman",UPPER_LETTER:"upperLetter",LOWER_LETTER:"lowerLetter",ORDINAL:"ordinal",CARDINAL_TEXT:"cardinalText",ORDINAL_TEXT:"ordinalText",HEX:"hex",CHICAGO:"chicago",IDEOGRAPH_DIGITAL:"ideographDigital",JAPANESE_COUNTING:"japaneseCounting",AIUEO:"aiueo",IROHA:"iroha",DECIMAL_FULL_WIDTH:"decimalFullWidth",DECIMAL_HALF_WIDTH:"decimalHalfWidth",JAPANESE_LEGAL:"japaneseLegal",JAPANESE_DIGITAL_TEN_THOUSAND:"japaneseDigitalTenThousand",DECIMAL_ENCLOSED_CIRCLE:"decimalEnclosedCircle",DECIMAL_FULL_WIDTH_2:"decimalFullWidth2",AIUEO_FULL_WIDTH:"aiueoFullWidth",IROHA_FULL_WIDTH:"irohaFullWidth",DECIMAL_ZERO:"decimalZero",BULLET:"bullet",GANADA:"ganada",CHOSUNG:"chosung",DECIMAL_ENCLOSED_FULL_STOP:"decimalEnclosedFullstop",DECIMAL_ENCLOSED_PAREN:"decimalEnclosedParen",DECIMAL_ENCLOSED_CIRCLE_CHINESE:"decimalEnclosedCircleChinese",IDEOGRAPH_ENCLOSED_CIRCLE:"ideographEnclosedCircle",IDEOGRAPH_TRADITIONAL:"ideographTraditional",IDEOGRAPH_ZODIAC:"ideographZodiac",IDEOGRAPH_ZODIAC_TRADITIONAL:"ideographZodiacTraditional",TAIWANESE_COUNTING:"taiwaneseCounting",IDEOGRAPH_LEGAL_TRADITIONAL:"ideographLegalTraditional",TAIWANESE_COUNTING_THOUSAND:"taiwaneseCountingThousand",TAIWANESE_DIGITAL:"taiwaneseDigital",CHINESE_COUNTING:"chineseCounting",CHINESE_LEGAL_SIMPLIFIED:"chineseLegalSimplified",CHINESE_COUNTING_TEN_THOUSAND:"chineseCountingThousand",KOREAN_DIGITAL:"koreanDigital",KOREAN_COUNTING:"koreanCounting",KOREAN_LEGAL:"koreanLegal",KOREAN_DIGITAL_2:"koreanDigital2",VIETNAMESE_COUNTING:"vietnameseCounting",RUSSIAN_LOWER:"russianLower",RUSSIAN_UPPER:"russianUpper",NONE:"none",NUMBER_IN_DASH:"numberInDash",HEBREW_1:"hebrew1",HEBREW_2:"hebrew2",ARABIC_ALPHA:"arabicAlpha",ARABIC_ABJAD:"arabicAbjad",HINDI_VOWELS:"hindiVowels",HINDI_CONSONANTS:"hindiConsonants",HINDI_NUMBERS:"hindiNumbers",HINDI_COUNTING:"hindiCounting",THAI_LETTERS:"thaiLetters",THAI_NUMBERS:"thaiNumbers",THAI_COUNTING:"thaiCounting",BAHT_TEXT:"bahtText",DOLLAR_TEXT:"dollarText"},g0={DEFAULT:"default",PRESERVE:"preserve"};class x0 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{space:"xml:space"})}}class vQ extends o{constructor(){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("PAGE")}}class _Q extends o{constructor(){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("NUMPAGES")}}class yQ extends o{constructor(){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("SECTIONPAGES")}}class bQ extends o{constructor(){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("SECTION")}}var j1=({fill:$,color:U,type:Y})=>new B0({name:"w:shd",attributes:{fill:{key:"w:fill",value:$===void 0?void 0:S2($)},color:{key:"w:color",value:U===void 0?void 0:S2(U)},type:{key:"w:val",value:Y}}}),WX={CLEAR:"clear",DIAGONAL_CROSS:"diagCross",DIAGONAL_STRIPE:"diagStripe",HORIZONTAL_CROSS:"horzCross",HORIZONTAL_STRIPE:"horzStripe",NIL:"nil",PERCENT_5:"pct5",PERCENT_10:"pct10",PERCENT_12:"pct12",PERCENT_15:"pct15",PERCENT_20:"pct20",PERCENT_25:"pct25",PERCENT_30:"pct30",PERCENT_35:"pct35",PERCENT_37:"pct37",PERCENT_40:"pct40",PERCENT_45:"pct45",PERCENT_50:"pct50",PERCENT_55:"pct55",PERCENT_60:"pct60",PERCENT_62:"pct62",PERCENT_65:"pct65",PERCENT_70:"pct70",PERCENT_75:"pct75",PERCENT_80:"pct80",PERCENT_85:"pct85",PERCENT_87:"pct87",PERCENT_90:"pct90",PERCENT_95:"pct95",REVERSE_DIAGONAL_STRIPE:"reverseDiagStripe",SOLID:"solid",THIN_DIAGONAL_CROSS:"thinDiagCross",THIN_DIAGONAL_STRIPE:"thinDiagStripe",THIN_HORIZONTAL_CROSS:"thinHorzCross",THIN_REVERSE_DIAGONAL_STRIPE:"thinReverseDiagStripe",THIN_VERTICAL_STRIPE:"thinVertStripe",VERTICAL_STRIPE:"vertStripe"};class _0 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id",author:"w:author",date:"w:date"})}}class gQ extends o{constructor($){super("w:del");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}class xQ extends o{constructor($){super("w:ins");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}var U$={DOT:"dot"},Y$=($=U$.DOT)=>new B0({name:"w:em",attributes:{val:{key:"w:val",value:$}}}),HX=()=>Y$(U$.DOT);class fQ extends o{constructor($){super("w:spacing");this.root.push(new O0({val:e0($)}))}}class hQ extends o{constructor($){super("w:color");this.root.push(new O0({val:S2($)}))}}class uQ extends o{constructor($){super("w:highlight");this.root.push(new O0({val:$}))}}class dQ extends o{constructor($){super("w:highlightCs");this.root.push(new O0({val:$}))}}var jX=($)=>new B0({name:"w:lang",attributes:{value:{key:"w:val",value:$.value},eastAsia:{key:"w:eastAsia",value:$.eastAsia},bidirectional:{key:"w:bidi",value:$.bidirectional}}}),g1=($,U)=>{if(typeof $==="string"){let Z=$;return new B0({name:"w:rFonts",attributes:{ascii:{key:"w:ascii",value:Z},cs:{key:"w:cs",value:Z},eastAsia:{key:"w:eastAsia",value:Z},hAnsi:{key:"w:hAnsi",value:Z},hint:{key:"w:hint",value:U}}})}let Y=$;return new B0({name:"w:rFonts",attributes:{ascii:{key:"w:ascii",value:Y.ascii},cs:{key:"w:cs",value:Y.cs},eastAsia:{key:"w:eastAsia",value:Y.eastAsia},hAnsi:{key:"w:hAnsi",value:Y.hAnsi},hint:{key:"w:hint",value:Y.hint}}})},cQ=($)=>new B0({name:"w:vertAlign",attributes:{val:{key:"w:val",value:$}}}),zX=()=>cQ("superscript"),FX=()=>cQ("subscript"),Z$={SINGLE:"single",WORDS:"words",DOUBLE:"double",THICK:"thick",DOTTED:"dotted",DOTTEDHEAVY:"dottedHeavy",DASH:"dash",DASHEDHEAVY:"dashedHeavy",DASHLONG:"dashLong",DASHLONGHEAVY:"dashLongHeavy",DOTDASH:"dotDash",DASHDOTHEAVY:"dashDotHeavy",DOTDOTDASH:"dotDotDash",DASHDOTDOTHEAVY:"dashDotDotHeavy",WAVE:"wave",WAVYHEAVY:"wavyHeavy",WAVYDOUBLE:"wavyDouble",NONE:"none"},mQ=($=Z$.SINGLE,U)=>new B0({name:"w:u",attributes:{val:{key:"w:val",value:$},color:{key:"w:color",value:U===void 0?void 0:S2(U)}}}),NX={BLINK_BACKGROUND:"blinkBackground",LIGHTS:"lights",ANTS_BLACK:"antsBlack",ANTS_RED:"antsRed",SHIMMER:"shimmer",SPARKLE:"sparkle",NONE:"none"},RX={BLACK:"black",BLUE:"blue",CYAN:"cyan",DARK_BLUE:"darkBlue",DARK_CYAN:"darkCyan",DARK_GRAY:"darkGray",DARK_GREEN:"darkGreen",DARK_MAGENTA:"darkMagenta",DARK_RED:"darkRed",DARK_YELLOW:"darkYellow",GREEN:"green",LIGHT_GRAY:"lightGray",MAGENTA:"magenta",NONE:"none",RED:"red",WHITE:"white",YELLOW:"yellow"};class J2 extends Q2{constructor($){var U,Y;super("w:rPr");if(!$)return;if($.style)this.push(new Y2("w:rStyle",$.style));if($.font)if(typeof $.font==="string")this.push(g1($.font));else if("name"in $.font)this.push(g1($.font.name,$.font.hint));else this.push(g1($.font));if($.bold!==void 0)this.push(new X0("w:b",$.bold));if($.boldComplexScript===void 0&&$.bold!==void 0||$.boldComplexScript)this.push(new X0("w:bCs",(U=$.boldComplexScript)!=null?U:$.bold));if($.italics!==void 0)this.push(new X0("w:i",$.italics));if($.italicsComplexScript===void 0&&$.italics!==void 0||$.italicsComplexScript)this.push(new X0("w:iCs",(Y=$.italicsComplexScript)!=null?Y:$.italics));if($.smallCaps!==void 0)this.push(new X0("w:smallCaps",$.smallCaps));else if($.allCaps!==void 0)this.push(new X0("w:caps",$.allCaps));if($.strike!==void 0)this.push(new X0("w:strike",$.strike));if($.doubleStrike!==void 0)this.push(new X0("w:dstrike",$.doubleStrike));if($.emboss!==void 0)this.push(new X0("w:emboss",$.emboss));if($.imprint!==void 0)this.push(new X0("w:imprint",$.imprint));if($.noProof!==void 0)this.push(new X0("w:noProof",$.noProof));if($.snapToGrid!==void 0)this.push(new X0("w:snapToGrid",$.snapToGrid));if($.vanish)this.push(new X0("w:vanish",$.vanish));if($.color)this.push(new hQ($.color));if($.characterSpacing)this.push(new fQ($.characterSpacing));if($.scale!==void 0)this.push(new k2("w:w",$.scale));if($.kern)this.push(new q1("w:kern",$.kern));if($.position)this.push(new Y2("w:position",$.position));if($.size!==void 0)this.push(new q1("w:sz",$.size));let Z=$.sizeComplexScript===void 0||$.sizeComplexScript===!0?$.size:$.sizeComplexScript;if(Z)this.push(new q1("w:szCs",Z));if($.highlight)this.push(new uQ($.highlight));let J=$.highlightComplexScript===void 0||$.highlightComplexScript===!0?$.highlight:$.highlightComplexScript;if(J)this.push(new dQ(J));if($.underline)this.push(mQ($.underline.type,$.underline.color));if($.effect)this.push(new Y2("w:effect",$.effect));if($.border)this.push(N0("w:bdr",$.border));if($.shading)this.push(j1($.shading));if($.subScript)this.push(FX());if($.superScript)this.push(zX());if($.rightToLeft!==void 0)this.push(new X0("w:rtl",$.rightToLeft));if($.emphasisMark)this.push(Y$($.emphasisMark.type));if($.language)this.push(jX($.language));if($.specVanish)this.push(new X0("w:specVanish",$.vanish));if($.math)this.push(new X0("w:oMath",$.math));if($.revision)this.push(new J$($.revision))}push($){this.root.push($)}}class Q$ extends J2{constructor($){super($);if($==null?void 0:$.insertion)this.push(new xQ($.insertion));if($==null?void 0:$.deletion)this.push(new gQ($.deletion))}}class J$ extends o{constructor($){super("w:rPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.addChildElement(new J2($))}}class a2 extends o{constructor($){var U;super("w:t");if(typeof $==="string")this.root.push(new x0({space:g0.PRESERVE})),this.root.push($);else this.root.push(new x0({space:(U=$.space)!=null?U:g0.DEFAULT})),this.root.push($.text)}}var N2={CURRENT:"CURRENT",TOTAL_PAGES:"TOTAL_PAGES",TOTAL_PAGES_IN_SECTION:"TOTAL_PAGES_IN_SECTION",CURRENT_SECTION:"SECTION"};class C0 extends o{constructor($){super("w:r");if(Y0(this,"properties"),this.properties=new J2($),this.root.push(this.properties),$.break)for(let U=0;U<$.break;U++)this.root.push(SQ());if($.children)for(let U of $.children){if(typeof U==="string"){switch(U){case N2.CURRENT:this.root.push($2()),this.root.push(new vQ),this.root.push(I2()),this.root.push(U2());break;case N2.TOTAL_PAGES:this.root.push($2()),this.root.push(new _Q),this.root.push(I2()),this.root.push(U2());break;case N2.TOTAL_PAGES_IN_SECTION:this.root.push($2()),this.root.push(new yQ),this.root.push(I2()),this.root.push(U2());break;case N2.CURRENT_SECTION:this.root.push($2()),this.root.push(new bQ),this.root.push(I2()),this.root.push(U2());break;default:this.root.push(new a2(U));break}continue}this.root.push(U)}else if($.text!==void 0)this.root.push(new a2($.text))}}class p2 extends C0{constructor($){super(typeof $==="string"?{text:$}:$)}}class lQ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{char:"w:char",symbolfont:"w:font"})}}var DZ=class extends o{constructor(U="",Y="Wingdings"){super("w:sym");this.root.push(new lQ({char:U,symbolfont:Y}))}};class G$ extends C0{constructor($){if(typeof $==="string"){super({});return this.root.push(new DZ($)),this}super($);this.root.push(new DZ($.char,$.symbolfont))}}var Z9={},z0={},Q9,AZ;function z1(){if(AZ)return Q9;AZ=1,Q9=$;function $(U,Y){if(!U)throw Error(Y||"Assertion failed")}return $.equal=function(Y,Z,J){if(Y!=Z)throw Error(J||"Assertion failed: "+Y+" != "+Z)},Q9}var PZ;function G2(){if(PZ)return z0;PZ=1;var $=z1(),U=R2();z0.inherits=U;function Y(S,h){if((S.charCodeAt(h)&64512)!==55296)return!1;if(h<0||h+1>=S.length)return!1;return(S.charCodeAt(h+1)&64512)===56320}function Z(S,h){if(Array.isArray(S))return S.slice();if(!S)return[];var N=[];if(typeof S==="string"){if(!h){var a=0;for(var $0=0;$0>6|192,N[a++]=m&63|128;else if(Y(S,$0))m=65536+((m&1023)<<10)+(S.charCodeAt(++$0)&1023),N[a++]=m>>18|240,N[a++]=m>>12&63|128,N[a++]=m>>6&63|128,N[a++]=m&63|128;else N[a++]=m>>12|224,N[a++]=m>>6&63|128,N[a++]=m&63|128}}else if(h==="hex"){if(S=S.replace(/[^a-z0-9]+/ig,""),S.length%2!==0)S="0"+S;for($0=0;$0>>24|S>>>8&65280|S<<8&16711680|(S&255)<<24;return h>>>0}z0.htonl=G;function X(S,h){var N="";for(var a=0;a>>0}return m}z0.join32=F;function z(S,h){var N=Array(S.length*4);for(var a=0,$0=0;a>>24,N[$0+1]=m>>>16&255,N[$0+2]=m>>>8&255,N[$0+3]=m&255;else N[$0+3]=m>>>24,N[$0+2]=m>>>16&255,N[$0+1]=m>>>8&255,N[$0]=m&255}return N}z0.split32=z;function W(S,h){return S>>>h|S<<32-h}z0.rotr32=W;function k(S,h){return S<>>32-h}z0.rotl32=k;function D(S,h){return S+h>>>0}z0.sum32=D;function C(S,h,N){return S+h+N>>>0}z0.sum32_3=C;function H(S,h,N,a){return S+h+N+a>>>0}z0.sum32_4=H;function O(S,h,N,a,$0){return S+h+N+a+$0>>>0}z0.sum32_5=O;function V(S,h,N,a){var $0=S[h],m=S[h+1],J0=a+m>>>0,U0=(J0>>0,S[h+1]=J0}z0.sum64=V;function j(S,h,N,a){var $0=h+a>>>0,m=($0>>0}z0.sum64_hi=j;function M(S,h,N,a){var $0=h+a;return $0>>>0}z0.sum64_lo=M;function L(S,h,N,a,$0,m,J0,U0){var L0=0,i=h;i=i+a>>>0,L0+=i>>0,L0+=i>>0,L0+=i>>0}z0.sum64_4_hi=L;function A(S,h,N,a,$0,m,J0,U0){var L0=h+a+m+U0;return L0>>>0}z0.sum64_4_lo=A;function y(S,h,N,a,$0,m,J0,U0,L0,i){var _=0,r=h;r=r+a>>>0,_+=r>>0,_+=r>>0,_+=r>>0,_+=r>>0}z0.sum64_5_hi=y;function g(S,h,N,a,$0,m,J0,U0,L0,i){var _=h+a+m+U0+i;return _>>>0}z0.sum64_5_lo=g;function d(S,h,N){var a=h<<32-N|S>>>N;return a>>>0}z0.rotr64_hi=d;function E(S,h,N){var a=S<<32-N|h>>>N;return a>>>0}z0.rotr64_lo=E;function s(S,h,N){return S>>>N}z0.shr64_hi=s;function V0(S,h,N){var a=S<<32-N|h>>>N;return a>>>0}return z0.shr64_lo=V0,z0}var J9={},TZ;function F1(){if(TZ)return J9;TZ=1;var $=G2(),U=z1();function Y(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}return J9.BlockHash=Y,Y.prototype.update=function(J,G){if(J=$.toArray(J,G),!this.pending)this.pending=J;else this.pending=this.pending.concat(J);if(this.pendingTotal+=J.length,this.pending.length>=this._delta8){J=this.pending;var X=J.length%this._delta8;if(this.pending=J.slice(J.length-X,J.length),this.pending.length===0)this.pending=null;J=$.join32(J,0,J.length-X,this.endian);for(var Q=0;Q>>24&255,Q[B++]=J>>>16&255,Q[B++]=J>>>8&255,Q[B++]=J&255}else{Q[B++]=J&255,Q[B++]=J>>>8&255,Q[B++]=J>>>16&255,Q[B++]=J>>>24&255,Q[B++]=0,Q[B++]=0,Q[B++]=0,Q[B++]=0;for(F=8;F>>3}s0.g0_256=B;function F(z){return U(z,17)^U(z,19)^z>>>10}return s0.g1_256=F,s0}var G9,OZ;function DX(){if(OZ)return G9;OZ=1;var $=G2(),U=F1(),Y=aQ(),Z=$.rotl32,J=$.sum32,G=$.sum32_5,X=Y.ft_1,Q=U.BlockHash,B=[1518500249,1859775393,2400959708,3395469782];function F(){if(!(this instanceof F))return new F;Q.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}return $.inherits(F,Q),G9=F,F.blockSize=512,F.outSize=160,F.hmacStrength=80,F.padLength=64,F.prototype._update=function(W,k){var D=this.W;for(var C=0;C<16;C++)D[C]=W[k+C];for(;Cthis.blockSize)J=new this.Hash().update(J).digest();U(J.length<=this.blockSize);for(var G=J.length;G{return(Y=U)=>{let Z="",J=Y|0;while(J--)Z+=$[Math.random()*$.length|0];return Z}},yX=($=21)=>{let U="",Y=$|0;while(Y--)U+=vX[Math.random()*64|0];return U},bX=($)=>Math.floor($/25.4*72*20),d0=($)=>Math.floor($*72*20),N1=($=0)=>{let U=$;return()=>++U},rQ=()=>N1(),sQ=()=>N1(1),nQ=()=>N1(),oQ=()=>N1(),R1=()=>yX().toLowerCase(),A9=($)=>SX.sha1().update($ instanceof ArrayBuffer?new Uint8Array($):$).digest("hex"),Y1=($)=>_X("1234567890abcdef",$)(),tQ=()=>`${Y1(8)}-${Y1(4)}-${Y1(4)}-${Y1(4)}-${Y1(12)}`,X1=($)=>new Uint8Array(new TextEncoder().encode($)),eQ={CHARACTER:"character",COLUMN:"column",INSIDE_MARGIN:"insideMargin",LEFT_MARGIN:"leftMargin",MARGIN:"margin",OUTSIDE_MARGIN:"outsideMargin",PAGE:"page",RIGHT_MARGIN:"rightMargin"},$J={BOTTOM_MARGIN:"bottomMargin",INSIDE_MARGIN:"insideMargin",LINE:"line",MARGIN:"margin",OUTSIDE_MARGIN:"outsideMargin",PAGE:"page",PARAGRAPH:"paragraph",TOP_MARGIN:"topMargin"},UJ=()=>new B0({name:"wp:simplePos",attributes:{x:{key:"x",value:0},y:{key:"y",value:0}}}),YJ=($)=>new B0({name:"wp:align",children:[$]}),ZJ=($)=>new B0({name:"wp:posOffset",children:[$.toString()]}),QJ=({relative:$,align:U,offset:Y})=>new B0({name:"wp:positionH",attributes:{relativeFrom:{key:"relativeFrom",value:$!=null?$:eQ.PAGE}},children:[(()=>{if(U)return YJ(U);else if(Y!==void 0)return ZJ(Y);else throw Error("There is no configuration provided for floating position (Align or offset)")})()]}),JJ=({relative:$,align:U,offset:Y})=>new B0({name:"wp:positionV",attributes:{relativeFrom:{key:"relativeFrom",value:$!=null?$:$J.PAGE}},children:[(()=>{if(U)return YJ(U);else if(Y!==void 0)return ZJ(Y);else throw Error("There is no configuration provided for floating position (Align or offset)")})()]}),GJ=(($)=>{return $.CENTER="ctr",$.TOP="t",$.BOTTOM="b",$})(GJ||{}),KJ=($={})=>{var U,Y,Z,J;return new B0({name:"wps:bodyPr",attributes:{lIns:{key:"lIns",value:(U=$.margins)==null?void 0:U.left},rIns:{key:"rIns",value:(Y=$.margins)==null?void 0:Y.right},tIns:{key:"tIns",value:(Z=$.margins)==null?void 0:Z.top},bIns:{key:"bIns",value:(J=$.margins)==null?void 0:J.bottom},anchor:{key:"anchor",value:$.verticalAnchor}},children:[...$.noAutoFit?[new X0("a:noAutofit",$.noAutoFit)]:[]]})},gX=($={txBox:"1"})=>new B0({name:"wps:cNvSpPr",attributes:{txBox:{key:"txBox",value:$.txBox}}}),xX=($)=>new B0({name:"w:txbxContent",children:[...$]}),fX=($)=>new B0({name:"wps:txbx",children:[xX($)]});class qJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{cx:"cx",cy:"cy"})}}class XJ extends o{constructor($,U){super("a:ext");Y0(this,"attributes"),this.attributes=new qJ({cx:$,cy:U}),this.root.push(this.attributes)}}class VJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{x:"x",y:"y"})}}class BJ extends o{constructor($,U){super("a:off");this.root.push(new VJ({x:$!=null?$:0,y:U!=null?U:0}))}}class LJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{flipVertical:"flipV",flipHorizontal:"flipH",rotation:"rot"})}}class K$ extends o{constructor($){var U,Y,Z,J,G,X;super("a:xfrm");Y0(this,"extents"),Y0(this,"offset"),this.root.push(new LJ({flipVertical:(U=$.flip)==null?void 0:U.vertical,flipHorizontal:(Y=$.flip)==null?void 0:Y.horizontal,rotation:$.rotation})),this.offset=new BJ((J=(Z=$.offset)==null?void 0:Z.emus)==null?void 0:J.x,(X=(G=$.offset)==null?void 0:G.emus)==null?void 0:X.y),this.extents=new XJ($.emus.x,$.emus.y),this.root.push(this.offset),this.root.push(this.extents)}}var MJ=()=>new B0({name:"a:noFill"}),hX=($)=>new B0({name:"a:srgbClr",attributes:{value:{key:"val",value:$.value}}}),uX=($)=>new B0({name:"a:schemeClr",attributes:{value:{key:"val",value:$.value}}}),P9=($)=>new B0({name:"a:solidFill",children:[$.type==="rgb"?hX($):uX($)]}),dX=($)=>new B0({name:"a:ln",attributes:{width:{key:"w",value:$.width},cap:{key:"cap",value:$.cap},compoundLine:{key:"cmpd",value:$.compoundLine},align:{key:"algn",value:$.align}},children:[$.type==="noFill"?MJ():$.solidFillType==="rgb"?P9({type:"rgb",value:$.value}):P9({type:"scheme",value:$.value})]});class IJ extends o{constructor(){super("a:avLst")}}class wJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{prst:"prst"})}}class WJ extends o{constructor(){super("a:prstGeom");this.root.push(new wJ({prst:"rect"})),this.root.push(new IJ)}}class HJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{bwMode:"bwMode"})}}class q$ extends o{constructor({element:$,outline:U,solidFill:Y,transform:Z}){super(`${$}:spPr`);if(Y0(this,"form"),this.root.push(new HJ({bwMode:"auto"})),this.form=new K$(Z),this.root.push(this.form),this.root.push(new WJ),U)this.root.push(MJ()),this.root.push(dX(U));if(Y)this.root.push(P9(Y))}}var xZ=($)=>new B0({name:"wps:wsp",children:[gX($.nonVisualProperties),new q$({element:"wps",transform:$.transformation,outline:$.outline,solidFill:$.solidFill}),fX($.children),KJ($.bodyProperties)]});class x1 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{uri:"uri"})}}var cX=($)=>new B0({name:"asvg:svgBlip",attributes:{asvg:{key:"xmlns:asvg",value:"http://schemas.microsoft.com/office/drawing/2016/SVG/main"},embed:{key:"r:embed",value:`rId{${$.fileName}}`}}}),mX=($)=>new B0({name:"a:ext",attributes:{uri:{key:"uri",value:"{96DAC541-7B7A-43D3-8B79-37D633B846F1}"}},children:[cX($)]}),lX=($)=>new B0({name:"a:extLst",children:[mX($)]}),aX=($)=>new B0({name:"a:blip",attributes:{embed:{key:"r:embed",value:`rId{${$.type==="svg"?$.fallback.fileName:$.fileName}}`},cstate:{key:"cstate",value:"none"}},children:$.type==="svg"?[lX($)]:[]});class jJ extends o{constructor(){super("a:srcRect")}}class zJ extends o{constructor(){super("a:fillRect")}}class FJ extends o{constructor(){super("a:stretch");this.root.push(new zJ)}}class NJ extends o{constructor($){super("pic:blipFill");this.root.push(aX($)),this.root.push(new jJ),this.root.push(new FJ)}}class RJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{noChangeAspect:"noChangeAspect",noChangeArrowheads:"noChangeArrowheads"})}}class DJ extends o{constructor(){super("a:picLocks");this.root.push(new RJ({noChangeAspect:1,noChangeArrowheads:1}))}}class AJ extends o{constructor(){super("pic:cNvPicPr");this.root.push(new DJ)}}var PJ=($,U)=>new B0({name:"a:hlinkClick",attributes:R0(W0({},U?{xmlns:{key:"xmlns:a",value:"http://schemas.openxmlformats.org/drawingml/2006/main"}}:{}),{id:{key:"r:id",value:`rId${$}`}})});class TJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"id",name:"name",descr:"descr"})}}class CJ extends o{constructor(){super("pic:cNvPr");this.root.push(new TJ({id:0,name:"",descr:""}))}prepForXml($){for(let U=$.stack.length-1;U>=0;U--){let Y=$.stack[U];if(!(Y instanceof _2))continue;this.root.push(PJ(Y.linkId,!1));break}return super.prepForXml($)}}class OJ extends o{constructor(){super("pic:nvPicPr");this.root.push(new CJ),this.root.push(new AJ)}}class kJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns:pic"})}}class T9 extends o{constructor({mediaData:$,transform:U,outline:Y}){super("pic:pic");this.root.push(new kJ({xmlns:"http://schemas.openxmlformats.org/drawingml/2006/picture"})),this.root.push(new OJ),this.root.push(new NJ($)),this.root.push(new q$({element:"pic",transform:U,outline:Y}))}}var pX=($)=>new B0({name:"wpg:grpSpPr",children:[new K$($)]}),iX=()=>new B0({name:"wpg:cNvGrpSpPr"}),rX=($)=>new B0({name:"wpg:wgp",children:[iX(),pX($.transformation),...$.children]});class EJ extends o{constructor({mediaData:$,transform:U,outline:Y,solidFill:Z}){super("a:graphicData");if($.type==="wps"){this.root.push(new x1({uri:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"}));let J=xZ(R0(W0({},$.data),{transformation:U,outline:Y,solidFill:Z}));this.root.push(J)}else if($.type==="wpg"){this.root.push(new x1({uri:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"}));let G=$.children.map((Q)=>{if(Q.type==="wps")return xZ(R0(W0({},Q.data),{transformation:Q.transformation,outline:Q.outline,solidFill:Q.solidFill}));else return new T9({mediaData:Q,transform:Q.transformation,outline:Q.outline})}),X=rX({children:G,transformation:U});this.root.push(X)}else{this.root.push(new x1({uri:"http://schemas.openxmlformats.org/drawingml/2006/picture"}));let G=new T9({mediaData:$,transform:U,outline:Y});this.root.push(G)}}}class SJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{a:"xmlns:a"})}}class X$ extends o{constructor({mediaData:$,transform:U,outline:Y,solidFill:Z}){super("a:graphic");Y0(this,"data"),this.root.push(new SJ({a:"http://schemas.openxmlformats.org/drawingml/2006/main"})),this.data=new EJ({mediaData:$,transform:U,outline:Y,solidFill:Z}),this.root.push(this.data)}}var G1={NONE:0,SQUARE:1,TIGHT:2,TOP_AND_BOTTOM:3},vJ={BOTH_SIDES:"bothSides",LEFT:"left",RIGHT:"right",LARGEST:"largest"},C9=()=>new B0({name:"wp:wrapNone"}),_J=($,U={top:0,bottom:0,left:0,right:0})=>new B0({name:"wp:wrapSquare",attributes:{wrapText:{key:"wrapText",value:$.side||vJ.BOTH_SIDES},distT:{key:"distT",value:U.top},distB:{key:"distB",value:U.bottom},distL:{key:"distL",value:U.left},distR:{key:"distR",value:U.right}}}),yJ=($={top:0,bottom:0})=>new B0({name:"wp:wrapTight",attributes:{distT:{key:"distT",value:$.top},distB:{key:"distB",value:$.bottom}}}),bJ=($={top:0,bottom:0})=>new B0({name:"wp:wrapTopAndBottom",attributes:{distT:{key:"distT",value:$.top},distB:{key:"distB",value:$.bottom}}});class V$ extends o{constructor({name:$,description:U,title:Y,id:Z}={name:"",description:"",title:""}){super("wp:docPr");Y0(this,"docPropertiesUniqueNumericId",nQ());let J={id:{key:"id",value:Z!=null?Z:this.docPropertiesUniqueNumericId()},name:{key:"name",value:$}};if(U!==null&&U!==void 0)J.description={key:"descr",value:U};if(Y!==null&&Y!==void 0)J.title={key:"title",value:Y};this.root.push(new n1(J))}prepForXml($){for(let U=$.stack.length-1;U>=0;U--){let Y=$.stack[U];if(!(Y instanceof _2))continue;this.root.push(PJ(Y.linkId,!0));break}return super.prepForXml($)}}var gJ=({top:$,right:U,bottom:Y,left:Z})=>new B0({name:"wp:effectExtent",attributes:{top:{key:"t",value:$},right:{key:"r",value:U},bottom:{key:"b",value:Y},left:{key:"l",value:Z}}}),xJ=({x:$,y:U})=>new B0({name:"wp:extent",attributes:{x:{key:"cx",value:$},y:{key:"cy",value:U}}});class fJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns:a",noChangeAspect:"noChangeAspect"})}}class hJ extends o{constructor(){super("a:graphicFrameLocks");this.root.push(new fJ({xmlns:"http://schemas.openxmlformats.org/drawingml/2006/main",noChangeAspect:1}))}}var uJ=()=>new B0({name:"wp:cNvGraphicFramePr",children:[new hJ]});class dJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{distT:"distT",distB:"distB",distL:"distL",distR:"distR",allowOverlap:"allowOverlap",behindDoc:"behindDoc",layoutInCell:"layoutInCell",locked:"locked",relativeHeight:"relativeHeight",simplePos:"simplePos"})}}class cJ extends o{constructor({mediaData:$,transform:U,drawingOptions:Y}){super("wp:anchor");let Z=W0({allowOverlap:!0,behindDocument:!1,lockAnchor:!1,layoutInCell:!0,verticalPosition:{},horizontalPosition:{}},Y.floating);if(this.root.push(new dJ({distT:Z.margins?Z.margins.top||0:0,distB:Z.margins?Z.margins.bottom||0:0,distL:Z.margins?Z.margins.left||0:0,distR:Z.margins?Z.margins.right||0:0,simplePos:"0",allowOverlap:Z.allowOverlap===!0?"1":"0",behindDoc:Z.behindDocument===!0?"1":"0",locked:Z.lockAnchor===!0?"1":"0",layoutInCell:Z.layoutInCell===!0?"1":"0",relativeHeight:Z.zIndex?Z.zIndex:U.emus.y})),this.root.push(UJ()),this.root.push(QJ(Z.horizontalPosition)),this.root.push(JJ(Z.verticalPosition)),this.root.push(xJ({x:U.emus.x,y:U.emus.y})),this.root.push(gJ({top:0,right:0,bottom:0,left:0})),Y.floating!==void 0&&Y.floating.wrap!==void 0)switch(Y.floating.wrap.type){case G1.SQUARE:this.root.push(_J(Y.floating.wrap,Y.floating.margins));break;case G1.TIGHT:this.root.push(yJ(Y.floating.margins));break;case G1.TOP_AND_BOTTOM:this.root.push(bJ(Y.floating.margins));break;case G1.NONE:default:this.root.push(C9())}else this.root.push(C9());this.root.push(new V$(Y.docProperties)),this.root.push(uJ()),this.root.push(new X$({mediaData:$,transform:U,outline:Y.outline,solidFill:Y.solidFill}))}}var sX=({mediaData:$,transform:U,docProperties:Y,outline:Z,solidFill:J})=>{var G,X,Q,B;return new B0({name:"wp:inline",attributes:{distanceTop:{key:"distT",value:0},distanceBottom:{key:"distB",value:0},distanceLeft:{key:"distL",value:0},distanceRight:{key:"distR",value:0}},children:[xJ({x:U.emus.x,y:U.emus.y}),gJ(Z?{top:((G=Z.width)!=null?G:9525)*2,right:((X=Z.width)!=null?X:9525)*2,bottom:((Q=Z.width)!=null?Q:9525)*2,left:((B=Z.width)!=null?B:9525)*2}:{top:0,right:0,bottom:0,left:0}),new V$(Y),uJ(),new X$({mediaData:$,transform:U,outline:Z,solidFill:J})]})};class D1 extends o{constructor($,U={}){super("w:drawing");if(!U.floating)this.root.push(sX({mediaData:$,transform:$.transformation,docProperties:U.docProperties,outline:U.outline,solidFill:U.solidFill}));else this.root.push(new cJ({mediaData:$,transform:$.transformation,drawingOptions:U}))}}var nX=($)=>{let Y=$.indexOf(";base64,"),Z=Y===-1?0:Y+8;return new Uint8Array(atob($.substring(Z)).split("").map((J)=>J.charCodeAt(0)))},mJ=($)=>typeof $==="string"?nX($):$,M9=($,U)=>({data:mJ($.data),fileName:U,transformation:{pixels:{x:Math.round($.transformation.width),y:Math.round($.transformation.height)},emus:{x:Math.round($.transformation.width*9525),y:Math.round($.transformation.height*9525)},flip:$.transformation.flip,rotation:$.transformation.rotation?$.transformation.rotation*60000:void 0}});class lJ extends C0{constructor($){super({});Y0(this,"imageData");let Y=`${A9($.data)}.${$.type}`;this.imageData=$.type==="svg"?R0(W0({type:$.type},M9($,Y)),{fallback:W0({type:$.fallback.type},M9(R0(W0({},$.fallback),{transformation:$.transformation}),`${A9($.fallback.data)}.${$.fallback.type}`))}):W0({type:$.type},M9($,Y));let Z=new D1(this.imageData,{floating:$.floating,docProperties:$.altText,outline:$.outline});this.root.push(Z)}prepForXml($){if($.file.Media.addImage(this.imageData.fileName,this.imageData),this.imageData.type==="svg")$.file.Media.addImage(this.imageData.fallback.fileName,this.imageData.fallback);return super.prepForXml($)}}var B$=($)=>{var U,Y,Z,J,G,X,Q,B;return{offset:{pixels:{x:Math.round((Y=(U=$.offset)==null?void 0:U.left)!=null?Y:0),y:Math.round((J=(Z=$.offset)==null?void 0:Z.top)!=null?J:0)},emus:{x:Math.round(((X=(G=$.offset)==null?void 0:G.left)!=null?X:0)*9525),y:Math.round(((B=(Q=$.offset)==null?void 0:Q.top)!=null?B:0)*9525)}},pixels:{x:Math.round($.width),y:Math.round($.height)},emus:{x:Math.round($.width*9525),y:Math.round($.height*9525)},flip:$.flip,rotation:$.rotation?$.rotation*60000:void 0}};class aJ extends C0{constructor($){super({});Y0(this,"wpsShapeData"),this.wpsShapeData={type:$.type,transformation:B$($.transformation),data:W0({},$)};let U=new D1(this.wpsShapeData,{floating:$.floating,docProperties:$.altText,outline:$.outline,solidFill:$.solidFill});this.root.push(U)}}class pJ extends C0{constructor($){super({});Y0(this,"wpgGroupData"),Y0(this,"mediaDatas"),this.wpgGroupData={type:$.type,transformation:B$($.transformation),children:$.children};let U=new D1(this.wpgGroupData,{floating:$.floating,docProperties:$.altText});this.mediaDatas=$.children.filter((Y)=>Y.type!=="wps").map((Y)=>Y),this.root.push(U)}prepForXml($){return this.mediaDatas.forEach((U)=>{if($.file.Media.addImage(U.fileName,U),U.type==="svg")$.file.Media.addImage(U.fallback.fileName,U.fallback)}),super.prepForXml($)}}class iJ extends o{constructor($){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push(`SEQ ${$}`)}}class rJ extends C0{constructor($){super({});this.root.push($2(!0)),this.root.push(new iJ($)),this.root.push(I2()),this.root.push(U2())}}class sJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{instr:"w:instr"})}}class J8 extends o{constructor($,U){super("w:fldSimple");if(this.root.push(new sJ({instr:$})),U!==void 0)this.root.push(new p2(U))}}class nJ extends J8{constructor($){super(` MERGEFIELD ${$} `,`«${$}»`)}}class oJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns"})}}var tJ={EXTERNAL:"External"},oX=($,U,Y,Z)=>new B0({name:"Relationship",attributes:{id:{key:"Id",value:$},type:{key:"Type",value:U},target:{key:"Target",value:Y},targetMode:{key:"TargetMode",value:Z}}});class W2 extends o{constructor(){super("Relationships");this.root.push(new oJ({xmlns:"http://schemas.openxmlformats.org/package/2006/relationships"}))}addRelationship($,U,Y,Z){this.root.push(oX(`rId${$}`,U,Y,Z))}get RelationshipCount(){return this.root.length-1}}class eJ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id",initials:"w:initials",author:"w:author",date:"w:date"})}}class G8 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id"})}}class $G extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{"xmlns:cx":"xmlns:cx","xmlns:cx1":"xmlns:cx1","xmlns:cx2":"xmlns:cx2","xmlns:cx3":"xmlns:cx3","xmlns:cx4":"xmlns:cx4","xmlns:cx5":"xmlns:cx5","xmlns:cx6":"xmlns:cx6","xmlns:cx7":"xmlns:cx7","xmlns:cx8":"xmlns:cx8","xmlns:mc":"xmlns:mc","xmlns:aink":"xmlns:aink","xmlns:am3d":"xmlns:am3d","xmlns:o":"xmlns:o","xmlns:r":"xmlns:r","xmlns:m":"xmlns:m","xmlns:v":"xmlns:v","xmlns:wp14":"xmlns:wp14","xmlns:wp":"xmlns:wp","xmlns:w10":"xmlns:w10","xmlns:w":"xmlns:w","xmlns:w14":"xmlns:w14","xmlns:w15":"xmlns:w15","xmlns:w16cex":"xmlns:w16cex","xmlns:w16cid":"xmlns:w16cid","xmlns:w16":"xmlns:w16","xmlns:w16sdtdh":"xmlns:w16sdtdh","xmlns:w16se":"xmlns:w16se","xmlns:wpg":"xmlns:wpg","xmlns:wpi":"xmlns:wpi","xmlns:wne":"xmlns:wne","xmlns:wps":"xmlns:wps"})}}class UG extends o{constructor($){super("w:commentRangeStart");this.root.push(new G8({id:$}))}}class YG extends o{constructor($){super("w:commentRangeEnd");this.root.push(new G8({id:$}))}}class ZG extends o{constructor($){super("w:commentReference");this.root.push(new G8({id:$}))}}class L$ extends o{constructor({id:$,initials:U,author:Y,date:Z=new Date,children:J}){super("w:comment");this.root.push(new eJ({id:$,initials:U,author:Y,date:Z.toISOString()}));for(let G of J)this.root.push(G)}}class M$ extends o{constructor({children:$}){super("w:comments");Y0(this,"relationships"),this.root.push(new $G({"xmlns:cx":"http://schemas.microsoft.com/office/drawing/2014/chartex","xmlns:cx1":"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex","xmlns:cx2":"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex","xmlns:cx3":"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex","xmlns:cx4":"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex","xmlns:cx5":"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex","xmlns:cx6":"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex","xmlns:cx7":"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex","xmlns:cx8":"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex","xmlns:mc":"http://schemas.openxmlformats.org/markup-compatibility/2006","xmlns:aink":"http://schemas.microsoft.com/office/drawing/2016/ink","xmlns:am3d":"http://schemas.microsoft.com/office/drawing/2017/model3d","xmlns:o":"urn:schemas-microsoft-com:office:office","xmlns:r":"http://schemas.openxmlformats.org/officeDocument/2006/relationships","xmlns:m":"http://schemas.openxmlformats.org/officeDocument/2006/math","xmlns:v":"urn:schemas-microsoft-com:vml","xmlns:wp14":"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing","xmlns:wp":"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing","xmlns:w10":"urn:schemas-microsoft-com:office:word","xmlns:w":"http://schemas.openxmlformats.org/wordprocessingml/2006/main","xmlns:w14":"http://schemas.microsoft.com/office/word/2010/wordml","xmlns:w15":"http://schemas.microsoft.com/office/word/2012/wordml","xmlns:w16cex":"http://schemas.microsoft.com/office/word/2018/wordml/cex","xmlns:w16cid":"http://schemas.microsoft.com/office/word/2016/wordml/cid","xmlns:w16":"http://schemas.microsoft.com/office/word/2018/wordml","xmlns:w16sdtdh":"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash","xmlns:w16se":"http://schemas.microsoft.com/office/word/2015/wordml/symex","xmlns:wpg":"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup","xmlns:wpi":"http://schemas.microsoft.com/office/word/2010/wordprocessingInk","xmlns:wne":"http://schemas.microsoft.com/office/word/2006/wordml","xmlns:wps":"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"}));for(let U of $)this.root.push(new L$(U));this.relationships=new W2}get Relationships(){return this.relationships}}class QG extends k0{constructor(){super("w:noBreakHyphen")}}class JG extends k0{constructor(){super("w:softHyphen")}}class GG extends k0{constructor(){super("w:dayShort")}}class KG extends k0{constructor(){super("w:monthShort")}}class qG extends k0{constructor(){super("w:yearShort")}}class XG extends k0{constructor(){super("w:dayLong")}}class VG extends k0{constructor(){super("w:monthLong")}}class BG extends k0{constructor(){super("w:yearLong")}}class LG extends k0{constructor(){super("w:annotationRef")}}class MG extends k0{constructor(){super("w:footnoteRef")}}class I$ extends k0{constructor(){super("w:endnoteRef")}}class IG extends k0{constructor(){super("w:separator")}}class wG extends k0{constructor(){super("w:continuationSeparator")}}class WG extends k0{constructor(){super("w:pgNum")}}class HG extends k0{constructor(){super("w:cr")}}class w$ extends k0{constructor(){super("w:tab")}}class jG extends k0{constructor(){super("w:lastRenderedPageBreak")}}var tX={LEFT:"left",CENTER:"center",RIGHT:"right"},eX={MARGIN:"margin",INDENT:"indent"},$V={NONE:"none",DOT:"dot",HYPHEN:"hyphen",UNDERSCORE:"underscore",MIDDLE_DOT:"middleDot"};class zG extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{alignment:"w:alignment",relativeTo:"w:relativeTo",leader:"w:leader"})}}class FG extends o{constructor($){super("w:ptab");this.root.push(new zG({alignment:$.alignment,relativeTo:$.relativeTo,leader:$.leader}))}}var NG={COLUMN:"column",PAGE:"page"};class W$ extends o{constructor($){super("w:br");this.root.push(new O0({type:$}))}}class RG extends C0{constructor(){super({});this.root.push(new W$(NG.PAGE))}}class DG extends C0{constructor(){super({});this.root.push(new W$(NG.COLUMN))}}class H$ extends o{constructor(){super("w:pageBreakBefore")}}var v2={AT_LEAST:"atLeast",EXACTLY:"exactly",EXACT:"exact",AUTO:"auto"},AG=({after:$,before:U,line:Y,lineRule:Z,beforeAutoSpacing:J,afterAutoSpacing:G})=>new B0({name:"w:spacing",attributes:{after:{key:"w:after",value:$},before:{key:"w:before",value:U},line:{key:"w:line",value:Y},lineRule:{key:"w:lineRule",value:Z},beforeAutoSpacing:{key:"w:beforeAutospacing",value:J},afterAutoSpacing:{key:"w:afterAutospacing",value:G}}}),UV={HEADING_1:"Heading1",HEADING_2:"Heading2",HEADING_3:"Heading3",HEADING_4:"Heading4",HEADING_5:"Heading5",HEADING_6:"Heading6",TITLE:"Title"},K1=($)=>new B0({name:"w:pStyle",attributes:{val:{key:"w:val",value:$}}}),O9={LEFT:"left",RIGHT:"right",CENTER:"center",BAR:"bar",CLEAR:"clear",DECIMAL:"decimal",END:"end",NUM:"num",START:"start"},YV={DOT:"dot",HYPHEN:"hyphen",MIDDLE_DOT:"middleDot",NONE:"none",UNDERSCORE:"underscore"},ZV={MAX:9026},PG=({type:$,position:U,leader:Y})=>new B0({name:"w:tab",attributes:{val:{key:"w:val",value:$},pos:{key:"w:pos",value:U},leader:{key:"w:leader",value:Y}}}),TG=($)=>new B0({name:"w:tabs",children:$.map((U)=>PG(U))});class V1 extends o{constructor($,U){super("w:numPr");this.root.push(new CG(U)),this.root.push(new OG($))}}class CG extends o{constructor($){super("w:ilvl");if($>9)throw Error("Level cannot be greater than 9. Read more here: https://answers.microsoft.com/en-us/msoffice/forum/all/does-word-support-more-than-9-list-levels/d130fdcd-1781-446d-8c84-c6c79124e4d7");this.root.push(new O0({val:$}))}}class OG extends o{constructor($){super("w:numId");this.root.push(new O0({val:typeof $==="string"?`{${$}}`:$}))}}class r2 extends o{constructor(){super(...arguments);Y0(this,"fileChild",Symbol())}}class kG extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"r:id",history:"w:history",anchor:"w:anchor"})}}var QV={INTERNAL:"INTERNAL",EXTERNAL:"EXTERNAL"};class _2 extends o{constructor($,U,Y){super("w:hyperlink");Y0(this,"linkId"),this.linkId=U;let Z={history:1,anchor:Y?Y:void 0,id:!Y?`rId${this.linkId}`:void 0},J=new kG(Z);this.root.push(J),$.forEach((G)=>{this.root.push(G)})}}class j$ extends _2{constructor($){super($.children,R1(),$.anchor)}}class K8 extends o{constructor($){super("w:externalHyperlink");this.options=$}}class EG extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id",name:"w:name"})}}class SG extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id"})}}class z${constructor($){Y0(this,"bookmarkUniqueNumericId",oQ()),Y0(this,"start"),Y0(this,"children"),Y0(this,"end");let U=this.bookmarkUniqueNumericId();this.start=new F$($.id,U),this.children=$.children,this.end=new N$(U)}}class F$ extends o{constructor($,U){super("w:bookmarkStart");let Y=new EG({name:$,id:U});this.root.push(Y)}}class N$ extends o{constructor($){super("w:bookmarkEnd");let U=new SG({id:$});this.root.push(U)}}var vG=(($)=>{return $.NONE="none",$.RELATIVE="relative",$.NO_CONTEXT="no_context",$.FULL_CONTEXT="full_context",$})(vG||{}),JV={["relative"]:"\\r",["no_context"]:"\\n",["full_context"]:"\\w",["none"]:void 0};class _G extends J8{constructor($,U,Y={}){let{hyperlink:Z=!0,referenceFormat:J="full_context"}=Y,G=`REF ${$}`,X=[...Z?["\\h"]:[],...[JV[J]].filter((B)=>!!B)],Q=`${G} ${X.join(" ")}`;super(Q,U)}}var yG=($)=>new B0({name:"w:outlineLvl",attributes:{val:{key:"w:val",value:$}}});class bG extends o{constructor($,U={}){super("w:instrText");this.root.push(new x0({space:g0.PRESERVE}));let Y=`PAGEREF ${$}`;if(U.hyperlink)Y=`${Y} \\h`;if(U.useRelativePosition)Y=`${Y} \\p`;this.root.push(Y)}}class gG extends C0{constructor($,U={}){super({children:[$2(!0),new bG($,U),U2()]})}}var GV={ANSI:"00",DEFAULT:"01",SYMBOL:"02",MAC:"4D",JIS:"80",HANGUL:"81",JOHAB:"82",GB_2312:"86",CHINESEBIG5:"88",GREEK:"A1",TURKISH:"A2",VIETNAMESE:"A3",HEBREW:"B1",ARABIC:"B2",BALTIC:"BA",RUSSIAN:"CC",THAI:"DE",EASTEUROPE:"EE",OEM:"FF"},_1=({id:$,fontKey:U,subsetted:Y},Z)=>new B0({name:Z,attributes:W0({id:{key:"r:id",value:$}},U?{fontKey:{key:"w:fontKey",value:`{${U}}`}}:{}),children:[...Y?[new X0("w:subsetted",Y)]:[]]}),KV=({name:$,altName:U,panose1:Y,charset:Z,family:J,notTrueType:G,pitch:X,sig:Q,embedRegular:B,embedBold:F,embedItalic:z,embedBoldItalic:W})=>new B0({name:"w:font",attributes:{name:{key:"w:name",value:$}},children:[...U?[u2("w:altName",U)]:[],...Y?[u2("w:panose1",Y)]:[],...Z?[u2("w:charset",Z)]:[],u2("w:family",J),...G?[new X0("w:notTrueType",G)]:[],u2("w:pitch",X),...Q?[new B0({name:"w:sig",attributes:{usb0:{key:"w:usb0",value:Q.usb0},usb1:{key:"w:usb1",value:Q.usb1},usb2:{key:"w:usb2",value:Q.usb2},usb3:{key:"w:usb3",value:Q.usb3},csb0:{key:"w:csb0",value:Q.csb0},csb1:{key:"w:csb1",value:Q.csb1}}})]:[],...B?[_1(B,"w:embedRegular")]:[],...F?[_1(F,"w:embedBold")]:[],...z?[_1(z,"w:embedItalic")]:[],...W?[_1(W,"w:embedBoldItalic")]:[]]}),qV=({name:$,index:U,fontKey:Y,characterSet:Z})=>KV({name:$,sig:{usb0:"E0002AFF",usb1:"C000247B",usb2:"00000009",usb3:"00000000",csb0:"000001FF",csb1:"00000000"},charset:Z,family:"auto",pitch:"variable",embedRegular:{fontKey:Y,id:`rId${U}`}}),XV=($)=>new B0({name:"w:fonts",attributes:{mc:{key:"xmlns:mc",value:"http://schemas.openxmlformats.org/markup-compatibility/2006"},r:{key:"xmlns:r",value:"http://schemas.openxmlformats.org/officeDocument/2006/relationships"},w:{key:"xmlns:w",value:"http://schemas.openxmlformats.org/wordprocessingml/2006/main"},w14:{key:"xmlns:w14",value:"http://schemas.microsoft.com/office/word/2010/wordml"},w15:{key:"xmlns:w15",value:"http://schemas.microsoft.com/office/word/2012/wordml"},w16cex:{key:"xmlns:w16cex",value:"http://schemas.microsoft.com/office/word/2018/wordml/cex"},w16cid:{key:"xmlns:w16cid",value:"http://schemas.microsoft.com/office/word/2016/wordml/cid"},w16:{key:"xmlns:w16",value:"http://schemas.microsoft.com/office/word/2018/wordml"},w16sdtdh:{key:"xmlns:w16sdtdh",value:"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash"},w16se:{key:"xmlns:w16se",value:"http://schemas.microsoft.com/office/word/2015/wordml/symex"},Ignorable:{key:"mc:Ignorable",value:"w14 w15 w16se w16cid w16 w16cex w16sdtdh"}},children:$.map((U,Y)=>qV({name:U.name,index:Y+1,fontKey:U.fontKey,characterSet:U.characterSet}))});class R${constructor($){Y0(this,"fontTable"),Y0(this,"relationships"),Y0(this,"fontOptionsWithKey",[]),this.options=$,this.fontOptionsWithKey=$.map((U)=>R0(W0({},U),{fontKey:tQ()})),this.fontTable=XV(this.fontOptionsWithKey),this.relationships=new W2;for(let U=0;U<$.length;U++)this.relationships.addRelationship(U+1,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/font",`fonts/${$[U].name}.odttf`)}get View(){return this.fontTable}get Relationships(){return this.relationships}}var VV=()=>new B0({name:"w:wordWrap",attributes:{val:{key:"w:val",value:0}}}),BV={NONE:"none",DROP:"drop",MARGIN:"margin"},LV={MARGIN:"margin",PAGE:"page",TEXT:"text"},MV={AROUND:"around",AUTO:"auto",NONE:"none",NOT_BESIDE:"notBeside",THROUGH:"through",TIGHT:"tight"},xG=($)=>{var U,Y;return new B0({name:"w:framePr",attributes:{anchorLock:{key:"w:anchorLock",value:$.anchorLock},dropCap:{key:"w:dropCap",value:$.dropCap},width:{key:"w:w",value:$.width},height:{key:"w:h",value:$.height},x:{key:"w:x",value:$.position?$.position.x:void 0},y:{key:"w:y",value:$.position?$.position.y:void 0},anchorHorizontal:{key:"w:hAnchor",value:$.anchor.horizontal},anchorVertical:{key:"w:vAnchor",value:$.anchor.vertical},spaceHorizontal:{key:"w:hSpace",value:(U=$.space)==null?void 0:U.horizontal},spaceVertical:{key:"w:vSpace",value:(Y=$.space)==null?void 0:Y.vertical},rule:{key:"w:hRule",value:$.rule},alignmentX:{key:"w:xAlign",value:$.alignment?$.alignment.x:void 0},alignmentY:{key:"w:yAlign",value:$.alignment?$.alignment.y:void 0},lines:{key:"w:lines",value:$.lines},wrap:{key:"w:wrap",value:$.wrap}}})};class Z2 extends Q2{constructor($){var U,Y;super("w:pPr",$==null?void 0:$.includeIfEmpty);if(Y0(this,"numberingReferences",[]),!$)return this;if($.heading)this.push(K1($.heading));if($.bullet)this.push(K1("ListParagraph"));if($.numbering){if(!$.style&&!$.heading){if(!$.numbering.custom)this.push(K1("ListParagraph"))}}if($.style)this.push(K1($.style));if($.keepNext!==void 0)this.push(new X0("w:keepNext",$.keepNext));if($.keepLines!==void 0)this.push(new X0("w:keepLines",$.keepLines));if($.pageBreakBefore)this.push(new H$);if($.frame)this.push(xG($.frame));if($.widowControl!==void 0)this.push(new X0("w:widowControl",$.widowControl));if($.bullet)this.push(new V1(1,$.bullet.level));if($.numbering)this.numberingReferences.push({reference:$.numbering.reference,instance:(U=$.numbering.instance)!=null?U:0}),this.push(new V1(`${$.numbering.reference}-${(Y=$.numbering.instance)!=null?Y:0}`,$.numbering.level));else if($.numbering===!1)this.push(new V1(0,0));if($.border)this.push(new o9($.border));if($.thematicBreak)this.push(new t9);if($.shading)this.push(j1($.shading));if($.wordWrap)this.push(VV());if($.overflowPunctuation)this.push(new X0("w:overflowPunct",$.overflowPunctuation));let Z=[...$.rightTabStop!==void 0?[{type:O9.RIGHT,position:$.rightTabStop}]:[],...$.tabStops?$.tabStops:[],...$.leftTabStop!==void 0?[{type:O9.LEFT,position:$.leftTabStop}]:[]];if(Z.length>0)this.push(TG(Z));if($.bidirectional!==void 0)this.push(new X0("w:bidi",$.bidirectional));if($.spacing)this.push(AG($.spacing));if($.indent)this.push(EQ($.indent));if($.contextualSpacing!==void 0)this.push(new X0("w:contextualSpacing",$.contextualSpacing));if($.alignment)this.push(n9($.alignment));if($.outlineLevel!==void 0)this.push(yG($.outlineLevel));if($.suppressLineNumbers!==void 0)this.push(new X0("w:suppressLineNumbers",$.suppressLineNumbers));if($.autoSpaceEastAsianText!==void 0)this.push(new X0("w:autoSpaceDN",$.autoSpaceEastAsianText));if($.run)this.push(new Q$($.run));if($.revision)this.push(new D$($.revision))}push($){this.root.push($)}prepForXml($){if(!($.viewWrapper instanceof R$))for(let U of this.numberingReferences)$.file.Numbering.createConcreteNumberingInstance(U.reference,U.instance);return super.prepForXml($)}}class D$ extends o{constructor($){super("w:pPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.root.push(new Z2(R0(W0({},$),{includeIfEmpty:!0})))}}class h0 extends r2{constructor($){super("w:p");if(Y0(this,"properties"),typeof $==="string")return this.properties=new Z2({}),this.root.push(this.properties),this.root.push(new p2($)),this;if(this.properties=new Z2($),this.root.push(this.properties),$.text)this.root.push(new p2($.text));if($.children)for(let U of $.children){if(U instanceof z$){this.root.push(U.start);for(let Y of U.children)this.root.push(Y);this.root.push(U.end);continue}this.root.push(U)}}prepForXml($){for(let U of this.root)if(U instanceof K8){let Y=this.root.indexOf(U),Z=new _2(U.options.children,R1());$.viewWrapper.Relationships.addRelationship(Z.linkId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",U.options.link,tJ.EXTERNAL),this.root[Y]=Z}return super.prepForXml($)}addRunToFront($){return this.root.splice(1,0,$),this}}var IV=class extends o{constructor(U){super("m:oMath");for(let Y of U.children)this.root.push(Y)}};class fG extends o{constructor($){super("m:t");this.root.push($)}}class hG extends o{constructor($){super("m:r");this.root.push(new fG($))}}class A$ extends o{constructor($){super("m:den");for(let U of $)this.root.push(U)}}class P$ extends o{constructor($){super("m:num");for(let U of $)this.root.push(U)}}class uG extends o{constructor($){super("m:f");this.root.push(new P$($.numerator)),this.root.push(new A$($.denominator))}}var dG=({accent:$})=>new B0({name:"m:chr",attributes:{accent:{key:"m:val",value:$}}}),y0=({children:$})=>new B0({name:"m:e",children:$}),cG=({value:$})=>new B0({name:"m:limLoc",attributes:{value:{key:"m:val",value:$||"undOvr"}}}),wV=()=>new B0({name:"m:subHide",attributes:{hide:{key:"m:val",value:1}}}),WV=()=>new B0({name:"m:supHide",attributes:{hide:{key:"m:val",value:1}}}),T$=({accent:$,hasSuperScript:U,hasSubScript:Y,limitLocationVal:Z})=>new B0({name:"m:naryPr",children:[...$?[dG({accent:$})]:[],cG({value:Z}),...!U?[WV()]:[],...!Y?[wV()]:[]]}),s2=({children:$})=>new B0({name:"m:sub",children:$}),n2=({children:$})=>new B0({name:"m:sup",children:$});class mG extends o{constructor($){super("m:nary");if(this.root.push(T$({accent:"∑",hasSuperScript:!!$.superScript,hasSubScript:!!$.subScript})),$.subScript)this.root.push(s2({children:$.subScript}));if($.superScript)this.root.push(n2({children:$.superScript}));this.root.push(y0({children:$.children}))}}class lG extends o{constructor($){super("m:nary");if(this.root.push(T$({accent:"",hasSuperScript:!!$.superScript,hasSubScript:!!$.subScript,limitLocationVal:"subSup"})),$.subScript)this.root.push(s2({children:$.subScript}));if($.superScript)this.root.push(n2({children:$.superScript}));this.root.push(y0({children:$.children}))}}class q8 extends o{constructor($){super("m:lim");for(let U of $)this.root.push(U)}}class aG extends o{constructor($){super("m:limUpp");this.root.push(y0({children:$.children})),this.root.push(new q8($.limit))}}class pG extends o{constructor($){super("m:limLow");this.root.push(y0({children:$.children})),this.root.push(new q8($.limit))}}var iG=()=>new B0({name:"m:sSupPr"});class rG extends o{constructor($){super("m:sSup");this.root.push(iG()),this.root.push(y0({children:$.children})),this.root.push(n2({children:$.superScript}))}}var sG=()=>new B0({name:"m:sSubPr"});class nG extends o{constructor($){super("m:sSub");this.root.push(sG()),this.root.push(y0({children:$.children})),this.root.push(s2({children:$.subScript}))}}var oG=()=>new B0({name:"m:sSubSupPr"});class tG extends o{constructor($){super("m:sSubSup");this.root.push(oG()),this.root.push(y0({children:$.children})),this.root.push(s2({children:$.subScript})),this.root.push(n2({children:$.superScript}))}}var eG=()=>new B0({name:"m:sPrePr"});class $K extends B0{constructor({children:$,subScript:U,superScript:Y}){super({name:"m:sPre",children:[eG(),y0({children:$}),s2({children:U}),n2({children:Y})]})}}var HV="";class C$ extends o{constructor($){super("m:deg");if($)for(let U of $)this.root.push(U)}}class UK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{hide:"m:val"})}}class YK extends o{constructor(){super("m:degHide");this.root.push(new UK({hide:1}))}}class O$ extends o{constructor($){super("m:radPr");if(!$)this.root.push(new YK)}}class ZK extends o{constructor($){super("m:rad");this.root.push(new O$(!!$.degree)),this.root.push(new C$($.degree)),this.root.push(y0({children:$.children}))}}class k$ extends o{constructor($){super("m:fName");for(let U of $)this.root.push(U)}}class E$ extends o{constructor(){super("m:funcPr")}}class QK extends o{constructor($){super("m:func");this.root.push(new E$),this.root.push(new k$($.name)),this.root.push(y0({children:$.children}))}}var jV=({character:$})=>new B0({name:"m:begChr",attributes:{character:{key:"m:val",value:$}}}),zV=({character:$})=>new B0({name:"m:endChr",attributes:{character:{key:"m:val",value:$}}}),X8=({characters:$})=>new B0({name:"m:dPr",children:$?[jV({character:$.beginningCharacter}),zV({character:$.endingCharacter})]:[]});class JK extends o{constructor($){super("m:d");this.root.push(X8({})),this.root.push(y0({children:$.children}))}}class GK extends o{constructor($){super("m:d");this.root.push(X8({characters:{beginningCharacter:"[",endingCharacter:"]"}})),this.root.push(y0({children:$.children}))}}class KK extends o{constructor($){super("m:d");this.root.push(X8({characters:{beginningCharacter:"{",endingCharacter:"}"}})),this.root.push(y0({children:$.children}))}}class qK extends o{constructor($){super("m:d");this.root.push(X8({characters:{beginningCharacter:"〈",endingCharacter:"〉"}})),this.root.push(y0({children:$.children}))}}var FV=($)=>new B0({name:"w:gridCol",attributes:$!==void 0?{width:{key:"w:w",value:T0($)}}:void 0});class S$ extends o{constructor($,U){super("w:tblGrid");for(let Y of $)this.root.push(FV(Y));if(U)this.root.push(new VK(U))}}class XK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id"})}}class VK extends o{constructor($){super("w:tblGridChange");this.root.push(new XK({id:$.id})),this.root.push(new S$($.columnWidths))}}class BK extends o{constructor($){super("w:ins");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.addChildElement(new p2($))}}class LK extends o{constructor(){super("w:delInstrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("PAGE")}}class MK extends o{constructor(){super("w:delInstrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("NUMPAGES")}}class IK extends o{constructor(){super("w:delInstrText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push("SECTIONPAGES")}}class k9 extends o{constructor($){super("w:delText");this.root.push(new x0({space:g0.PRESERVE})),this.root.push($)}}class wK extends o{constructor($){super("w:del");Y0(this,"deletedTextRunWrapper"),this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.deletedTextRunWrapper=new WK($),this.addChildElement(this.deletedTextRunWrapper)}}class WK extends o{constructor($){super("w:r");if(this.root.push(new J2($)),$.children)for(let U of $.children){if(typeof U==="string"){switch(U){case N2.CURRENT:this.root.push($2()),this.root.push(new LK),this.root.push(I2()),this.root.push(U2());break;case N2.TOTAL_PAGES:this.root.push($2()),this.root.push(new MK),this.root.push(I2()),this.root.push(U2());break;case N2.TOTAL_PAGES_IN_SECTION:this.root.push($2()),this.root.push(new IK),this.root.push(I2()),this.root.push(U2());break;default:this.root.push(new k9(U));break}continue}this.root.push(U)}else if($.text)this.root.push(new k9($.text));if($.break)for(let U=0;U<$.break;U++)this.root.splice(1,0,SQ())}}class v$ extends o{constructor($){super("w:ins");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}class _$ extends o{constructor($){super("w:del");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}class y$ extends o{constructor($){super("w:cellIns");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}class b$ extends o{constructor($){super("w:cellDel");this.root.push(new _0({id:$.id,author:$.author,date:$.date}))}}var NV={CONTINUE:"cont",RESTART:"rest"};class g$ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id",author:"w:author",date:"w:date",verticalMerge:"w:vMerge",verticalMergeOriginal:"w:vMergeOrig"})}}class x$ extends o{constructor($){super("w:cellMerge");this.root.push(new g$($))}}var HK={TOP:"top",CENTER:"center",BOTTOM:"bottom"},jK=R0(W0({},HK),{BOTH:"both"}),RV=jK,f$=($)=>new B0({name:"w:vAlign",attributes:{verticalAlign:{key:"w:val",value:$}}}),zK=({marginUnitType:$=l1.DXA,top:U,left:Y,bottom:Z,right:J})=>[{name:"w:top",size:U},{name:"w:left",size:Y},{name:"w:bottom",size:Z},{name:"w:right",size:J}].filter((G)=>G.size!==void 0).map(({name:G,size:X})=>M1(G,{type:$,size:X})),DV=($)=>{let U=zK($);if(U.length===0)return;return new B0({name:"w:tblCellMar",children:U})},AV=($)=>{let U=zK($);if(U.length===0)return;return new B0({name:"w:tcMar",children:U})},l1={AUTO:"auto",DXA:"dxa",NIL:"nil",PERCENTAGE:"pct"},M1=($,{type:U=l1.AUTO,size:Y})=>{let Z=Y;if(U===l1.PERCENTAGE&&typeof Y==="number")Z=`${Y}%`;return new B0({name:$,attributes:{type:{key:"w:type",value:U},size:{key:"w:w",value:s9(Z)}}})};class h$ extends Q2{constructor($){super("w:tcBorders");if($.top)this.root.push(N0("w:top",$.top));if($.start)this.root.push(N0("w:start",$.start));if($.left)this.root.push(N0("w:left",$.left));if($.bottom)this.root.push(N0("w:bottom",$.bottom));if($.end)this.root.push(N0("w:end",$.end));if($.right)this.root.push(N0("w:right",$.right))}}class FK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class u$ extends o{constructor($){super("w:gridSpan");this.root.push(new FK({val:S0($)}))}}var d$={CONTINUE:"continue",RESTART:"restart"};class NK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class a1 extends o{constructor($){super("w:vMerge");this.root.push(new NK({val:$}))}}var PV={BOTTOM_TO_TOP_LEFT_TO_RIGHT:"btLr",LEFT_TO_RIGHT_TOP_TO_BOTTOM:"lrTb",TOP_TO_BOTTOM_RIGHT_TO_LEFT:"tbRl"};class RK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class c$ extends o{constructor($){super("w:textDirection");this.root.push(new RK({val:$}))}}class m$ extends Q2{constructor($){super("w:tcPr",$.includeIfEmpty);if($.width)this.root.push(M1("w:tcW",$.width));if($.columnSpan)this.root.push(new u$($.columnSpan));if($.verticalMerge)this.root.push(new a1($.verticalMerge));else if($.rowSpan&&$.rowSpan>1)this.root.push(new a1(d$.RESTART));if($.borders)this.root.push(new h$($.borders));if($.shading)this.root.push(j1($.shading));if($.margins){let U=AV($.margins);if(U)this.root.push(U)}if($.textDirection)this.root.push(new c$($.textDirection));if($.verticalAlign)this.root.push(f$($.verticalAlign));if($.insertion)this.root.push(new y$($.insertion));if($.deletion)this.root.push(new b$($.deletion));if($.revision)this.root.push(new DK($.revision));if($.cellMerge)this.root.push(new x$($.cellMerge))}}class DK extends o{constructor($){super("w:tcPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.root.push(new m$(R0(W0({},$),{includeIfEmpty:!0})))}}class V8 extends o{constructor($){super("w:tc");this.options=$,this.root.push(new m$($));for(let U of $.children)this.root.push(U)}prepForXml($){if(!(this.root[this.root.length-1]instanceof h0))this.root.push(new h0({}));return super.prepForXml($)}}var x2={style:Q8.NONE,size:0,color:"auto"},f2={style:Q8.SINGLE,size:4,color:"auto"};class B8 extends o{constructor($){var U,Y,Z,J,G,X;super("w:tblBorders");this.root.push(N0("w:top",(U=$.top)!=null?U:f2)),this.root.push(N0("w:left",(Y=$.left)!=null?Y:f2)),this.root.push(N0("w:bottom",(Z=$.bottom)!=null?Z:f2)),this.root.push(N0("w:right",(J=$.right)!=null?J:f2)),this.root.push(N0("w:insideH",(G=$.insideHorizontal)!=null?G:f2)),this.root.push(N0("w:insideV",(X=$.insideVertical)!=null?X:f2))}}Y0(B8,"NONE",{top:x2,bottom:x2,left:x2,right:x2,insideHorizontal:x2,insideVertical:x2});var TV={MARGIN:"margin",PAGE:"page",TEXT:"text"},CV={CENTER:"center",INSIDE:"inside",LEFT:"left",OUTSIDE:"outside",RIGHT:"right"},OV={CENTER:"center",INSIDE:"inside",BOTTOM:"bottom",OUTSIDE:"outside",INLINE:"inline",TOP:"top"},kV={NEVER:"never",OVERLAP:"overlap"},EV=($)=>new B0({name:"w:tblOverlap",attributes:{val:{key:"w:val",value:$}}}),AK=({horizontalAnchor:$,verticalAnchor:U,absoluteHorizontalPosition:Y,relativeHorizontalPosition:Z,absoluteVerticalPosition:J,relativeVerticalPosition:G,bottomFromText:X,topFromText:Q,leftFromText:B,rightFromText:F,overlap:z})=>new B0({name:"w:tblpPr",attributes:{leftFromText:{key:"w:leftFromText",value:B===void 0?void 0:T0(B)},rightFromText:{key:"w:rightFromText",value:F===void 0?void 0:T0(F)},topFromText:{key:"w:topFromText",value:Q===void 0?void 0:T0(Q)},bottomFromText:{key:"w:bottomFromText",value:X===void 0?void 0:T0(X)},absoluteHorizontalPosition:{key:"w:tblpX",value:Y===void 0?void 0:e0(Y)},absoluteVerticalPosition:{key:"w:tblpY",value:J===void 0?void 0:e0(J)},horizontalAnchor:{key:"w:horzAnchor",value:$},relativeHorizontalPosition:{key:"w:tblpXSpec",value:Z},relativeVerticalPosition:{key:"w:tblpYSpec",value:G},verticalAnchor:{key:"w:vertAnchor",value:U}},children:z?[EV(z)]:void 0}),SV={AUTOFIT:"autofit",FIXED:"fixed"},PK=($)=>new B0({name:"w:tblLayout",attributes:{type:{key:"w:type",value:$}}}),vV={DXA:"dxa"},TK=({type:$=vV.DXA,value:U})=>new B0({name:"w:tblCellSpacing",attributes:{type:{key:"w:type",value:$},value:{key:"w:w",value:s9(U)}}}),CK=({firstRow:$,lastRow:U,firstColumn:Y,lastColumn:Z,noHBand:J,noVBand:G})=>new B0({name:"w:tblLook",attributes:{firstRow:{key:"w:firstRow",value:$},lastRow:{key:"w:lastRow",value:U},firstColumn:{key:"w:firstColumn",value:Y},lastColumn:{key:"w:lastColumn",value:Z},noHBand:{key:"w:noHBand",value:J},noVBand:{key:"w:noVBand",value:G}}});class L8 extends Q2{constructor($){super("w:tblPr",$.includeIfEmpty);if($.style)this.root.push(new Y2("w:tblStyle",$.style));if($.float)this.root.push(AK($.float));if($.visuallyRightToLeft!==void 0)this.root.push(new X0("w:bidiVisual",$.visuallyRightToLeft));if($.width)this.root.push(M1("w:tblW",$.width));if($.alignment)this.root.push(n9($.alignment));if($.indent)this.root.push(M1("w:tblInd",$.indent));if($.borders)this.root.push(new B8($.borders));if($.shading)this.root.push(j1($.shading));if($.layout)this.root.push(PK($.layout));if($.cellMargin){let U=DV($.cellMargin);if(U)this.root.push(U)}if($.tableLook)this.root.push(CK($.tableLook));if($.cellSpacing)this.root.push(TK($.cellSpacing));if($.revision)this.root.push(new OK($.revision))}}class OK extends o{constructor($){super("w:tblPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.root.push(new L8(R0(W0({},$),{includeIfEmpty:!0})))}}class kK extends r2{constructor({rows:$,width:U,columnWidths:Y=Array(Math.max(...$.map((H)=>H.CellCount))).fill(100),columnWidthsRevision:Z,margins:J,indent:G,float:X,layout:Q,style:B,borders:F,alignment:z,visuallyRightToLeft:W,tableLook:k,cellSpacing:D,revision:C}){super("w:tbl");this.root.push(new L8({borders:F!=null?F:{},width:U!=null?U:{size:100},indent:G,float:X,layout:Q,style:B,alignment:z,cellMargin:J,visuallyRightToLeft:W,tableLook:k,cellSpacing:D,revision:C})),this.root.push(new S$(Y,Z));for(let H of $)this.root.push(H);$.forEach((H,O)=>{if(O===$.length-1)return;let V=0;H.cells.forEach((j)=>{if(j.options.rowSpan&&j.options.rowSpan>1){let M=new V8({rowSpan:j.options.rowSpan-1,columnSpan:j.options.columnSpan,borders:j.options.borders,children:[],verticalMerge:d$.CONTINUE});$[O+1].addCellToColumnIndex(M,V)}V+=j.options.columnSpan||1})})}}var _V={AUTO:"auto",ATLEAST:"atLeast",EXACT:"exact"},EK=($,U)=>new B0({name:"w:trHeight",attributes:{value:{key:"w:val",value:T0($)},rule:{key:"w:hRule",value:U}}});class M8 extends Q2{constructor($){super("w:trPr",$.includeIfEmpty);if($.cantSplit!==void 0)this.root.push(new X0("w:cantSplit",$.cantSplit));if($.tableHeader!==void 0)this.root.push(new X0("w:tblHeader",$.tableHeader));if($.height)this.root.push(EK($.height.value,$.height.rule));if($.cellSpacing)this.root.push(TK($.cellSpacing));if($.insertion)this.root.push(new v$($.insertion));if($.deletion)this.root.push(new _$($.deletion));if($.revision)this.root.push(new l$($.revision))}}class l$ extends o{constructor($){super("w:trPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.root.push(new M8(R0(W0({},$),{includeIfEmpty:!0})))}}class SK extends o{constructor($){super("w:tr");this.options=$,this.root.push(new M8($));for(let U of $.children)this.root.push(U)}get CellCount(){return this.options.children.length}get cells(){return this.root.filter(($)=>$ instanceof V8)}addCellToIndex($,U){this.root.splice(U+1,0,$)}addCellToColumnIndex($,U){let Y=this.columnIndexToRootIndex(U,!0);this.addCellToIndex($,Y-1)}rootIndexToColumnIndex($){if($<1||$>=this.root.length)throw Error(`cell 'rootIndex' should between 1 to ${this.root.length-1}`);let U=0;for(let Y=1;Y<$;Y++){let Z=this.root[Y];U+=Z.options.columnSpan||1}return U}columnIndexToRootIndex($,U=!1){if($<0)throw Error("cell 'columnIndex' should not less than zero");let Y=0,Z=1;while(Y<=$){if(Z>=this.root.length)if(U)return this.root.length;else throw Error(`cell 'columnIndex' should not great than ${Y-1}`);let J=this.root[Z];Z+=1,Y+=J&&J.options.columnSpan||1}return Z-1}}class vK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns",vt:"xmlns:vt"})}}class _K extends o{constructor(){super("Properties");this.root.push(new vK({xmlns:"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties",vt:"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"}))}}class yK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns"})}}var B2=($,U)=>new B0({name:"Default",attributes:{contentType:{key:"ContentType",value:$},extension:{key:"Extension",value:U}}}),f0=($,U)=>new B0({name:"Override",attributes:{contentType:{key:"ContentType",value:$},partName:{key:"PartName",value:U}}});class bK extends o{constructor(){super("Types");this.root.push(new yK({xmlns:"http://schemas.openxmlformats.org/package/2006/content-types"})),this.root.push(B2("image/png","png")),this.root.push(B2("image/jpeg","jpeg")),this.root.push(B2("image/jpeg","jpg")),this.root.push(B2("image/bmp","bmp")),this.root.push(B2("image/gif","gif")),this.root.push(B2("image/svg+xml","svg")),this.root.push(B2("application/vnd.openxmlformats-package.relationships+xml","rels")),this.root.push(B2("application/xml","xml")),this.root.push(B2("application/vnd.openxmlformats-officedocument.obfuscatedFont","odttf")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml","/word/document.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml","/word/styles.xml")),this.root.push(f0("application/vnd.openxmlformats-package.core-properties+xml","/docProps/core.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.custom-properties+xml","/docProps/custom.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.extended-properties+xml","/docProps/app.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml","/word/numbering.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml","/word/footnotes.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml","/word/endnotes.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml","/word/settings.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml","/word/comments.xml")),this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml","/word/fontTable.xml"))}addFooter($){this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",`/word/footer${$}.xml`))}addHeader($){this.root.push(f0("application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",`/word/header${$}.xml`))}}var p1={wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",cp:"http://schemas.openxmlformats.org/package/2006/metadata/core-properties",dc:"http://purl.org/dc/elements/1.1/",dcterms:"http://purl.org/dc/terms/",dcmitype:"http://purl.org/dc/dcmitype/",xsi:"http://www.w3.org/2001/XMLSchema-instance",cx:"http://schemas.microsoft.com/office/drawing/2014/chartex",cx1:"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex",cx2:"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex",cx3:"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex",cx4:"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex",cx5:"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex",cx6:"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex",cx7:"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex",cx8:"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex",aink:"http://schemas.microsoft.com/office/drawing/2016/ink",am3d:"http://schemas.microsoft.com/office/drawing/2017/model3d",w16cex:"http://schemas.microsoft.com/office/word/2018/wordml/cex",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16:"http://schemas.microsoft.com/office/word/2018/wordml",w16sdtdh:"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash",w16se:"http://schemas.microsoft.com/office/word/2015/wordml/symex"};class o2 extends I0{constructor($,U){super(W0({Ignorable:U},Object.fromEntries($.map((Y)=>[Y,p1[Y]]))));Y0(this,"xmlKeys",W0({Ignorable:"mc:Ignorable"},Object.fromEntries(Object.keys(p1).map((Y)=>[Y,`xmlns:${Y}`]))))}}class gK extends o{constructor($){super("cp:coreProperties");if(this.root.push(new o2(["cp","dc","dcterms","dcmitype","xsi"])),$.title)this.root.push(new L2("dc:title",$.title));if($.subject)this.root.push(new L2("dc:subject",$.subject));if($.creator)this.root.push(new L2("dc:creator",$.creator));if($.keywords)this.root.push(new L2("cp:keywords",$.keywords));if($.description)this.root.push(new L2("dc:description",$.description));if($.lastModifiedBy)this.root.push(new L2("cp:lastModifiedBy",$.lastModifiedBy));if($.revision)this.root.push(new L2("cp:revision",String($.revision)));this.root.push(new E9("dcterms:created")),this.root.push(new E9("dcterms:modified"))}}class xK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{type:"xsi:type"})}}class E9 extends o{constructor($){super($);this.root.push(new xK({type:"dcterms:W3CDTF"})),this.root.push(OQ(new Date))}}class fK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{xmlns:"xmlns",vt:"xmlns:vt"})}}class hK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{formatId:"fmtid",pid:"pid",name:"name"})}}class uK extends o{constructor($,U){super("property");this.root.push(new hK({formatId:"{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",pid:$.toString(),name:U.name})),this.root.push(new dK(U.value))}}class dK extends o{constructor($){super("vt:lpwstr");this.root.push($)}}class cK extends o{constructor($){super("Properties");Y0(this,"nextId"),Y0(this,"properties",[]),this.root.push(new fK({xmlns:"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties",vt:"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"})),this.nextId=2;for(let U of $)this.addCustomProperty(U)}prepForXml($){return this.properties.forEach((U)=>this.root.push(U)),super.prepForXml($)}addCustomProperty($){this.properties.push(new uK(this.nextId++,$))}}var mK=({space:$,count:U,separate:Y,equalWidth:Z,children:J})=>new B0({name:"w:cols",attributes:{space:{key:"w:space",value:$===void 0?void 0:T0($)},count:{key:"w:num",value:U===void 0?void 0:S0(U)},separate:{key:"w:sep",value:Y},equalWidth:{key:"w:equalWidth",value:Z}},children:!Z&&J?J:void 0}),yV={DEFAULT:"default",LINES:"lines",LINES_AND_CHARS:"linesAndChars",SNAP_TO_CHARS:"snapToChars"},lK=({type:$,linePitch:U,charSpace:Y})=>new B0({name:"w:docGrid",attributes:{type:{key:"w:type",value:$},linePitch:{key:"w:linePitch",value:S0(U)},charSpace:{key:"w:charSpace",value:Y?S0(Y):void 0}}}),E2={DEFAULT:"default",FIRST:"first",EVEN:"even"},S9={HEADER:"w:headerReference",FOOTER:"w:footerReference"},f1=($,U)=>new B0({name:$,attributes:{type:{key:"w:type",value:U.type||E2.DEFAULT},id:{key:"r:id",value:`rId${U.id}`}}}),bV={NEW_PAGE:"newPage",NEW_SECTION:"newSection",CONTINUOUS:"continuous"},aK=({countBy:$,start:U,restart:Y,distance:Z})=>new B0({name:"w:lnNumType",attributes:{countBy:{key:"w:countBy",value:$===void 0?void 0:S0($)},start:{key:"w:start",value:U===void 0?void 0:S0(U)},restart:{key:"w:restart",value:Y},distance:{key:"w:distance",value:Z===void 0?void 0:T0(Z)}}}),gV={ALL_PAGES:"allPages",FIRST_PAGE:"firstPage",NOT_FIRST_PAGE:"notFirstPage"},xV={PAGE:"page",TEXT:"text"},fV={BACK:"back",FRONT:"front"};class v9 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{display:"w:display",offsetFrom:"w:offsetFrom",zOrder:"w:zOrder"})}}class a$ extends Q2{constructor($){super("w:pgBorders");if(!$)return this;if($.pageBorders)this.root.push(new v9({display:$.pageBorders.display,offsetFrom:$.pageBorders.offsetFrom,zOrder:$.pageBorders.zOrder}));else this.root.push(new v9({}));if($.pageBorderTop)this.root.push(N0("w:top",$.pageBorderTop));if($.pageBorderLeft)this.root.push(N0("w:left",$.pageBorderLeft));if($.pageBorderBottom)this.root.push(N0("w:bottom",$.pageBorderBottom));if($.pageBorderRight)this.root.push(N0("w:right",$.pageBorderRight))}}var pK=($,U,Y,Z,J,G,X)=>new B0({name:"w:pgMar",attributes:{top:{key:"w:top",value:e0($)},right:{key:"w:right",value:T0(U)},bottom:{key:"w:bottom",value:e0(Y)},left:{key:"w:left",value:T0(Z)},header:{key:"w:header",value:T0(J)},footer:{key:"w:footer",value:T0(G)},gutter:{key:"w:gutter",value:T0(X)}}}),hV={HYPHEN:"hyphen",PERIOD:"period",COLON:"colon",EM_DASH:"emDash",EN_DASH:"endash"},iK=({start:$,formatType:U,separator:Y})=>new B0({name:"w:pgNumType",attributes:{start:{key:"w:start",value:$===void 0?void 0:S0($)},formatType:{key:"w:fmt",value:U},separator:{key:"w:chapSep",value:Y}}}),i1={PORTRAIT:"portrait",LANDSCAPE:"landscape"},rK=({width:$,height:U,orientation:Y,code:Z})=>{let J=T0($),G=T0(U);return new B0({name:"w:pgSz",attributes:{width:{key:"w:w",value:Y===i1.LANDSCAPE?G:J},height:{key:"w:h",value:Y===i1.LANDSCAPE?J:G},orientation:{key:"w:orient",value:Y},code:{key:"w:code",value:Z}}})},uV={LEFT_TO_RIGHT_TOP_TO_BOTTOM:"lrTb",TOP_TO_BOTTOM_RIGHT_TO_LEFT:"tbRl"};class sK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class p$ extends o{constructor($){super("w:textDirection");this.root.push(new sK({val:$}))}}var dV={NEXT_PAGE:"nextPage",NEXT_COLUMN:"nextColumn",CONTINUOUS:"continuous",EVEN_PAGE:"evenPage",ODD_PAGE:"oddPage"},nK=($)=>new B0({name:"w:type",attributes:{val:{key:"w:val",value:$}}}),F2={TOP:1440,RIGHT:1440,BOTTOM:1440,LEFT:1440,HEADER:708,FOOTER:708,GUTTER:0},h1={WIDTH:11906,HEIGHT:16838,ORIENTATION:i1.PORTRAIT};class I8 extends o{constructor({page:{size:{width:$=h1.WIDTH,height:U=h1.HEIGHT,orientation:Y=h1.ORIENTATION}={},margin:{top:Z=F2.TOP,right:J=F2.RIGHT,bottom:G=F2.BOTTOM,left:X=F2.LEFT,header:Q=F2.HEADER,footer:B=F2.FOOTER,gutter:F=F2.GUTTER}={},pageNumbers:z={},borders:W,textDirection:k}={},grid:{linePitch:D=360,charSpace:C,type:H}={},headerWrapperGroup:O={},footerWrapperGroup:V={},lineNumbers:j,titlePage:M,verticalAlign:L,column:A,type:y,revision:g}={}){super("w:sectPr");if(this.addHeaderFooterGroup(S9.HEADER,O),this.addHeaderFooterGroup(S9.FOOTER,V),y)this.root.push(nK(y));if(this.root.push(rK({width:$,height:U,orientation:Y})),this.root.push(pK(Z,J,G,X,Q,B,F)),W)this.root.push(new a$(W));if(j)this.root.push(aK(j));if(this.root.push(iK(z)),A)this.root.push(mK(A));if(L)this.root.push(f$(L));if(M!==void 0)this.root.push(new X0("w:titlePg",M));if(k)this.root.push(new p$(k));if(g)this.root.push(new i$(g));this.root.push(lK({linePitch:D,charSpace:C,type:H}))}addHeaderFooterGroup($,U){if(U.default)this.root.push(f1($,{type:E2.DEFAULT,id:U.default.View.ReferenceId}));if(U.first)this.root.push(f1($,{type:E2.FIRST,id:U.first.View.ReferenceId}));if(U.even)this.root.push(f1($,{type:E2.EVEN,id:U.even.View.ReferenceId}))}}class i$ extends o{constructor($){super("w:sectPrChange");this.root.push(new _0({id:$.id,author:$.author,date:$.date})),this.root.push(new I8($))}}class oK extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{width:"w:w",space:"w:space"})}}class tK extends o{constructor($){super("w:col");this.root.push(new oK({width:T0($.width),space:$.space===void 0?void 0:T0($.space)}))}}class r$ extends o{constructor(){super("w:body");Y0(this,"sections",[])}addSection($){let U=this.sections.pop();this.root.push(this.createSectionParagraph(U)),this.sections.push(new I8($))}prepForXml($){if(this.sections.length===1)this.root.splice(0,1),this.root.push(this.sections.pop());return super.prepForXml($)}push($){this.root.push($)}createSectionParagraph($){let U=new h0({}),Y=new Z2({});return Y.push($),U.addChildElement(Y),U}}class s$ extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{color:"w:color",themeColor:"w:themeColor",themeShade:"w:themeShade",themeTint:"w:themeTint"})}}class n$ extends o{constructor($){super("w:background");this.root.push(new s$({color:$.color===void 0?void 0:S2($.color),themeColor:$.themeColor,themeShade:$.themeShade===void 0?void 0:D9($.themeShade),themeTint:$.themeTint===void 0?void 0:D9($.themeTint)}))}}class eK extends o{constructor($){super("w:document");if(Y0(this,"body"),this.root.push(new o2(["wpc","mc","o","r","m","v","wp14","wp","w10","w","w14","w15","wpg","wpi","wne","wps","cx","cx1","cx2","cx3","cx4","cx5","cx6","cx7","cx8","aink","am3d","w16cex","w16cid","w16","w16sdtdh","w16se"],"w14 w15 wp14")),this.body=new r$,$.background)this.root.push(new n$($.background));this.root.push(this.body)}add($){return this.body.push($),this}get Body(){return this.body}}class $5{constructor($){Y0(this,"document"),Y0(this,"relationships"),this.document=new eK($),this.relationships=new W2}get View(){return this.document}get Relationships(){return this.relationships}}class U5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",Ignorable:"mc:Ignorable"})}}class Y5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{type:"w:type",id:"w:id"})}}class Z5 extends C0{constructor(){super({style:"EndnoteReference"});this.root.push(new I$)}}var fZ={SEPARATOR:"separator",CONTINUATION_SEPARATOR:"continuationSeparator"};class u1 extends o{constructor($){super("w:endnote");this.root.push(new Y5({type:$.type,id:$.id}));for(let U=0;U<$.children.length;U++){let Y=$.children[U];if(U===0)Y.addRunToFront(new Z5);this.root.push(Y)}}}class Q5 extends o{constructor(){super("w:continuationSeparator")}}class o$ extends C0{constructor(){super({});this.root.push(new Q5)}}class J5 extends o{constructor(){super("w:separator")}}class t$ extends C0{constructor(){super({});this.root.push(new J5)}}class e$ extends o{constructor(){super("w:endnotes");this.root.push(new U5({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",Ignorable:"w14 w15 wp14"}));let $=new u1({id:-1,type:fZ.SEPARATOR,children:[new h0({spacing:{after:0,line:240,lineRule:v2.AUTO},children:[new t$]})]});this.root.push($);let U=new u1({id:0,type:fZ.CONTINUATION_SEPARATOR,children:[new h0({spacing:{after:0,line:240,lineRule:v2.AUTO},children:[new o$]})]});this.root.push(U)}createEndnote($,U){let Y=new u1({id:$,children:U});this.root.push(Y)}}class G5{constructor(){Y0(this,"endnotes"),Y0(this,"relationships"),this.endnotes=new e$,this.relationships=new W2}get View(){return this.endnotes}get Relationships(){return this.relationships}}class K5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",cp:"xmlns:cp",dc:"xmlns:dc",dcterms:"xmlns:dcterms",dcmitype:"xmlns:dcmitype",xsi:"xmlns:xsi",type:"xsi:type"})}}var cV=class extends Y8{constructor(U,Y){super("w:ftr",Y);if(Y0(this,"refId"),this.refId=U,!Y)this.root.push(new K5({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape"}))}get ReferenceId(){return this.refId}add(U){this.root.push(U)}};class $U{constructor($,U,Y){Y0(this,"footer"),Y0(this,"relationships"),this.media=$,this.footer=new cV(U,Y),this.relationships=new W2}add($){this.footer.add($)}addChildElement($){this.footer.addChildElement($)}get View(){return this.footer}get Relationships(){return this.relationships}get Media(){return this.media}}class q5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{type:"w:type",id:"w:id"})}}class X5 extends o{constructor(){super("w:footnoteRef")}}class V5 extends C0{constructor(){super({style:"FootnoteReference"});this.root.push(new X5)}}var hZ={SEPERATOR:"separator",CONTINUATION_SEPERATOR:"continuationSeparator"};class d1 extends o{constructor($){super("w:footnote");this.root.push(new q5({type:$.type,id:$.id}));for(let U=0;U<$.children.length;U++){let Y=$.children[U];if(U===0)Y.addRunToFront(new V5);this.root.push(Y)}}}class B5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",Ignorable:"mc:Ignorable"})}}class UU extends o{constructor(){super("w:footnotes");this.root.push(new B5({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",Ignorable:"w14 w15 wp14"}));let $=new d1({id:-1,type:hZ.SEPERATOR,children:[new h0({spacing:{after:0,line:240,lineRule:v2.AUTO},children:[new t$]})]});this.root.push($);let U=new d1({id:0,type:hZ.CONTINUATION_SEPERATOR,children:[new h0({spacing:{after:0,line:240,lineRule:v2.AUTO},children:[new o$]})]});this.root.push(U)}createFootNote($,U){let Y=new d1({id:$,children:U});this.root.push(Y)}}class L5{constructor(){Y0(this,"footnotess"),Y0(this,"relationships"),this.footnotess=new UU,this.relationships=new W2}get View(){return this.footnotess}get Relationships(){return this.relationships}}class M5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",cp:"xmlns:cp",dc:"xmlns:dc",dcterms:"xmlns:dcterms",dcmitype:"xmlns:dcmitype",xsi:"xmlns:xsi",type:"xsi:type",cx:"xmlns:cx",cx1:"xmlns:cx1",cx2:"xmlns:cx2",cx3:"xmlns:cx3",cx4:"xmlns:cx4",cx5:"xmlns:cx5",cx6:"xmlns:cx6",cx7:"xmlns:cx7",cx8:"xmlns:cx8",w16cid:"xmlns:w16cid",w16se:"xmlns:w16se"})}}var mV=class extends Y8{constructor(U,Y){super("w:hdr",Y);if(Y0(this,"refId"),this.refId=U,!Y)this.root.push(new M5({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",cx:"http://schemas.microsoft.com/office/drawing/2014/chartex",cx1:"http://schemas.microsoft.com/office/drawing/2015/9/8/chartex",cx2:"http://schemas.microsoft.com/office/drawing/2015/10/21/chartex",cx3:"http://schemas.microsoft.com/office/drawing/2016/5/9/chartex",cx4:"http://schemas.microsoft.com/office/drawing/2016/5/10/chartex",cx5:"http://schemas.microsoft.com/office/drawing/2016/5/11/chartex",cx6:"http://schemas.microsoft.com/office/drawing/2016/5/12/chartex",cx7:"http://schemas.microsoft.com/office/drawing/2016/5/13/chartex",cx8:"http://schemas.microsoft.com/office/drawing/2016/5/14/chartex",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16se:"http://schemas.microsoft.com/office/word/2015/wordml/symex"}))}get ReferenceId(){return this.refId}add(U){this.root.push(U)}};class YU{constructor($,U,Y){Y0(this,"header"),Y0(this,"relationships"),this.media=$,this.header=new mV(U,Y),this.relationships=new W2}add($){return this.header.add($),this}addChildElement($){this.header.addChildElement($)}get View(){return this.header}get Relationships(){return this.relationships}get Media(){return this.media}}class w8{constructor(){Y0(this,"map"),this.map=new Map}addImage($,U){this.map.set($,U)}get Array(){return Array.from(this.map.values())}}var lV="",n0={DECIMAL:"decimal",UPPER_ROMAN:"upperRoman",LOWER_ROMAN:"lowerRoman",UPPER_LETTER:"upperLetter",LOWER_LETTER:"lowerLetter",ORDINAL:"ordinal",CARDINAL_TEXT:"cardinalText",ORDINAL_TEXT:"ordinalText",HEX:"hex",CHICAGO:"chicago",IDEOGRAPH__DIGITAL:"ideographDigital",JAPANESE_COUNTING:"japaneseCounting",AIUEO:"aiueo",IROHA:"iroha",DECIMAL_FULL_WIDTH:"decimalFullWidth",DECIMAL_HALF_WIDTH:"decimalHalfWidth",JAPANESE_LEGAL:"japaneseLegal",JAPANESE_DIGITAL_TEN_THOUSAND:"japaneseDigitalTenThousand",DECIMAL_ENCLOSED_CIRCLE:"decimalEnclosedCircle",DECIMAL_FULL_WIDTH2:"decimalFullWidth2",AIUEO_FULL_WIDTH:"aiueoFullWidth",IROHA_FULL_WIDTH:"irohaFullWidth",DECIMAL_ZERO:"decimalZero",BULLET:"bullet",GANADA:"ganada",CHOSUNG:"chosung",DECIMAL_ENCLOSED_FULLSTOP:"decimalEnclosedFullstop",DECIMAL_ENCLOSED_PARENTHESES:"decimalEnclosedParen",DECIMAL_ENCLOSED_CIRCLE_CHINESE:"decimalEnclosedCircleChinese",IDEOGRAPH_ENCLOSED_CIRCLE:"ideographEnclosedCircle",IDEOGRAPH_TRADITIONAL:"ideographTraditional",IDEOGRAPH_ZODIAC:"ideographZodiac",IDEOGRAPH_ZODIAC_TRADITIONAL:"ideographZodiacTraditional",TAIWANESE_COUNTING:"taiwaneseCounting",IDEOGRAPH_LEGAL_TRADITIONAL:"ideographLegalTraditional",TAIWANESE_COUNTING_THOUSAND:"taiwaneseCountingThousand",TAIWANESE_DIGITAL:"taiwaneseDigital",CHINESE_COUNTING:"chineseCounting",CHINESE_LEGAL_SIMPLIFIED:"chineseLegalSimplified",CHINESE_COUNTING_THOUSAND:"chineseCountingThousand",KOREAN_DIGITAL:"koreanDigital",KOREAN_COUNTING:"koreanCounting",KOREAN_LEGAL:"koreanLegal",KOREAN_DIGITAL2:"koreanDigital2",VIETNAMESE_COUNTING:"vietnameseCounting",RUSSIAN_LOWER:"russianLower",RUSSIAN_UPPER:"russianUpper",NONE:"none",NUMBER_IN_DASH:"numberInDash",HEBREW1:"hebrew1",HEBREW2:"hebrew2",ARABIC_ALPHA:"arabicAlpha",ARABIC_ABJAD:"arabicAbjad",HINDI_VOWELS:"hindiVowels",HINDI_CONSONANTS:"hindiConsonants",HINDI_NUMBERS:"hindiNumbers",HINDI_COUNTING:"hindiCounting",THAI_LETTERS:"thaiLetters",THAI_NUMBERS:"thaiNumbers",THAI_COUNTING:"thaiCounting",BAHT_TEXT:"bahtText",DOLLAR_TEXT:"dollarText",CUSTOM:"custom"};class I5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{ilvl:"w:ilvl",tentative:"w15:tentative"})}}class w5 extends o{constructor($){super("w:numFmt");this.root.push(new O0({val:$}))}}class W5 extends o{constructor($){super("w:lvlText");this.root.push(new O0({val:$}))}}class H5 extends o{constructor($){super("w:lvlJc");this.root.push(new O0({val:$}))}}var aV={NOTHING:"nothing",SPACE:"space",TAB:"tab"};class j5 extends o{constructor($){super("w:suff");this.root.push(new O0({val:$}))}}class z5 extends o{constructor(){super("w:isLgl")}}class W8 extends o{constructor({level:$,format:U,text:Y,alignment:Z=m0.START,start:J=1,style:G,suffix:X,isLegalNumberingStyle:Q}){super("w:lvl");if(Y0(this,"paragraphProperties"),Y0(this,"runProperties"),this.root.push(new k2("w:start",S0(J))),U)this.root.push(new w5(U));if(X)this.root.push(new j5(X));if(Q)this.root.push(new z5);if(Y)this.root.push(new W5(Y));if(this.root.push(new H5(Z)),this.paragraphProperties=new Z2(G&&G.paragraph),this.runProperties=new J2(G&&G.run),this.root.push(this.paragraphProperties),this.root.push(this.runProperties),$>9)throw Error("Level cannot be greater than 9. Read more here: https://answers.microsoft.com/en-us/msoffice/forum/all/does-word-support-more-than-9-list-levels/d130fdcd-1781-446d-8c84-c6c79124e4d7");this.root.push(new I5({ilvl:S0($),tentative:1}))}}class ZU extends W8{}class F5 extends W8{}class N5 extends o{constructor($){super("w:multiLevelType");this.root.push(new O0({val:$}))}}class R5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{abstractNumId:"w:abstractNumId",restartNumberingAfterBreak:"w15:restartNumberingAfterBreak"})}}class r1 extends o{constructor($,U){super("w:abstractNum");Y0(this,"id"),this.root.push(new R5({abstractNumId:S0($),restartNumberingAfterBreak:0})),this.root.push(new N5("hybridMultilevel")),this.id=$;for(let Y of U)this.root.push(new ZU(Y))}}class D5 extends o{constructor($){super("w:abstractNumId");this.root.push(new O0({val:$}))}}class A5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{numId:"w:numId"})}}class s1 extends o{constructor($){super("w:num");if(Y0(this,"numId"),Y0(this,"reference"),Y0(this,"instance"),this.numId=$.numId,this.reference=$.reference,this.instance=$.instance,this.root.push(new A5({numId:S0($.numId)})),this.root.push(new D5(S0($.abstractNumId))),$.overrideLevels&&$.overrideLevels.length)for(let U of $.overrideLevels)this.root.push(new QU(U.num,U.start))}}class P5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{ilvl:"w:ilvl"})}}class QU extends o{constructor($,U){super("w:lvlOverride");if(this.root.push(new P5({ilvl:$})),U!==void 0)this.root.push(new C5(U))}}class T5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class C5 extends o{constructor($){super("w:startOverride");this.root.push(new T5({val:$}))}}class JU extends o{constructor($){super("w:numbering");Y0(this,"abstractNumberingMap",new Map),Y0(this,"concreteNumberingMap",new Map),Y0(this,"referenceConfigMap",new Map),Y0(this,"abstractNumUniqueNumericId",rQ()),Y0(this,"concreteNumUniqueNumericId",sQ()),this.root.push(new o2(["wpc","mc","o","r","m","v","wp14","wp","w10","w","w14","w15","wpg","wpi","wne","wps"],"w14 w15 wp14"));let U=new r1(this.abstractNumUniqueNumericId(),[{level:0,format:n0.BULLET,text:"●",alignment:m0.LEFT,style:{paragraph:{indent:{left:d0(0.5),hanging:d0(0.25)}}}},{level:1,format:n0.BULLET,text:"○",alignment:m0.LEFT,style:{paragraph:{indent:{left:d0(1),hanging:d0(0.25)}}}},{level:2,format:n0.BULLET,text:"■",alignment:m0.LEFT,style:{paragraph:{indent:{left:2160,hanging:d0(0.25)}}}},{level:3,format:n0.BULLET,text:"●",alignment:m0.LEFT,style:{paragraph:{indent:{left:2880,hanging:d0(0.25)}}}},{level:4,format:n0.BULLET,text:"○",alignment:m0.LEFT,style:{paragraph:{indent:{left:3600,hanging:d0(0.25)}}}},{level:5,format:n0.BULLET,text:"■",alignment:m0.LEFT,style:{paragraph:{indent:{left:4320,hanging:d0(0.25)}}}},{level:6,format:n0.BULLET,text:"●",alignment:m0.LEFT,style:{paragraph:{indent:{left:5040,hanging:d0(0.25)}}}},{level:7,format:n0.BULLET,text:"●",alignment:m0.LEFT,style:{paragraph:{indent:{left:5760,hanging:d0(0.25)}}}},{level:8,format:n0.BULLET,text:"●",alignment:m0.LEFT,style:{paragraph:{indent:{left:6480,hanging:d0(0.25)}}}}]);this.concreteNumberingMap.set("default-bullet-numbering",new s1({numId:1,abstractNumId:U.id,reference:"default-bullet-numbering",instance:0,overrideLevels:[{num:0,start:1}]})),this.abstractNumberingMap.set("default-bullet-numbering",U);for(let Y of $.config)this.abstractNumberingMap.set(Y.reference,new r1(this.abstractNumUniqueNumericId(),Y.levels)),this.referenceConfigMap.set(Y.reference,Y.levels)}prepForXml($){for(let U of this.abstractNumberingMap.values())this.root.push(U);for(let U of this.concreteNumberingMap.values())this.root.push(U);return super.prepForXml($)}createConcreteNumberingInstance($,U){let Y=this.abstractNumberingMap.get($);if(!Y)return;let Z=`${$}-${U}`;if(this.concreteNumberingMap.has(Z))return;let J=this.referenceConfigMap.get($),G=J&&J[0].start,X={numId:this.concreteNumUniqueNumericId(),abstractNumId:Y.id,reference:$,instance:U,overrideLevels:[typeof G==="number"&&Number.isInteger(G)?{num:0,start:G}:{num:0,start:1}]};this.concreteNumberingMap.set(Z,new s1(X))}get ConcreteNumbering(){return Array.from(this.concreteNumberingMap.values())}get ReferenceConfig(){return Array.from(this.referenceConfigMap.values())}}var pV=($)=>new B0({name:"w:compatSetting",attributes:{version:{key:"w:val",value:$},name:{key:"w:name",value:"compatibilityMode"},uri:{key:"w:uri",value:"http://schemas.microsoft.com/office/word"}}});class O5 extends o{constructor($){super("w:compat");if($.version)this.root.push(pV($.version));if($.useSingleBorderforContiguousCells)this.root.push(new X0("w:useSingleBorderforContiguousCells",$.useSingleBorderforContiguousCells));if($.wordPerfectJustification)this.root.push(new X0("w:wpJustification",$.wordPerfectJustification));if($.noTabStopForHangingIndent)this.root.push(new X0("w:noTabHangInd",$.noTabStopForHangingIndent));if($.noLeading)this.root.push(new X0("w:noLeading",$.noLeading));if($.spaceForUnderline)this.root.push(new X0("w:spaceForUL",$.spaceForUnderline));if($.noColumnBalance)this.root.push(new X0("w:noColumnBalance",$.noColumnBalance));if($.balanceSingleByteDoubleByteWidth)this.root.push(new X0("w:balanceSingleByteDoubleByteWidth",$.balanceSingleByteDoubleByteWidth));if($.noExtraLineSpacing)this.root.push(new X0("w:noExtraLineSpacing",$.noExtraLineSpacing));if($.doNotLeaveBackslashAlone)this.root.push(new X0("w:doNotLeaveBackslashAlone",$.doNotLeaveBackslashAlone));if($.underlineTrailingSpaces)this.root.push(new X0("w:ulTrailSpace",$.underlineTrailingSpaces));if($.doNotExpandShiftReturn)this.root.push(new X0("w:doNotExpandShiftReturn",$.doNotExpandShiftReturn));if($.spacingInWholePoints)this.root.push(new X0("w:spacingInWholePoints",$.spacingInWholePoints));if($.lineWrapLikeWord6)this.root.push(new X0("w:lineWrapLikeWord6",$.lineWrapLikeWord6));if($.printBodyTextBeforeHeader)this.root.push(new X0("w:printBodyTextBeforeHeader",$.printBodyTextBeforeHeader));if($.printColorsBlack)this.root.push(new X0("w:printColBlack",$.printColorsBlack));if($.spaceWidth)this.root.push(new X0("w:wpSpaceWidth",$.spaceWidth));if($.showBreaksInFrames)this.root.push(new X0("w:showBreaksInFrames",$.showBreaksInFrames));if($.subFontBySize)this.root.push(new X0("w:subFontBySize",$.subFontBySize));if($.suppressBottomSpacing)this.root.push(new X0("w:suppressBottomSpacing",$.suppressBottomSpacing));if($.suppressTopSpacing)this.root.push(new X0("w:suppressTopSpacing",$.suppressTopSpacing));if($.suppressSpacingAtTopOfPage)this.root.push(new X0("w:suppressSpacingAtTopOfPage",$.suppressSpacingAtTopOfPage));if($.suppressTopSpacingWP)this.root.push(new X0("w:suppressTopSpacingWP",$.suppressTopSpacingWP));if($.suppressSpBfAfterPgBrk)this.root.push(new X0("w:suppressSpBfAfterPgBrk",$.suppressSpBfAfterPgBrk));if($.swapBordersFacingPages)this.root.push(new X0("w:swapBordersFacingPages",$.swapBordersFacingPages));if($.convertMailMergeEsc)this.root.push(new X0("w:convMailMergeEsc",$.convertMailMergeEsc));if($.truncateFontHeightsLikeWP6)this.root.push(new X0("w:truncateFontHeightsLikeWP6",$.truncateFontHeightsLikeWP6));if($.macWordSmallCaps)this.root.push(new X0("w:mwSmallCaps",$.macWordSmallCaps));if($.usePrinterMetrics)this.root.push(new X0("w:usePrinterMetrics",$.usePrinterMetrics));if($.doNotSuppressParagraphBorders)this.root.push(new X0("w:doNotSuppressParagraphBorders",$.doNotSuppressParagraphBorders));if($.wrapTrailSpaces)this.root.push(new X0("w:wrapTrailSpaces",$.wrapTrailSpaces));if($.footnoteLayoutLikeWW8)this.root.push(new X0("w:footnoteLayoutLikeWW8",$.footnoteLayoutLikeWW8));if($.shapeLayoutLikeWW8)this.root.push(new X0("w:shapeLayoutLikeWW8",$.shapeLayoutLikeWW8));if($.alignTablesRowByRow)this.root.push(new X0("w:alignTablesRowByRow",$.alignTablesRowByRow));if($.forgetLastTabAlignment)this.root.push(new X0("w:forgetLastTabAlignment",$.forgetLastTabAlignment));if($.adjustLineHeightInTable)this.root.push(new X0("w:adjustLineHeightInTable",$.adjustLineHeightInTable));if($.autoSpaceLikeWord95)this.root.push(new X0("w:autoSpaceLikeWord95",$.autoSpaceLikeWord95));if($.noSpaceRaiseLower)this.root.push(new X0("w:noSpaceRaiseLower",$.noSpaceRaiseLower));if($.doNotUseHTMLParagraphAutoSpacing)this.root.push(new X0("w:doNotUseHTMLParagraphAutoSpacing",$.doNotUseHTMLParagraphAutoSpacing));if($.layoutRawTableWidth)this.root.push(new X0("w:layoutRawTableWidth",$.layoutRawTableWidth));if($.layoutTableRowsApart)this.root.push(new X0("w:layoutTableRowsApart",$.layoutTableRowsApart));if($.useWord97LineBreakRules)this.root.push(new X0("w:useWord97LineBreakRules",$.useWord97LineBreakRules));if($.doNotBreakWrappedTables)this.root.push(new X0("w:doNotBreakWrappedTables",$.doNotBreakWrappedTables));if($.doNotSnapToGridInCell)this.root.push(new X0("w:doNotSnapToGridInCell",$.doNotSnapToGridInCell));if($.selectFieldWithFirstOrLastCharacter)this.root.push(new X0("w:selectFldWithFirstOrLastChar",$.selectFieldWithFirstOrLastCharacter));if($.applyBreakingRules)this.root.push(new X0("w:applyBreakingRules",$.applyBreakingRules));if($.doNotWrapTextWithPunctuation)this.root.push(new X0("w:doNotWrapTextWithPunct",$.doNotWrapTextWithPunctuation));if($.doNotUseEastAsianBreakRules)this.root.push(new X0("w:doNotUseEastAsianBreakRules",$.doNotUseEastAsianBreakRules));if($.useWord2002TableStyleRules)this.root.push(new X0("w:useWord2002TableStyleRules",$.useWord2002TableStyleRules));if($.growAutofit)this.root.push(new X0("w:growAutofit",$.growAutofit));if($.useFELayout)this.root.push(new X0("w:useFELayout",$.useFELayout));if($.useNormalStyleForList)this.root.push(new X0("w:useNormalStyleForList",$.useNormalStyleForList));if($.doNotUseIndentAsNumberingTabStop)this.root.push(new X0("w:doNotUseIndentAsNumberingTabStop",$.doNotUseIndentAsNumberingTabStop));if($.useAlternateEastAsianLineBreakRules)this.root.push(new X0("w:useAltKinsokuLineBreakRules",$.useAlternateEastAsianLineBreakRules));if($.allowSpaceOfSameStyleInTable)this.root.push(new X0("w:allowSpaceOfSameStyleInTable",$.allowSpaceOfSameStyleInTable));if($.doNotSuppressIndentation)this.root.push(new X0("w:doNotSuppressIndentation",$.doNotSuppressIndentation));if($.doNotAutofitConstrainedTables)this.root.push(new X0("w:doNotAutofitConstrainedTables",$.doNotAutofitConstrainedTables));if($.autofitToFirstFixedWidthCell)this.root.push(new X0("w:autofitToFirstFixedWidthCell",$.autofitToFirstFixedWidthCell));if($.underlineTabInNumberingList)this.root.push(new X0("w:underlineTabInNumList",$.underlineTabInNumberingList));if($.displayHangulFixedWidth)this.root.push(new X0("w:displayHangulFixedWidth",$.displayHangulFixedWidth));if($.splitPgBreakAndParaMark)this.root.push(new X0("w:splitPgBreakAndParaMark",$.splitPgBreakAndParaMark));if($.doNotVerticallyAlignCellWithSp)this.root.push(new X0("w:doNotVertAlignCellWithSp",$.doNotVerticallyAlignCellWithSp));if($.doNotBreakConstrainedForcedTable)this.root.push(new X0("w:doNotBreakConstrainedForcedTable",$.doNotBreakConstrainedForcedTable));if($.ignoreVerticalAlignmentInTextboxes)this.root.push(new X0("w:doNotVertAlignInTxbx",$.ignoreVerticalAlignmentInTextboxes));if($.useAnsiKerningPairs)this.root.push(new X0("w:useAnsiKerningPairs",$.useAnsiKerningPairs));if($.cachedColumnBalance)this.root.push(new X0("w:cachedColBalance",$.cachedColumnBalance))}}class k5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{wpc:"xmlns:wpc",mc:"xmlns:mc",o:"xmlns:o",r:"xmlns:r",m:"xmlns:m",v:"xmlns:v",wp14:"xmlns:wp14",wp:"xmlns:wp",w10:"xmlns:w10",w:"xmlns:w",w14:"xmlns:w14",w15:"xmlns:w15",wpg:"xmlns:wpg",wpi:"xmlns:wpi",wne:"xmlns:wne",wps:"xmlns:wps",Ignorable:"mc:Ignorable"})}}class E5 extends o{constructor($){var U,Y,Z,J,G,X,Q,B;super("w:settings");if(this.root.push(new k5({wpc:"http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006",o:"urn:schemas-microsoft-com:office:office",r:"http://schemas.openxmlformats.org/officeDocument/2006/relationships",m:"http://schemas.openxmlformats.org/officeDocument/2006/math",v:"urn:schemas-microsoft-com:vml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",wp:"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",w10:"urn:schemas-microsoft-com:office:word",w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wpg:"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",wpi:"http://schemas.microsoft.com/office/word/2010/wordprocessingInk",wne:"http://schemas.microsoft.com/office/word/2006/wordml",wps:"http://schemas.microsoft.com/office/word/2010/wordprocessingShape",Ignorable:"w14 w15 wp14"})),this.root.push(new X0("w:displayBackgroundShape",!0)),$.trackRevisions!==void 0)this.root.push(new X0("w:trackRevisions",$.trackRevisions));if($.evenAndOddHeaders!==void 0)this.root.push(new X0("w:evenAndOddHeaders",$.evenAndOddHeaders));if($.updateFields!==void 0)this.root.push(new X0("w:updateFields",$.updateFields));if($.defaultTabStop!==void 0)this.root.push(new k2("w:defaultTabStop",$.defaultTabStop));if(((U=$.hyphenation)==null?void 0:U.autoHyphenation)!==void 0)this.root.push(new X0("w:autoHyphenation",$.hyphenation.autoHyphenation));if(((Y=$.hyphenation)==null?void 0:Y.hyphenationZone)!==void 0)this.root.push(new k2("w:hyphenationZone",$.hyphenation.hyphenationZone));if(((Z=$.hyphenation)==null?void 0:Z.consecutiveHyphenLimit)!==void 0)this.root.push(new k2("w:consecutiveHyphenLimit",$.hyphenation.consecutiveHyphenLimit));if(((J=$.hyphenation)==null?void 0:J.doNotHyphenateCaps)!==void 0)this.root.push(new X0("w:doNotHyphenateCaps",$.hyphenation.doNotHyphenateCaps));this.root.push(new O5(R0(W0({},(G=$.compatibility)!=null?G:{}),{version:(B=(Q=(X=$.compatibility)==null?void 0:X.version)!=null?Q:$.compatibilityModeVersion)!=null?B:15})))}}class GU extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w:val"})}}class S5 extends o{constructor($){super("w:name");this.root.push(new GU({val:$}))}}class v5 extends o{constructor($){super("w:uiPriority");this.root.push(new GU({val:S0($)}))}}class _5 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{type:"w:type",styleId:"w:styleId",default:"w:default",customStyle:"w:customStyle"})}}class KU extends o{constructor($,U){super("w:style");if(this.root.push(new _5($)),U.name)this.root.push(new S5(U.name));if(U.basedOn)this.root.push(new Y2("w:basedOn",U.basedOn));if(U.next)this.root.push(new Y2("w:next",U.next));if(U.link)this.root.push(new Y2("w:link",U.link));if(U.uiPriority!==void 0)this.root.push(new v5(U.uiPriority));if(U.semiHidden!==void 0)this.root.push(new X0("w:semiHidden",U.semiHidden));if(U.unhideWhenUsed!==void 0)this.root.push(new X0("w:unhideWhenUsed",U.unhideWhenUsed));if(U.quickFormat!==void 0)this.root.push(new X0("w:qFormat",U.quickFormat))}}class y2 extends KU{constructor($){super({type:"paragraph",styleId:$.id},$);Y0(this,"paragraphProperties"),Y0(this,"runProperties"),this.paragraphProperties=new Z2($.paragraph),this.runProperties=new J2($.run),this.root.push(this.paragraphProperties),this.root.push(this.runProperties)}}class D2 extends KU{constructor($){super({type:"character",styleId:$.id},W0({uiPriority:99,unhideWhenUsed:!0},$));Y0(this,"runProperties"),this.runProperties=new J2($.run),this.root.push(this.runProperties)}}class H2 extends y2{constructor($){super(W0({basedOn:"Normal",next:"Normal",quickFormat:!0},$))}}class y5 extends H2{constructor($){super(W0({id:"Title",name:"Title"},$))}}class b5 extends H2{constructor($){super(W0({id:"Heading1",name:"Heading 1"},$))}}class g5 extends H2{constructor($){super(W0({id:"Heading2",name:"Heading 2"},$))}}class x5 extends H2{constructor($){super(W0({id:"Heading3",name:"Heading 3"},$))}}class f5 extends H2{constructor($){super(W0({id:"Heading4",name:"Heading 4"},$))}}class h5 extends H2{constructor($){super(W0({id:"Heading5",name:"Heading 5"},$))}}class u5 extends H2{constructor($){super(W0({id:"Heading6",name:"Heading 6"},$))}}class d5 extends H2{constructor($){super(W0({id:"Strong",name:"Strong"},$))}}class c5 extends y2{constructor($){super(W0({id:"ListParagraph",name:"List Paragraph",basedOn:"Normal",quickFormat:!0},$))}}class m5 extends y2{constructor($){super(W0({id:"FootnoteText",name:"footnote text",link:"FootnoteTextChar",basedOn:"Normal",uiPriority:99,semiHidden:!0,unhideWhenUsed:!0,paragraph:{spacing:{after:0,line:240,lineRule:v2.AUTO}},run:{size:20}},$))}}class l5 extends D2{constructor($){super(W0({id:"FootnoteReference",name:"footnote reference",basedOn:"DefaultParagraphFont",semiHidden:!0,run:{superScript:!0}},$))}}class a5 extends D2{constructor($){super(W0({id:"FootnoteTextChar",name:"Footnote Text Char",basedOn:"DefaultParagraphFont",link:"FootnoteText",semiHidden:!0,run:{size:20}},$))}}class p5 extends y2{constructor($){super(W0({id:"EndnoteText",name:"endnote text",link:"EndnoteTextChar",basedOn:"Normal",uiPriority:99,semiHidden:!0,unhideWhenUsed:!0,paragraph:{spacing:{after:0,line:240,lineRule:v2.AUTO}},run:{size:20}},$))}}class i5 extends D2{constructor($){super(W0({id:"EndnoteReference",name:"endnote reference",basedOn:"DefaultParagraphFont",semiHidden:!0,run:{superScript:!0}},$))}}class r5 extends D2{constructor($){super(W0({id:"EndnoteTextChar",name:"Endnote Text Char",basedOn:"DefaultParagraphFont",link:"EndnoteText",semiHidden:!0,run:{size:20}},$))}}class s5 extends D2{constructor($){super(W0({id:"Hyperlink",name:"Hyperlink",basedOn:"DefaultParagraphFont",run:{color:"0563C1",underline:{type:Z$.SINGLE}}},$))}}class B1 extends o{constructor($){super("w:styles");if($.initialStyles)this.root.push($.initialStyles);if($.importedStyles)for(let U of $.importedStyles)this.root.push(U);if($.paragraphStyles)for(let U of $.paragraphStyles)this.root.push(new y2(U));if($.characterStyles)for(let U of $.characterStyles)this.root.push(new D2(U))}}class qU extends o{constructor($){super("w:pPrDefault");this.root.push(new Z2($))}}class XU extends o{constructor($){super("w:rPrDefault");this.root.push(new J2($))}}class VU extends o{constructor($){super("w:docDefaults");Y0(this,"runPropertiesDefaults"),Y0(this,"paragraphPropertiesDefaults"),this.runPropertiesDefaults=new XU($.run),this.paragraphPropertiesDefaults=new qU($.paragraph),this.root.push(this.runPropertiesDefaults),this.root.push(this.paragraphPropertiesDefaults)}}class n5{newInstance($){let U=$8.xml2js($,{compact:!1}),Y;for(let J of U.elements||[])if(J.name==="w:styles")Y=J;if(Y===void 0)throw Error("can not find styles element");let Z=Y.elements||[];return{initialStyles:new i9(Y.attributes),importedStyles:Z.map((J)=>U8(J))}}}class c1{newInstance($={}){var U;return{initialStyles:new o2(["mc","r","w","w14","w15"],"w14 w15"),importedStyles:[new VU((U=$.document)!=null?U:{}),new y5(W0({run:{size:56}},$.title)),new b5(W0({run:{color:"2E74B5",size:32}},$.heading1)),new g5(W0({run:{color:"2E74B5",size:26}},$.heading2)),new x5(W0({run:{color:"1F4D78",size:24}},$.heading3)),new f5(W0({run:{color:"2E74B5",italics:!0}},$.heading4)),new h5(W0({run:{color:"2E74B5"}},$.heading5)),new u5(W0({run:{color:"1F4D78"}},$.heading6)),new d5(W0({run:{bold:!0}},$.strong)),new c5($.listParagraph||{}),new s5($.hyperlink||{}),new l5($.footnoteReference||{}),new m5($.footnoteText||{}),new a5($.footnoteTextChar||{}),new i5($.endnoteReference||{}),new p5($.endnoteText||{}),new r5($.endnoteTextChar||{})]}}}class o5{constructor($){Y0(this,"currentRelationshipId",1),Y0(this,"documentWrapper"),Y0(this,"headers",[]),Y0(this,"footers",[]),Y0(this,"coreProperties"),Y0(this,"numbering"),Y0(this,"media"),Y0(this,"fileRelationships"),Y0(this,"footnotesWrapper"),Y0(this,"endnotesWrapper"),Y0(this,"settings"),Y0(this,"contentTypes"),Y0(this,"customProperties"),Y0(this,"appProperties"),Y0(this,"styles"),Y0(this,"comments"),Y0(this,"fontWrapper");var U,Y,Z,J,G,X,Q,B,F,z,W,k,D;if(this.coreProperties=new gK(R0(W0({},$),{creator:(U=$.creator)!=null?U:"Un-named",revision:(Y=$.revision)!=null?Y:1,lastModifiedBy:(Z=$.lastModifiedBy)!=null?Z:"Un-named"})),this.numbering=new JU($.numbering?$.numbering:{config:[]}),this.comments=new M$((J=$.comments)!=null?J:{children:[]}),this.fileRelationships=new W2,this.customProperties=new cK((G=$.customProperties)!=null?G:[]),this.appProperties=new _K,this.footnotesWrapper=new L5,this.endnotesWrapper=new G5,this.contentTypes=new bK,this.documentWrapper=new $5({background:$.background}),this.settings=new E5({compatibilityModeVersion:$.compatabilityModeVersion,compatibility:$.compatibility,evenAndOddHeaders:$.evenAndOddHeaderAndFooters?!0:!1,trackRevisions:(X=$.features)==null?void 0:X.trackRevisions,updateFields:(Q=$.features)==null?void 0:Q.updateFields,defaultTabStop:$.defaultTabStop,hyphenation:{autoHyphenation:(B=$.hyphenation)==null?void 0:B.autoHyphenation,hyphenationZone:(F=$.hyphenation)==null?void 0:F.hyphenationZone,consecutiveHyphenLimit:(z=$.hyphenation)==null?void 0:z.consecutiveHyphenLimit,doNotHyphenateCaps:(W=$.hyphenation)==null?void 0:W.doNotHyphenateCaps}}),this.media=new w8,$.externalStyles!==void 0){let H=new c1().newInstance((k=$.styles)==null?void 0:k.default),V=new n5().newInstance($.externalStyles);this.styles=new B1(R0(W0({},V),{importedStyles:[...H.importedStyles,...V.importedStyles]}))}else if($.styles){let H=new c1().newInstance($.styles.default);this.styles=new B1(W0(W0({},H),$.styles))}else{let C=new c1;this.styles=new B1(C.newInstance())}this.addDefaultRelationships();for(let C of $.sections)this.addSection(C);if($.footnotes)for(let C in $.footnotes)this.footnotesWrapper.View.createFootNote(parseFloat(C),$.footnotes[C].children);if($.endnotes)for(let C in $.endnotes)this.endnotesWrapper.View.createEndnote(parseFloat(C),$.endnotes[C].children);this.fontWrapper=new R$((D=$.fonts)!=null?D:[])}addSection({headers:$={},footers:U={},children:Y,properties:Z}){this.documentWrapper.View.Body.addSection(R0(W0({},Z),{headerWrapperGroup:{default:$.default?this.createHeader($.default):void 0,first:$.first?this.createHeader($.first):void 0,even:$.even?this.createHeader($.even):void 0},footerWrapperGroup:{default:U.default?this.createFooter(U.default):void 0,first:U.first?this.createFooter(U.first):void 0,even:U.even?this.createFooter(U.even):void 0}}));for(let J of Y)this.documentWrapper.View.add(J)}createHeader($){let U=new YU(this.media,this.currentRelationshipId++);for(let Y of $.options.children)U.add(Y);return this.addHeaderToDocument(U),U}createFooter($){let U=new $U(this.media,this.currentRelationshipId++);for(let Y of $.options.children)U.add(Y);return this.addFooterToDocument(U),U}addHeaderToDocument($,U=E2.DEFAULT){this.headers.push({header:$,type:U}),this.documentWrapper.Relationships.addRelationship($.View.ReferenceId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",`header${this.headers.length}.xml`),this.contentTypes.addHeader(this.headers.length)}addFooterToDocument($,U=E2.DEFAULT){this.footers.push({footer:$,type:U}),this.documentWrapper.Relationships.addRelationship($.View.ReferenceId,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",`footer${this.footers.length}.xml`),this.contentTypes.addFooter(this.footers.length)}addDefaultRelationships(){this.fileRelationships.addRelationship(1,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","word/document.xml"),this.fileRelationships.addRelationship(2,"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties","docProps/core.xml"),this.fileRelationships.addRelationship(3,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties","docProps/app.xml"),this.fileRelationships.addRelationship(4,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties","docProps/custom.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles","styles.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering","numbering.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes","footnotes.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes","endnotes.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings","settings.xml"),this.documentWrapper.Relationships.addRelationship(this.currentRelationshipId++,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments","comments.xml")}get Document(){return this.documentWrapper}get Styles(){return this.styles}get CoreProperties(){return this.coreProperties}get Numbering(){return this.numbering}get Media(){return this.media}get FileRelationships(){return this.fileRelationships}get Headers(){return this.headers.map(($)=>$.header)}get Footers(){return this.footers.map(($)=>$.footer)}get ContentTypes(){return this.contentTypes}get CustomProperties(){return this.customProperties}get AppProperties(){return this.appProperties}get FootNotes(){return this.footnotesWrapper}get Endnotes(){return this.endnotesWrapper}get Settings(){return this.settings}get Comments(){return this.comments}get FontTable(){return this.fontWrapper}}class t5 extends o{constructor($={}){super("w:instrText");Y0(this,"properties"),this.properties=$,this.root.push(new x0({space:g0.PRESERVE}));let U="TOC";if(this.properties.captionLabel)U=`${U} \\a "${this.properties.captionLabel}"`;if(this.properties.entriesFromBookmark)U=`${U} \\b "${this.properties.entriesFromBookmark}"`;if(this.properties.captionLabelIncludingNumbers)U=`${U} \\c "${this.properties.captionLabelIncludingNumbers}"`;if(this.properties.sequenceAndPageNumbersSeparator)U=`${U} \\d "${this.properties.sequenceAndPageNumbersSeparator}"`;if(this.properties.tcFieldIdentifier)U=`${U} \\f "${this.properties.tcFieldIdentifier}"`;if(this.properties.hyperlink)U=`${U} \\h`;if(this.properties.tcFieldLevelRange)U=`${U} \\l "${this.properties.tcFieldLevelRange}"`;if(this.properties.pageNumbersEntryLevelsRange)U=`${U} \\n "${this.properties.pageNumbersEntryLevelsRange}"`;if(this.properties.headingStyleRange)U=`${U} \\o "${this.properties.headingStyleRange}"`;if(this.properties.entryAndPageNumberSeparator)U=`${U} \\p "${this.properties.entryAndPageNumberSeparator}"`;if(this.properties.seqFieldIdentifierForPrefix)U=`${U} \\s "${this.properties.seqFieldIdentifierForPrefix}"`;if(this.properties.stylesWithLevels&&this.properties.stylesWithLevels.length){let Y=this.properties.stylesWithLevels.map((Z)=>`${Z.styleName},${Z.level}`).join(",");U=`${U} \\t "${Y}"`}if(this.properties.useAppliedParagraphOutlineLevel)U=`${U} \\u`;if(this.properties.preserveTabInEntries)U=`${U} \\w`;if(this.properties.preserveNewLineInEntries)U=`${U} \\x`;if(this.properties.hideTabAndPageNumbersInWebView)U=`${U} \\z`;this.root.push(U)}}class BU extends o{constructor(){super("w:sdtContent")}}class LU extends o{constructor($){super("w:sdtPr");if($)this.root.push(new Y2("w:alias",$))}}class e5 extends r2{constructor($="Table of Contents",U={}){var Y=U,{contentChildren:Z=[],cachedEntries:J=[],beginDirty:G=!0}=Y,X=oZ(Y,["contentChildren","cachedEntries","beginDirty"]);super("w:sdt");this.root.push(new LU($));let Q=new BU,B=[new C0({children:[$2(G),new t5(X),I2()]})],F=[new C0({children:[U2()]})];if(J!==void 0&&J.length>0){let{stylesWithLevels:W}=X,k=J.map((C,H)=>{var O,V;let j=this.buildCachedContentParagraphChild(C,X),M=(V=(O=W==null?void 0:W.find((A)=>A.level===C.level))==null?void 0:O.styleName)!=null?V:`TOC${C.level}`,L=H===0?[...B,j]:H===J.length-1?[j,...F]:[j];return new h0({style:M,tabStops:this.getTabStopsForLevel(C.level),children:L})}),D=k;if(J.length<=1)D=[...k,new h0({children:F})];for(let C of D)Q.addChildElement(C)}else{let W=new h0({children:B});Q.addChildElement(W);for(let D of Z)Q.addChildElement(D);let k=new h0({children:F});Q.addChildElement(k)}this.root.push(Q)}getTabStopsForLevel($,U=9025){return[{type:"clear",position:U+1-($-1)*240},{type:"right",position:U,leader:"dot"}]}buildCachedContentRun($,U){var Y,Z;return new C0({style:(U==null?void 0:U.hyperlink)&&$.href!==void 0?"IndexLink":void 0,children:[new a2({text:$.title}),new w$,new a2({text:(Z=(Y=$.page)==null?void 0:Y.toString())!=null?Z:""})]})}buildCachedContentParagraphChild($,U){let Y=this.buildCachedContentRun($,U);if((U==null?void 0:U.hyperlink)&&$.href!==void 0)return new j$({anchor:$.href,children:[Y]});return Y}}class $7{constructor($,U){Y0(this,"styleName"),Y0(this,"level"),this.styleName=$,this.level=U}}class U7{constructor($={children:[]}){Y0(this,"options"),this.options=$}}class Y7{constructor($={children:[]}){Y0(this,"options"),this.options=$}}class MU extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id"})}}class IU extends o{constructor($){super("w:footnoteReference");this.root.push(new MU({id:$}))}}class Z7 extends C0{constructor($){super({style:"FootnoteReference"});this.root.push(new IU($))}}class wU extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{id:"w:id"})}}class WU extends o{constructor($){super("w:endnoteReference");this.root.push(new wU({id:$}))}}class Q7 extends C0{constructor($){super({style:"EndnoteReference"});this.root.push(new WU($))}}class _9 extends I0{constructor(){super(...arguments);Y0(this,"xmlKeys",{val:"w14:val",symbolfont:"w14:font"})}}class L1 extends o{constructor($,U,Y){super($);if(Y)this.root.push(new _9({val:DQ(U),symbolfont:Y}));else this.root.push(new _9({val:U}))}}class HU extends o{constructor($){var U,Y,Z,J,G,X,Q,B;super("w14:checkbox");Y0(this,"DEFAULT_UNCHECKED_SYMBOL","2610"),Y0(this,"DEFAULT_CHECKED_SYMBOL","2612"),Y0(this,"DEFAULT_FONT","MS Gothic");let F=($==null?void 0:$.checked)?"1":"0",z,W;this.root.push(new L1("w14:checked",F)),z=((U=$==null?void 0:$.checkedState)==null?void 0:U.value)?(Y=$==null?void 0:$.checkedState)==null?void 0:Y.value:this.DEFAULT_CHECKED_SYMBOL,W=((Z=$==null?void 0:$.checkedState)==null?void 0:Z.font)?(J=$==null?void 0:$.checkedState)==null?void 0:J.font:this.DEFAULT_FONT,this.root.push(new L1("w14:checkedState",z,W)),z=((G=$==null?void 0:$.uncheckedState)==null?void 0:G.value)?(X=$==null?void 0:$.uncheckedState)==null?void 0:X.value:this.DEFAULT_UNCHECKED_SYMBOL,W=((Q=$==null?void 0:$.uncheckedState)==null?void 0:Q.font)?(B=$==null?void 0:$.uncheckedState)==null?void 0:B.font:this.DEFAULT_FONT,this.root.push(new L1("w14:uncheckedState",z,W))}}class J7 extends o{constructor($){var U,Y,Z,J;super("w:sdt");Y0(this,"DEFAULT_UNCHECKED_SYMBOL","2610"),Y0(this,"DEFAULT_CHECKED_SYMBOL","2612"),Y0(this,"DEFAULT_FONT","MS Gothic");let G=new LU($==null?void 0:$.alias);G.addChildElement(new HU($)),this.root.push(G);let X=new BU,Q=(U=$==null?void 0:$.checkedState)==null?void 0:U.font,B=(Y=$==null?void 0:$.checkedState)==null?void 0:Y.value,F=(Z=$==null?void 0:$.uncheckedState)==null?void 0:Z.font,z=(J=$==null?void 0:$.uncheckedState)==null?void 0:J.value,W,k;if($==null?void 0:$.checked)W=Q?Q:this.DEFAULT_FONT,k=B?B:this.DEFAULT_CHECKED_SYMBOL;else W=F?F:this.DEFAULT_FONT,k=z?z:this.DEFAULT_UNCHECKED_SYMBOL;let D=new G$({char:k,symbolfont:W});X.addChildElement(D),this.root.push(X)}}var iV=({shape:$})=>new B0({name:"w:pict",children:[$]}),rV=({children:$=[]})=>new B0({name:"w:txbxContent",children:$}),sV=({style:$,children:U,inset:Y})=>new B0({name:"v:textbox",attributes:{style:{key:"style",value:$},insetMode:{key:"insetmode",value:Y?"custom":"auto"},inset:{key:"inset",value:Y?`${Y.left}, ${Y.top}, ${Y.right}, ${Y.bottom}`:void 0}},children:[rV({children:U})]}),nV="#_x0000_t202",oV={flip:"flip",height:"height",left:"left",marginBottom:"margin-bottom",marginLeft:"margin-left",marginRight:"margin-right",marginTop:"margin-top",positionHorizontal:"mso-position-horizontal",positionHorizontalRelative:"mso-position-horizontal-relative",positionVertical:"mso-position-vertical",positionVerticalRelative:"mso-position-vertical-relative",wrapDistanceBottom:"mso-wrap-distance-bottom",wrapDistanceLeft:"mso-wrap-distance-left",wrapDistanceRight:"mso-wrap-distance-right",wrapDistanceTop:"mso-wrap-distance-top",wrapEdited:"mso-wrap-edited",wrapStyle:"mso-wrap-style",position:"position",rotation:"rotation",top:"top",visibility:"visibility",width:"width",zIndex:"z-index"},tV=($)=>$?Object.entries($).map(([U,Y])=>`${oV[U]}:${Y}`).join(";"):void 0,eV=({id:$,children:U,type:Y=nV,style:Z})=>new B0({name:"v:shape",attributes:{id:{key:"id",value:$},type:{key:"type",value:Y},style:{key:"style",value:tV(Z)}},children:[sV({style:"mso-fit-shape-to-text:t;",children:U})]});class G7 extends r2{constructor($){var U=$,{style:Y,children:Z}=U,J=oZ(U,["style","children"]);super("w:p");this.root.push(new Z2(J)),this.root.push(iV({shape:eV({children:Z,id:R1(),style:Y})}))}}var $B=m9();function y1($){throw Error('Could not dynamically require "'+$+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var I9={exports:{}},uZ;function UB(){if(uZ)return I9.exports;return uZ=1,function($,U){(function(Y){$.exports=Y()})(function(){return function Y(Z,J,G){function X(F,z){if(!J[F]){if(!Z[F]){var W=typeof y1=="function"&&y1;if(!z&&W)return W(F,!0);if(Q)return Q(F,!0);var k=Error("Cannot find module '"+F+"'");throw k.code="MODULE_NOT_FOUND",k}var D=J[F]={exports:{}};Z[F][0].call(D.exports,function(C){var H=Z[F][1][C];return X(H||C)},D,D.exports,Y,Z,J,G)}return J[F].exports}for(var Q=typeof y1=="function"&&y1,B=0;B>2,D=(3&F)<<4|z>>4,C=1>6:64,H=2>4,z=(15&k)<<4|(D=Q.indexOf(B.charAt(H++)))>>2,W=(3&D)<<6|(C=Q.indexOf(B.charAt(H++))),j[O++]=F,D!==64&&(j[O++]=z),C!==64&&(j[O++]=W);return j}},{"./support":30,"./utils":32}],2:[function(Y,Z,J){var G=Y("./external"),X=Y("./stream/DataWorker"),Q=Y("./stream/Crc32Probe"),B=Y("./stream/DataLengthProbe");function F(z,W,k,D,C){this.compressedSize=z,this.uncompressedSize=W,this.crc32=k,this.compression=D,this.compressedContent=C}F.prototype={getContentWorker:function(){var z=new X(G.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new B("data_length")),W=this;return z.on("end",function(){if(this.streamInfo.data_length!==W.uncompressedSize)throw Error("Bug : uncompressed data size mismatch")}),z},getCompressedWorker:function(){return new X(G.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},F.createWorkerFrom=function(z,W,k){return z.pipe(new Q).pipe(new B("uncompressedSize")).pipe(W.compressWorker(k)).pipe(new B("compressedSize")).withStreamInfo("compression",W)},Z.exports=F},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(Y,Z,J){var G=Y("./stream/GenericWorker");J.STORE={magic:"\x00\x00",compressWorker:function(){return new G("STORE compression")},uncompressWorker:function(){return new G("STORE decompression")}},J.DEFLATE=Y("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(Y,Z,J){var G=Y("./utils"),X=function(){for(var Q,B=[],F=0;F<256;F++){Q=F;for(var z=0;z<8;z++)Q=1&Q?3988292384^Q>>>1:Q>>>1;B[F]=Q}return B}();Z.exports=function(Q,B){return Q!==void 0&&Q.length?G.getTypeOf(Q)!=="string"?function(F,z,W,k){var D=X,C=k+W;F^=-1;for(var H=k;H>>8^D[255&(F^z[H])];return-1^F}(0|B,Q,Q.length,0):function(F,z,W,k){var D=X,C=k+W;F^=-1;for(var H=k;H>>8^D[255&(F^z.charCodeAt(H))];return-1^F}(0|B,Q,Q.length,0):0}},{"./utils":32}],5:[function(Y,Z,J){J.base64=!1,J.binary=!1,J.dir=!1,J.createFolders=!0,J.date=null,J.compression=null,J.compressionOptions=null,J.comment=null,J.unixPermissions=null,J.dosPermissions=null},{}],6:[function(Y,Z,J){var G=null;G=typeof Promise<"u"?Promise:Y("lie"),Z.exports={Promise:G}},{lie:37}],7:[function(Y,Z,J){var G=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",X=Y("pako"),Q=Y("./utils"),B=Y("./stream/GenericWorker"),F=G?"uint8array":"array";function z(W,k){B.call(this,"FlateWorker/"+W),this._pako=null,this._pakoAction=W,this._pakoOptions=k,this.meta={}}J.magic="\b\x00",Q.inherits(z,B),z.prototype.processChunk=function(W){this.meta=W.meta,this._pako===null&&this._createPako(),this._pako.push(Q.transformTo(F,W.data),!1)},z.prototype.flush=function(){B.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},z.prototype.cleanUp=function(){B.prototype.cleanUp.call(this),this._pako=null},z.prototype._createPako=function(){this._pako=new X[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var W=this;this._pako.onData=function(k){W.push({data:k,meta:W.meta})}},J.compressWorker=function(W){return new z("Deflate",W)},J.uncompressWorker=function(){return new z("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(Y,Z,J){function G(D,C){var H,O="";for(H=0;H>>=8;return O}function X(D,C,H,O,V,j){var M,L,A=D.file,y=D.compression,g=j!==F.utf8encode,d=Q.transformTo("string",j(A.name)),E=Q.transformTo("string",F.utf8encode(A.name)),s=A.comment,V0=Q.transformTo("string",j(s)),S=Q.transformTo("string",F.utf8encode(s)),h=E.length!==A.name.length,N=S.length!==s.length,a="",$0="",m="",J0=A.dir,U0=A.date,L0={crc32:0,compressedSize:0,uncompressedSize:0};C&&!H||(L0.crc32=D.crc32,L0.compressedSize=D.compressedSize,L0.uncompressedSize=D.uncompressedSize);var i=0;C&&(i|=8),g||!h&&!N||(i|=2048);var _=0,r=0;J0&&(_|=16),V==="UNIX"?(r=798,_|=function(Z0,p){var P=Z0;return Z0||(P=p?16893:33204),(65535&P)<<16}(A.unixPermissions,J0)):(r=20,_|=function(Z0){return 63&(Z0||0)}(A.dosPermissions)),M=U0.getUTCHours(),M<<=6,M|=U0.getUTCMinutes(),M<<=5,M|=U0.getUTCSeconds()/2,L=U0.getUTCFullYear()-1980,L<<=4,L|=U0.getUTCMonth()+1,L<<=5,L|=U0.getUTCDate(),h&&($0=G(1,1)+G(z(d),4)+E,a+="up"+G($0.length,2)+$0),N&&(m=G(1,1)+G(z(V0),4)+S,a+="uc"+G(m.length,2)+m);var n="";return n+=` +\x00`,n+=G(i,2),n+=y.magic,n+=G(M,2),n+=G(L,2),n+=G(L0.crc32,4),n+=G(L0.compressedSize,4),n+=G(L0.uncompressedSize,4),n+=G(d.length,2),n+=G(a.length,2),{fileRecord:W.LOCAL_FILE_HEADER+n+d+a,dirRecord:W.CENTRAL_FILE_HEADER+G(r,2)+n+G(V0.length,2)+"\x00\x00\x00\x00"+G(_,4)+G(O,4)+d+a+V0}}var Q=Y("../utils"),B=Y("../stream/GenericWorker"),F=Y("../utf8"),z=Y("../crc32"),W=Y("../signature");function k(D,C,H,O){B.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=C,this.zipPlatform=H,this.encodeFileName=O,this.streamFiles=D,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Q.inherits(k,B),k.prototype.push=function(D){var C=D.meta.percent||0,H=this.entriesCount,O=this._sources.length;this.accumulate?this.contentBuffer.push(D):(this.bytesWritten+=D.data.length,B.prototype.push.call(this,{data:D.data,meta:{currentFile:this.currentFile,percent:H?(C+100*(H-O-1))/H:100}}))},k.prototype.openedSource=function(D){this.currentSourceOffset=this.bytesWritten,this.currentFile=D.file.name;var C=this.streamFiles&&!D.file.dir;if(C){var H=X(D,C,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:H.fileRecord,meta:{percent:0}})}else this.accumulate=!0},k.prototype.closedSource=function(D){this.accumulate=!1;var C=this.streamFiles&&!D.file.dir,H=X(D,C,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(H.dirRecord),C)this.push({data:function(O){return W.DATA_DESCRIPTOR+G(O.crc32,4)+G(O.compressedSize,4)+G(O.uncompressedSize,4)}(D),meta:{percent:100}});else for(this.push({data:H.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},k.prototype.flush=function(){for(var D=this.bytesWritten,C=0;C=this.index;B--)F=(F<<8)+this.byteAt(B);return this.index+=Q,F},readString:function(Q){return G.transformTo("string",this.readData(Q))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var Q=this.readInt(4);return new Date(Date.UTC(1980+(Q>>25&127),(Q>>21&15)-1,Q>>16&31,Q>>11&31,Q>>5&63,(31&Q)<<1))}},Z.exports=X},{"../utils":32}],19:[function(Y,Z,J){var G=Y("./Uint8ArrayReader");function X(Q){G.call(this,Q)}Y("../utils").inherits(X,G),X.prototype.readData=function(Q){this.checkOffset(Q);var B=this.data.slice(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,B},Z.exports=X},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(Y,Z,J){var G=Y("./DataReader");function X(Q){G.call(this,Q)}Y("../utils").inherits(X,G),X.prototype.byteAt=function(Q){return this.data.charCodeAt(this.zero+Q)},X.prototype.lastIndexOfSignature=function(Q){return this.data.lastIndexOf(Q)-this.zero},X.prototype.readAndCheckSignature=function(Q){return Q===this.readData(4)},X.prototype.readData=function(Q){this.checkOffset(Q);var B=this.data.slice(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,B},Z.exports=X},{"../utils":32,"./DataReader":18}],21:[function(Y,Z,J){var G=Y("./ArrayReader");function X(Q){G.call(this,Q)}Y("../utils").inherits(X,G),X.prototype.readData=function(Q){if(this.checkOffset(Q),Q===0)return new Uint8Array(0);var B=this.data.subarray(this.zero+this.index,this.zero+this.index+Q);return this.index+=Q,B},Z.exports=X},{"../utils":32,"./ArrayReader":17}],22:[function(Y,Z,J){var G=Y("../utils"),X=Y("../support"),Q=Y("./ArrayReader"),B=Y("./StringReader"),F=Y("./NodeBufferReader"),z=Y("./Uint8ArrayReader");Z.exports=function(W){var k=G.getTypeOf(W);return G.checkSupport(k),k!=="string"||X.uint8array?k==="nodebuffer"?new F(W):X.uint8array?new z(G.transformTo("uint8array",W)):new Q(G.transformTo("array",W)):new B(W)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(Y,Z,J){J.LOCAL_FILE_HEADER="PK\x03\x04",J.CENTRAL_FILE_HEADER="PK\x01\x02",J.CENTRAL_DIRECTORY_END="PK\x05\x06",J.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x06\x07",J.ZIP64_CENTRAL_DIRECTORY_END="PK\x06\x06",J.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(Y,Z,J){var G=Y("./GenericWorker"),X=Y("../utils");function Q(B){G.call(this,"ConvertWorker to "+B),this.destType=B}X.inherits(Q,G),Q.prototype.processChunk=function(B){this.push({data:X.transformTo(this.destType,B.data),meta:B.meta})},Z.exports=Q},{"../utils":32,"./GenericWorker":28}],25:[function(Y,Z,J){var G=Y("./GenericWorker"),X=Y("../crc32");function Q(){G.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}Y("../utils").inherits(Q,G),Q.prototype.processChunk=function(B){this.streamInfo.crc32=X(B.data,this.streamInfo.crc32||0),this.push(B)},Z.exports=Q},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(Y,Z,J){var G=Y("../utils"),X=Y("./GenericWorker");function Q(B){X.call(this,"DataLengthProbe for "+B),this.propName=B,this.withStreamInfo(B,0)}G.inherits(Q,X),Q.prototype.processChunk=function(B){if(B){var F=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=F+B.data.length}X.prototype.processChunk.call(this,B)},Z.exports=Q},{"../utils":32,"./GenericWorker":28}],27:[function(Y,Z,J){var G=Y("../utils"),X=Y("./GenericWorker");function Q(B){X.call(this,"DataWorker");var F=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,B.then(function(z){F.dataIsReady=!0,F.data=z,F.max=z&&z.length||0,F.type=G.getTypeOf(z),F.isPaused||F._tickAndRepeat()},function(z){F.error(z)})}G.inherits(Q,X),Q.prototype.cleanUp=function(){X.prototype.cleanUp.call(this),this.data=null},Q.prototype.resume=function(){return!!X.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,G.delay(this._tickAndRepeat,[],this)),!0)},Q.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(G.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},Q.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var B=null,F=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":B=this.data.substring(this.index,F);break;case"uint8array":B=this.data.subarray(this.index,F);break;case"array":case"nodebuffer":B=this.data.slice(this.index,F)}return this.index=F,this.push({data:B,meta:{percent:this.max?this.index/this.max*100:0}})},Z.exports=Q},{"../utils":32,"./GenericWorker":28}],28:[function(Y,Z,J){function G(X){this.name=X||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}G.prototype={push:function(X){this.emit("data",X)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(X){this.emit("error",X)}return!0},error:function(X){return!this.isFinished&&(this.isPaused?this.generatedError=X:(this.isFinished=!0,this.emit("error",X),this.previous&&this.previous.error(X),this.cleanUp()),!0)},on:function(X,Q){return this._listeners[X].push(Q),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(X,Q){if(this._listeners[X])for(var B=0;B "+X:X}},Z.exports=G},{}],29:[function(Y,Z,J){var G=Y("../utils"),X=Y("./ConvertWorker"),Q=Y("./GenericWorker"),B=Y("../base64"),F=Y("../support"),z=Y("../external"),W=null;if(F.nodestream)try{W=Y("../nodejs/NodejsStreamOutputAdapter")}catch(C){}function k(C,H){return new z.Promise(function(O,V){var j=[],M=C._internalType,L=C._outputType,A=C._mimeType;C.on("data",function(y,g){j.push(y),H&&H(g)}).on("error",function(y){j=[],V(y)}).on("end",function(){try{var y=function(g,d,E){switch(g){case"blob":return G.newBlob(G.transformTo("arraybuffer",d),E);case"base64":return B.encode(d);default:return G.transformTo(g,d)}}(L,function(g,d){var E,s=0,V0=null,S=0;for(E=0;E"u")J.blob=!1;else{var G=new ArrayBuffer(0);try{J.blob=new Blob([G],{type:"application/zip"}).size===0}catch(Q){try{var X=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);X.append(G),J.blob=X.getBlob("application/zip").size===0}catch(B){J.blob=!1}}}try{J.nodestream=!!Y("readable-stream").Readable}catch(Q){J.nodestream=!1}},{"readable-stream":16}],31:[function(Y,Z,J){for(var G=Y("./utils"),X=Y("./support"),Q=Y("./nodejsUtils"),B=Y("./stream/GenericWorker"),F=Array(256),z=0;z<256;z++)F[z]=252<=z?6:248<=z?5:240<=z?4:224<=z?3:192<=z?2:1;F[254]=F[254]=1;function W(){B.call(this,"utf-8 decode"),this.leftOver=null}function k(){B.call(this,"utf-8 encode")}J.utf8encode=function(D){return X.nodebuffer?Q.newBufferFrom(D,"utf-8"):function(C){var H,O,V,j,M,L=C.length,A=0;for(j=0;j>>6:(O<65536?H[M++]=224|O>>>12:(H[M++]=240|O>>>18,H[M++]=128|O>>>12&63),H[M++]=128|O>>>6&63),H[M++]=128|63&O);return H}(D)},J.utf8decode=function(D){return X.nodebuffer?G.transformTo("nodebuffer",D).toString("utf-8"):function(C){var H,O,V,j,M=C.length,L=Array(2*M);for(H=O=0;H>10&1023,L[O++]=56320|1023&V)}return L.length!==O&&(L.subarray?L=L.subarray(0,O):L.length=O),G.applyFromCharCode(L)}(D=G.transformTo(X.uint8array?"uint8array":"array",D))},G.inherits(W,B),W.prototype.processChunk=function(D){var C=G.transformTo(X.uint8array?"uint8array":"array",D.data);if(this.leftOver&&this.leftOver.length){if(X.uint8array){var H=C;(C=new Uint8Array(H.length+this.leftOver.length)).set(this.leftOver,0),C.set(H,this.leftOver.length)}else C=this.leftOver.concat(C);this.leftOver=null}var O=function(j,M){var L;for((M=M||j.length)>j.length&&(M=j.length),L=M-1;0<=L&&(192&j[L])==128;)L--;return L<0?M:L===0?M:L+F[j[L]]>M?L:M}(C),V=C;O!==C.length&&(X.uint8array?(V=C.subarray(0,O),this.leftOver=C.subarray(O,C.length)):(V=C.slice(0,O),this.leftOver=C.slice(O,C.length))),this.push({data:J.utf8decode(V),meta:D.meta})},W.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:J.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},J.Utf8DecodeWorker=W,G.inherits(k,B),k.prototype.processChunk=function(D){this.push({data:J.utf8encode(D.data),meta:D.meta})},J.Utf8EncodeWorker=k},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(Y,Z,J){var G=Y("./support"),X=Y("./base64"),Q=Y("./nodejsUtils"),B=Y("./external");function F(H){return H}function z(H,O){for(var V=0;V>8;this.dir=!!(16&this.externalFileAttributes),D==0&&(this.dosPermissions=63&this.externalFileAttributes),D==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var D=G(this.extraFields[1].value);this.uncompressedSize===X.MAX_VALUE_32BITS&&(this.uncompressedSize=D.readInt(8)),this.compressedSize===X.MAX_VALUE_32BITS&&(this.compressedSize=D.readInt(8)),this.localHeaderOffset===X.MAX_VALUE_32BITS&&(this.localHeaderOffset=D.readInt(8)),this.diskNumberStart===X.MAX_VALUE_32BITS&&(this.diskNumberStart=D.readInt(4))}},readExtraFields:function(D){var C,H,O,V=D.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});D.index+4>>6:(D<65536?k[O++]=224|D>>>12:(k[O++]=240|D>>>18,k[O++]=128|D>>>12&63),k[O++]=128|D>>>6&63),k[O++]=128|63&D);return k},J.buf2binstring=function(W){return z(W,W.length)},J.binstring2buf=function(W){for(var k=new G.Buf8(W.length),D=0,C=k.length;D>10&1023,j[C++]=56320|1023&H)}return z(j,C)},J.utf8border=function(W,k){var D;for((k=k||W.length)>W.length&&(k=W.length),D=k-1;0<=D&&(192&W[D])==128;)D--;return D<0?k:D===0?k:D+B[W[D]]>k?D:k}},{"./common":41}],43:[function(Y,Z,J){Z.exports=function(G,X,Q,B){for(var F=65535&G|0,z=G>>>16&65535|0,W=0;Q!==0;){for(Q-=W=2000>>1:X>>>1;Q[B]=X}return Q}();Z.exports=function(X,Q,B,F){var z=G,W=F+B;X^=-1;for(var k=F;k>>8^z[255&(X^Q[k])];return-1^X}},{}],46:[function(Y,Z,J){var G,X=Y("../utils/common"),Q=Y("./trees"),B=Y("./adler32"),F=Y("./crc32"),z=Y("./messages"),W=0,k=4,D=0,C=-2,H=-1,O=4,V=2,j=8,M=9,L=286,A=30,y=19,g=2*L+1,d=15,E=3,s=258,V0=s+E+1,S=42,h=113,N=1,a=2,$0=3,m=4;function J0(I,t){return I.msg=z[t],t}function U0(I){return(I<<1)-(4I.avail_out&&(T=I.avail_out),T!==0&&(X.arraySet(I.output,t.pending_buf,t.pending_out,T,I.next_out),I.next_out+=T,t.pending_out+=T,I.total_out+=T,I.avail_out-=T,t.pending-=T,t.pending===0&&(t.pending_out=0))}function _(I,t){Q._tr_flush_block(I,0<=I.block_start?I.block_start:-1,I.strstart-I.block_start,t),I.block_start=I.strstart,i(I.strm)}function r(I,t){I.pending_buf[I.pending++]=t}function n(I,t){I.pending_buf[I.pending++]=t>>>8&255,I.pending_buf[I.pending++]=255&t}function Z0(I,t){var T,K,q=I.max_chain_length,w=I.strstart,x=I.prev_length,l=I.nice_match,u=I.strstart>I.w_size-V0?I.strstart-(I.w_size-V0):0,Q0=I.window,q0=I.w_mask,K0=I.prev,M0=I.strstart+s,w0=Q0[w+x-1],H0=Q0[w+x];I.prev_length>=I.good_match&&(q>>=2),l>I.lookahead&&(l=I.lookahead);do if(Q0[(T=t)+x]===H0&&Q0[T+x-1]===w0&&Q0[T]===Q0[w]&&Q0[++T]===Q0[w+1]){w+=2,T++;do;while(Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&Q0[++w]===Q0[++T]&&wu&&--q!=0);return x<=I.lookahead?x:I.lookahead}function p(I){var t,T,K,q,w,x,l,u,Q0,q0,K0=I.w_size;do{if(q=I.window_size-I.lookahead-I.strstart,I.strstart>=K0+(K0-V0)){for(X.arraySet(I.window,I.window,K0,K0,0),I.match_start-=K0,I.strstart-=K0,I.block_start-=K0,t=T=I.hash_size;K=I.head[--t],I.head[t]=K0<=K?K-K0:0,--T;);for(t=T=K0;K=I.prev[--t],I.prev[t]=K0<=K?K-K0:0,--T;);q+=K0}if(I.strm.avail_in===0)break;if(x=I.strm,l=I.window,u=I.strstart+I.lookahead,Q0=q,q0=void 0,q0=x.avail_in,Q0=E)for(w=I.strstart-I.insert,I.ins_h=I.window[w],I.ins_h=(I.ins_h<=E&&(I.ins_h=(I.ins_h<=E)if(K=Q._tr_tally(I,I.strstart-I.match_start,I.match_length-E),I.lookahead-=I.match_length,I.match_length<=I.max_lazy_match&&I.lookahead>=E){for(I.match_length--;I.strstart++,I.ins_h=(I.ins_h<=E&&(I.ins_h=(I.ins_h<=E&&I.match_length<=I.prev_length){for(q=I.strstart+I.lookahead-E,K=Q._tr_tally(I,I.strstart-1-I.prev_match,I.prev_length-E),I.lookahead-=I.prev_length-1,I.prev_length-=2;++I.strstart<=q&&(I.ins_h=(I.ins_h<I.pending_buf_size-5&&(T=I.pending_buf_size-5);;){if(I.lookahead<=1){if(p(I),I.lookahead===0&&t===W)return N;if(I.lookahead===0)break}I.strstart+=I.lookahead,I.lookahead=0;var K=I.block_start+T;if((I.strstart===0||I.strstart>=K)&&(I.lookahead=I.strstart-K,I.strstart=K,_(I,!1),I.strm.avail_out===0))return N;if(I.strstart-I.block_start>=I.w_size-V0&&(_(I,!1),I.strm.avail_out===0))return N}return I.insert=0,t===k?(_(I,!0),I.strm.avail_out===0?$0:m):(I.strstart>I.block_start&&(_(I,!1),I.strm.avail_out),N)}),new c(4,4,8,4,P),new c(4,5,16,8,P),new c(4,6,32,32,P),new c(4,4,16,16,R),new c(8,16,32,32,R),new c(8,16,128,128,R),new c(8,32,128,256,R),new c(32,128,258,1024,R),new c(32,258,258,4096,R)],J.deflateInit=function(I,t){return e(I,t,j,15,8,0)},J.deflateInit2=e,J.deflateReset=b,J.deflateResetKeep=v,J.deflateSetHeader=function(I,t){return I&&I.state?I.state.wrap!==2?C:(I.state.gzhead=t,D):C},J.deflate=function(I,t){var T,K,q,w;if(!I||!I.state||5>8&255),r(K,K.gzhead.time>>16&255),r(K,K.gzhead.time>>24&255),r(K,K.level===9?2:2<=K.strategy||K.level<2?4:0),r(K,255&K.gzhead.os),K.gzhead.extra&&K.gzhead.extra.length&&(r(K,255&K.gzhead.extra.length),r(K,K.gzhead.extra.length>>8&255)),K.gzhead.hcrc&&(I.adler=F(I.adler,K.pending_buf,K.pending,0)),K.gzindex=0,K.status=69):(r(K,0),r(K,0),r(K,0),r(K,0),r(K,0),r(K,K.level===9?2:2<=K.strategy||K.level<2?4:0),r(K,3),K.status=h);else{var x=j+(K.w_bits-8<<4)<<8;x|=(2<=K.strategy||K.level<2?0:K.level<6?1:K.level===6?2:3)<<6,K.strstart!==0&&(x|=32),x+=31-x%31,K.status=h,n(K,x),K.strstart!==0&&(n(K,I.adler>>>16),n(K,65535&I.adler)),I.adler=1}if(K.status===69)if(K.gzhead.extra){for(q=K.pending;K.gzindex<(65535&K.gzhead.extra.length)&&(K.pending!==K.pending_buf_size||(K.gzhead.hcrc&&K.pending>q&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),i(I),q=K.pending,K.pending!==K.pending_buf_size));)r(K,255&K.gzhead.extra[K.gzindex]),K.gzindex++;K.gzhead.hcrc&&K.pending>q&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),K.gzindex===K.gzhead.extra.length&&(K.gzindex=0,K.status=73)}else K.status=73;if(K.status===73)if(K.gzhead.name){q=K.pending;do{if(K.pending===K.pending_buf_size&&(K.gzhead.hcrc&&K.pending>q&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),i(I),q=K.pending,K.pending===K.pending_buf_size)){w=1;break}w=K.gzindexq&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),w===0&&(K.gzindex=0,K.status=91)}else K.status=91;if(K.status===91)if(K.gzhead.comment){q=K.pending;do{if(K.pending===K.pending_buf_size&&(K.gzhead.hcrc&&K.pending>q&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),i(I),q=K.pending,K.pending===K.pending_buf_size)){w=1;break}w=K.gzindexq&&(I.adler=F(I.adler,K.pending_buf,K.pending-q,q)),w===0&&(K.status=103)}else K.status=103;if(K.status===103&&(K.gzhead.hcrc?(K.pending+2>K.pending_buf_size&&i(I),K.pending+2<=K.pending_buf_size&&(r(K,255&I.adler),r(K,I.adler>>8&255),I.adler=0,K.status=h)):K.status=h),K.pending!==0){if(i(I),I.avail_out===0)return K.last_flush=-1,D}else if(I.avail_in===0&&U0(t)<=U0(T)&&t!==k)return J0(I,-5);if(K.status===666&&I.avail_in!==0)return J0(I,-5);if(I.avail_in!==0||K.lookahead!==0||t!==W&&K.status!==666){var l=K.strategy===2?function(u,Q0){for(var q0;;){if(u.lookahead===0&&(p(u),u.lookahead===0)){if(Q0===W)return N;break}if(u.match_length=0,q0=Q._tr_tally(u,0,u.window[u.strstart]),u.lookahead--,u.strstart++,q0&&(_(u,!1),u.strm.avail_out===0))return N}return u.insert=0,Q0===k?(_(u,!0),u.strm.avail_out===0?$0:m):u.last_lit&&(_(u,!1),u.strm.avail_out===0)?N:a}(K,t):K.strategy===3?function(u,Q0){for(var q0,K0,M0,w0,H0=u.window;;){if(u.lookahead<=s){if(p(u),u.lookahead<=s&&Q0===W)return N;if(u.lookahead===0)break}if(u.match_length=0,u.lookahead>=E&&0u.lookahead&&(u.match_length=u.lookahead)}if(u.match_length>=E?(q0=Q._tr_tally(u,1,u.match_length-E),u.lookahead-=u.match_length,u.strstart+=u.match_length,u.match_length=0):(q0=Q._tr_tally(u,0,u.window[u.strstart]),u.lookahead--,u.strstart++),q0&&(_(u,!1),u.strm.avail_out===0))return N}return u.insert=0,Q0===k?(_(u,!0),u.strm.avail_out===0?$0:m):u.last_lit&&(_(u,!1),u.strm.avail_out===0)?N:a}(K,t):G[K.level].func(K,t);if(l!==$0&&l!==m||(K.status=666),l===N||l===$0)return I.avail_out===0&&(K.last_flush=-1),D;if(l===a&&(t===1?Q._tr_align(K):t!==5&&(Q._tr_stored_block(K,0,0,!1),t===3&&(L0(K.head),K.lookahead===0&&(K.strstart=0,K.block_start=0,K.insert=0))),i(I),I.avail_out===0))return K.last_flush=-1,D}return t!==k?D:K.wrap<=0?1:(K.wrap===2?(r(K,255&I.adler),r(K,I.adler>>8&255),r(K,I.adler>>16&255),r(K,I.adler>>24&255),r(K,255&I.total_in),r(K,I.total_in>>8&255),r(K,I.total_in>>16&255),r(K,I.total_in>>24&255)):(n(K,I.adler>>>16),n(K,65535&I.adler)),i(I),0=T.w_size&&(w===0&&(L0(T.head),T.strstart=0,T.block_start=0,T.insert=0),Q0=new X.Buf8(T.w_size),X.arraySet(Q0,t,q0-T.w_size,T.w_size,0),t=Q0,q0=T.w_size),x=I.avail_in,l=I.next_in,u=I.input,I.avail_in=q0,I.next_in=0,I.input=t,p(T);T.lookahead>=E;){for(K=T.strstart,q=T.lookahead-(E-1);T.ins_h=(T.ins_h<>>=E=d>>>24,M-=E,(E=d>>>16&255)===0)a[z++]=65535&d;else{if(!(16&E)){if((64&E)==0){d=L[(65535&d)+(j&(1<>>=E,M-=E),M<15&&(j+=N[B++]<>>=E=d>>>24,M-=E,!(16&(E=d>>>16&255))){if((64&E)==0){d=A[(65535&d)+(j&(1<>>=E,M-=E,(E=z-W)>3,j&=(1<<(M-=s<<3))-1,G.next_in=B,G.next_out=z,G.avail_in=B>>24&255)+(S>>>8&65280)+((65280&S)<<8)+((255&S)<<24)}function j(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new G.Buf16(320),this.work=new G.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function M(S){var h;return S&&S.state?(h=S.state,S.total_in=S.total_out=h.total=0,S.msg="",h.wrap&&(S.adler=1&h.wrap),h.mode=C,h.last=0,h.havedict=0,h.dmax=32768,h.head=null,h.hold=0,h.bits=0,h.lencode=h.lendyn=new G.Buf32(H),h.distcode=h.distdyn=new G.Buf32(O),h.sane=1,h.back=-1,k):D}function L(S){var h;return S&&S.state?((h=S.state).wsize=0,h.whave=0,h.wnext=0,M(S)):D}function A(S,h){var N,a;return S&&S.state?(a=S.state,h<0?(N=0,h=-h):(N=1+(h>>4),h<48&&(h&=15)),h&&(h<8||15=m.wsize?(G.arraySet(m.window,h,N-m.wsize,m.wsize,0),m.wnext=0,m.whave=m.wsize):(a<($0=m.wsize-m.wnext)&&($0=a),G.arraySet(m.window,h,N-a,$0,m.wnext),(a-=$0)?(G.arraySet(m.window,h,N-a,a,0),m.wnext=a,m.whave=m.wsize):(m.wnext+=$0,m.wnext===m.wsize&&(m.wnext=0),m.whave>>8&255,N.check=Q(N.check,w,2,0),_=i=0,N.mode=2;break}if(N.flags=0,N.head&&(N.head.done=!1),!(1&N.wrap)||(((255&i)<<8)+(i>>8))%31){S.msg="incorrect header check",N.mode=30;break}if((15&i)!=8){S.msg="unknown compression method",N.mode=30;break}if(_-=4,I=8+(15&(i>>>=4)),N.wbits===0)N.wbits=I;else if(I>N.wbits){S.msg="invalid window size",N.mode=30;break}N.dmax=1<>8&1),512&N.flags&&(w[0]=255&i,w[1]=i>>>8&255,N.check=Q(N.check,w,2,0)),_=i=0,N.mode=3;case 3:for(;_<32;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}N.head&&(N.head.time=i),512&N.flags&&(w[0]=255&i,w[1]=i>>>8&255,w[2]=i>>>16&255,w[3]=i>>>24&255,N.check=Q(N.check,w,4,0)),_=i=0,N.mode=4;case 4:for(;_<16;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}N.head&&(N.head.xflags=255&i,N.head.os=i>>8),512&N.flags&&(w[0]=255&i,w[1]=i>>>8&255,N.check=Q(N.check,w,2,0)),_=i=0,N.mode=5;case 5:if(1024&N.flags){for(;_<16;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}N.length=i,N.head&&(N.head.extra_len=i),512&N.flags&&(w[0]=255&i,w[1]=i>>>8&255,N.check=Q(N.check,w,2,0)),_=i=0}else N.head&&(N.head.extra=null);N.mode=6;case 6:if(1024&N.flags&&(U0<(Z0=N.length)&&(Z0=U0),Z0&&(N.head&&(I=N.head.extra_len-N.length,N.head.extra||(N.head.extra=Array(N.head.extra_len)),G.arraySet(N.head.extra,a,m,Z0,I)),512&N.flags&&(N.check=Q(N.check,a,Z0,m)),U0-=Z0,m+=Z0,N.length-=Z0),N.length))break $;N.length=0,N.mode=7;case 7:if(2048&N.flags){if(U0===0)break $;for(Z0=0;I=a[m+Z0++],N.head&&I&&N.length<65536&&(N.head.name+=String.fromCharCode(I)),I&&Z0>9&1,N.head.done=!0),S.adler=N.check=0,N.mode=12;break;case 10:for(;_<32;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}S.adler=N.check=V(i),_=i=0,N.mode=11;case 11:if(N.havedict===0)return S.next_out=J0,S.avail_out=L0,S.next_in=m,S.avail_in=U0,N.hold=i,N.bits=_,2;S.adler=N.check=1,N.mode=12;case 12:if(h===5||h===6)break $;case 13:if(N.last){i>>>=7&_,_-=7&_,N.mode=27;break}for(;_<3;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}switch(N.last=1&i,_-=1,3&(i>>>=1)){case 0:N.mode=14;break;case 1:if(s(N),N.mode=20,h!==6)break;i>>>=2,_-=2;break $;case 2:N.mode=17;break;case 3:S.msg="invalid block type",N.mode=30}i>>>=2,_-=2;break;case 14:for(i>>>=7&_,_-=7&_;_<32;){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}if((65535&i)!=(i>>>16^65535)){S.msg="invalid stored block lengths",N.mode=30;break}if(N.length=65535&i,_=i=0,N.mode=15,h===6)break $;case 15:N.mode=16;case 16:if(Z0=N.length){if(U0>>=5,_-=5,N.ndist=1+(31&i),i>>>=5,_-=5,N.ncode=4+(15&i),i>>>=4,_-=4,286>>=3,_-=3}for(;N.have<19;)N.lens[x[N.have++]]=0;if(N.lencode=N.lendyn,N.lenbits=7,T={bits:N.lenbits},t=F(0,N.lens,0,19,N.lencode,0,N.work,T),N.lenbits=T.bits,t){S.msg="invalid code lengths set",N.mode=30;break}N.have=0,N.mode=19;case 19:for(;N.have>>16&255,f=65535&q,!((R=q>>>24)<=_);){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}if(f<16)i>>>=R,_-=R,N.lens[N.have++]=f;else{if(f===16){for(K=R+2;_>>=R,_-=R,N.have===0){S.msg="invalid bit length repeat",N.mode=30;break}I=N.lens[N.have-1],Z0=3+(3&i),i>>>=2,_-=2}else if(f===17){for(K=R+3;_>>=R)),i>>>=3,_-=3}else{for(K=R+7;_>>=R)),i>>>=7,_-=7}if(N.have+Z0>N.nlen+N.ndist){S.msg="invalid bit length repeat",N.mode=30;break}for(;Z0--;)N.lens[N.have++]=I}}if(N.mode===30)break;if(N.lens[256]===0){S.msg="invalid code -- missing end-of-block",N.mode=30;break}if(N.lenbits=9,T={bits:N.lenbits},t=F(z,N.lens,0,N.nlen,N.lencode,0,N.work,T),N.lenbits=T.bits,t){S.msg="invalid literal/lengths set",N.mode=30;break}if(N.distbits=6,N.distcode=N.distdyn,T={bits:N.distbits},t=F(W,N.lens,N.nlen,N.ndist,N.distcode,0,N.work,T),N.distbits=T.bits,t){S.msg="invalid distances set",N.mode=30;break}if(N.mode=20,h===6)break $;case 20:N.mode=21;case 21:if(6<=U0&&258<=L0){S.next_out=J0,S.avail_out=L0,S.next_in=m,S.avail_in=U0,N.hold=i,N.bits=_,B(S,n),J0=S.next_out,$0=S.output,L0=S.avail_out,m=S.next_in,a=S.input,U0=S.avail_in,i=N.hold,_=N.bits,N.mode===12&&(N.back=-1);break}for(N.back=0;c=(q=N.lencode[i&(1<>>16&255,f=65535&q,!((R=q>>>24)<=_);){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}if(c&&(240&c)==0){for(v=R,b=c,e=f;c=(q=N.lencode[e+((i&(1<>v)])>>>16&255,f=65535&q,!(v+(R=q>>>24)<=_);){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}i>>>=v,_-=v,N.back+=v}if(i>>>=R,_-=R,N.back+=R,N.length=f,c===0){N.mode=26;break}if(32&c){N.back=-1,N.mode=12;break}if(64&c){S.msg="invalid literal/length code",N.mode=30;break}N.extra=15&c,N.mode=22;case 22:if(N.extra){for(K=N.extra;_>>=N.extra,_-=N.extra,N.back+=N.extra}N.was=N.length,N.mode=23;case 23:for(;c=(q=N.distcode[i&(1<>>16&255,f=65535&q,!((R=q>>>24)<=_);){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}if((240&c)==0){for(v=R,b=c,e=f;c=(q=N.distcode[e+((i&(1<>v)])>>>16&255,f=65535&q,!(v+(R=q>>>24)<=_);){if(U0===0)break $;U0--,i+=a[m++]<<_,_+=8}i>>>=v,_-=v,N.back+=v}if(i>>>=R,_-=R,N.back+=R,64&c){S.msg="invalid distance code",N.mode=30;break}N.offset=f,N.extra=15&c,N.mode=24;case 24:if(N.extra){for(K=N.extra;_>>=N.extra,_-=N.extra,N.back+=N.extra}if(N.offset>N.dmax){S.msg="invalid distance too far back",N.mode=30;break}N.mode=25;case 25:if(L0===0)break $;if(Z0=n-L0,N.offset>Z0){if((Z0=N.offset-Z0)>N.whave&&N.sane){S.msg="invalid distance too far back",N.mode=30;break}p=Z0>N.wnext?(Z0-=N.wnext,N.wsize-Z0):N.wnext-Z0,Z0>N.length&&(Z0=N.length),P=N.window}else P=$0,p=J0-N.offset,Z0=N.length;for(L0g?(E=p[P+O[h]],_[r+O[h]]):(E=96,0),j=1<>J0)+(M-=j)]=d<<24|E<<16|s|0,M!==0;);for(j=1<>=1;if(j!==0?(i&=j-1,i+=j):i=0,h++,--n[S]==0){if(S===a)break;S=W[k+O[h]]}if($0>>7)]}function r(q,w){q.pending_buf[q.pending++]=255&w,q.pending_buf[q.pending++]=w>>>8&255}function n(q,w,x){q.bi_valid>V-x?(q.bi_buf|=w<>V-q.bi_valid,q.bi_valid+=x-V):(q.bi_buf|=w<>>=1,x<<=1,0<--w;);return x>>>1}function P(q,w,x){var l,u,Q0=Array(O+1),q0=0;for(l=1;l<=O;l++)Q0[l]=q0=q0+x[l-1]<<1;for(u=0;u<=w;u++){var K0=q[2*u+1];K0!==0&&(q[2*u]=p(Q0[K0]++,K0))}}function R(q){var w;for(w=0;w>1;1<=x;x--)v(q,Q0,x);for(u=M0;x=q.heap[1],q.heap[1]=q.heap[q.heap_len--],v(q,Q0,1),l=q.heap[1],q.heap[--q.heap_max]=x,q.heap[--q.heap_max]=l,Q0[2*u]=Q0[2*x]+Q0[2*l],q.depth[u]=(q.depth[x]>=q.depth[l]?q.depth[x]:q.depth[l])+1,Q0[2*x+1]=Q0[2*l+1]=u,q.heap[1]=u++,v(q,Q0,1),2<=q.heap_len;);q.heap[--q.heap_max]=q.heap[1],function(H0,v0){var j2,l0,t2,D0,A1,z8,K2=v0.dyn_tree,NU=v0.max_code,H7=v0.stat_desc.static_tree,j7=v0.stat_desc.has_stree,z7=v0.stat_desc.extra_bits,RU=v0.stat_desc.extra_base,e2=v0.stat_desc.max_length,P1=0;for(D0=0;D0<=O;D0++)H0.bl_count[D0]=0;for(K2[2*H0.heap[H0.heap_max]+1]=0,j2=H0.heap_max+1;j2>=7;u>>=1)if(1&w0&&K0.dyn_ltree[2*M0]!==0)return X;if(K0.dyn_ltree[18]!==0||K0.dyn_ltree[20]!==0||K0.dyn_ltree[26]!==0)return Q;for(M0=32;M0>>3,(Q0=q.static_len+3+7>>>3)<=u&&(u=Q0)):u=Q0=x+5,x+4<=u&&w!==-1?K(q,w,x,l):q.strategy===4||Q0===u?(n(q,2+(l?1:0),3),b(q,V0,S)):(n(q,4+(l?1:0),3),function(K0,M0,w0,H0){var v0;for(n(K0,M0-257,5),n(K0,w0-1,5),n(K0,H0-4,4),v0=0;v0>>8&255,q.pending_buf[q.d_buf+2*q.last_lit+1]=255&w,q.pending_buf[q.l_buf+q.last_lit]=255&x,q.last_lit++,w===0?q.dyn_ltree[2*x]++:(q.matches++,w--,q.dyn_ltree[2*(N[x]+W+1)]++,q.dyn_dtree[2*_(w)]++),q.last_lit===q.lit_bufsize-1},J._tr_align=function(q){n(q,2,3),Z0(q,M,V0),function(w){w.bi_valid===16?(r(w,w.bi_buf),w.bi_buf=0,w.bi_valid=0):8<=w.bi_valid&&(w.pending_buf[w.pending++]=255&w.bi_buf,w.bi_buf>>=8,w.bi_valid-=8)}(q)}},{"../utils/common":41}],53:[function(Y,Z,J){Z.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(Y,Z,J){(function(G){(function(X,Q){if(!X.setImmediate){var B,F,z,W,k=1,D={},C=!1,H=X.document,O=Object.getPrototypeOf&&Object.getPrototypeOf(X);O=O&&O.setTimeout?O:X,B={}.toString.call(X.process)==="[object process]"?function(L){j0.nextTick(function(){j(L)})}:function(){if(X.postMessage&&!X.importScripts){var L=!0,A=X.onmessage;return X.onmessage=function(){L=!1},X.postMessage("","*"),X.onmessage=A,L}}()?(W="setImmediate$"+Math.random()+"$",X.addEventListener?X.addEventListener("message",M,!1):X.attachEvent("onmessage",M),function(L){X.postMessage(W+L,"*")}):X.MessageChannel?((z=new MessageChannel).port1.onmessage=function(L){j(L.data)},function(L){z.port2.postMessage(L)}):H&&("onreadystatechange"in H.createElement("script"))?(F=H.documentElement,function(L){var A=H.createElement("script");A.onreadystatechange=function(){j(L),A.onreadystatechange=null,F.removeChild(A),A=null},F.appendChild(A)}):function(L){setTimeout(j,0,L)},O.setImmediate=function(L){typeof L!="function"&&(L=Function(""+L));for(var A=Array(arguments.length-1),y=0;y"u"?G===void 0?this:G:self)}).call(this,typeof c0<"u"?c0:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})}(I9),I9.exports}var YB=UB(),c2=g9(YB),Z1={exports:{}},w9,dZ;function ZB(){if(dZ)return w9;dZ=1;var $={"&":"&",'"':""","'":"'","<":"<",">":">"};function U(Y){return Y&&Y.replace?Y.replace(/([&"<>'])/g,function(Z,J){return $[J]}):Y}return w9=U,w9}var cZ;function QB(){if(cZ)return Z1.exports;cZ=1;var $=ZB(),U=m9().Stream,Y=" ";function Z(F,z){if(typeof z!=="object")z={indent:z};var W=z.stream?new U:null,k="",D=!1,C=!z.indent?"":z.indent===!0?Y:z.indent,H=!0;function O(A){if(!H)A();else j0.nextTick(A)}function V(A,y){if(y!==void 0)k+=y;if(A&&!D)W=W||new U,D=!0;if(A&&D){var g=k;O(function(){W.emit("data",g)}),k=""}}function j(A,y){Q(V,X(A,C,C?1:0),y)}function M(){if(W){var A=k;O(function(){W.emit("data",A),W.emit("end"),W.readable=!1,W.emit("close")})}}function L(A){var y=A.encoding||"UTF-8",g={version:"1.0",encoding:y};if(A.standalone)g.standalone=A.standalone;j({"?xml":{_attr:g}}),k=k.replace("/>","?>")}if(O(function(){H=!1}),z.declaration)L(z.declaration);if(F&&F.forEach)F.forEach(function(A,y){var g;if(y+1===F.length)g=M;j(A,g)});else j(F,M);if(W)return W.readable=!0,W;return k}function J(){var F=Array.prototype.slice.call(arguments),z={_elem:X(F)};return z.push=function(W){if(!this.append)throw Error("not assigned to a parent!");var k=this,D=this._elem.indent;Q(this.append,X(W,D,this._elem.icount+(D?1:0)),function(){k.append(!0)})},z.close=function(W){if(W!==void 0)this.push(W);if(this.end)this.end()},z}function G(F,z){return Array(z||0).join(F||"")}function X(F,z,W){W=W||0;var k=G(z,W),D,C=F,H=!1;if(typeof F==="object"){var O=Object.keys(F);if(D=O[0],C=F[D],C&&C._elem)return C._elem.name=D,C._elem.icount=W,C._elem.indent=z,C._elem.indents=k,C._elem.interrupt=C,C._elem}var V=[],j=[],M;function L(A){var y=Object.keys(A);y.forEach(function(g){V.push(B(g,A[g]))})}switch(typeof C){case"object":if(C===null)break;if(C._attr)L(C._attr);if(C._cdata)j.push(("/g,"]]]]>")+"]]>");if(C.forEach){if(M=!1,j.push(""),C.forEach(function(A){if(typeof A=="object"){var y=Object.keys(A)[0];if(y=="_attr")L(A._attr);else j.push(X(A,z,W+1))}else j.pop(),M=!0,j.push($(A))}),!M)j.push("")}break;default:j.push($(C))}return{name:D,interrupt:H,attributes:V,content:j,icount:W,indents:k,indent:z}}function Q(F,z,W){if(typeof z!="object")return F(!1,z);var k=z.interrupt?1:z.content.length;function D(){while(z.content.length){var H=z.content.shift();if(H===void 0)continue;if(C(H))return;Q(F,H)}if(F(!1,(k>1?z.indents:"")+(z.name?"":"")+(z.indent&&!W?` +`:"")),W)W()}function C(H){if(H.interrupt)return H.interrupt.append=F,H.interrupt.end=D,H.interrupt=!1,F(!0),!0;return!1}if(F(!1,z.indents+(z.name?"<"+z.name:"")+(z.attributes.length?" "+z.attributes.join(" "):"")+(k?z.name?">":"":z.name?"/>":"")+(z.indent&&k>1?` +`:"")),!k)return F(!1,z.indent?` +`:"");if(!C(z))D()}function B(F,z){return F+'="'+$(z)+'"'}return Z1.exports=Z,Z1.exports.element=Z1.exports.Element=J,Z1.exports}var JB=QB(),F0=g9(JB),Q1=0,W9=32,GB=32,KB=($,U)=>{let Y=U.replace(/-/g,"");if(Y.length!==GB)throw Error(`Error: Cannot extract GUID from font filename: ${U}`);let J=Y.replace(/(..)/g,"$1 ").trim().split(" ").map((B)=>parseInt(B,16));J.reverse();let X=$.slice(Q1,W9).map((B,F)=>B^J[F%J.length]),Q=new Uint8Array(Q1+X.length+Math.max(0,$.length-W9));return Q.set($.slice(0,Q1)),Q.set(X,Q1),Q.set($.slice(W9),Q1+X.length),Q};class H8{format($,U={stack:[]}){let Y=$.prepForXml(U);if(Y)return Y;else throw Error("XMLComponent did not format correctly")}}class jU{replace($,U,Y){let Z=$;return U.forEach((J,G)=>{Z=Z.replace(new RegExp(`{${J.fileName}}`,"g"),(Y+G).toString())}),Z}getMediaData($,U){return U.Array.filter((Y)=>$.search(`{${Y.fileName}}`)>0)}}class K7{replace($,U){let Y=$;for(let Z of U)Y=Y.replace(new RegExp(`{${Z.reference}-${Z.instance}}`,"g"),Z.numId.toString());return Y}}class q7{constructor(){Y0(this,"formatter"),Y0(this,"imageReplacer"),Y0(this,"numberingReplacer"),this.formatter=new H8,this.imageReplacer=new jU,this.numberingReplacer=new K7}compile($,U,Y=[]){let Z=new c2,J=this.xmlifyFile($,U),G=new Map(Object.entries(J));for(let[,X]of G)if(Array.isArray(X))for(let Q of X)Z.file(Q.path,X1(Q.data));else Z.file(X.path,X1(X.data));for(let X of Y)Z.file(X.path,X1(X.data));for(let X of $.Media.Array)if(X.type!=="svg")Z.file(`word/media/${X.fileName}`,X.data);else Z.file(`word/media/${X.fileName}`,X.data),Z.file(`word/media/${X.fallback.fileName}`,X.fallback.data);for(let{data:X,name:Q,fontKey:B}of $.FontTable.fontOptionsWithKey){let[F]=Q.split(".");Z.file(`word/fonts/${F}.odttf`,KB(X,B))}return Z}xmlifyFile($,U){let Y=$.Document.Relationships.RelationshipCount+1,Z=F0(this.formatter.format($.Document.View,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),J=$.Comments.Relationships.RelationshipCount+1,G=F0(this.formatter.format($.Comments,{viewWrapper:{View:$.Comments,Relationships:$.Comments.Relationships},file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),X=$.FootNotes.Relationships.RelationshipCount+1,Q=F0(this.formatter.format($.FootNotes.View,{viewWrapper:$.FootNotes,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),B=this.imageReplacer.getMediaData(Z,$.Media),F=this.imageReplacer.getMediaData(G,$.Media),z=this.imageReplacer.getMediaData(Q,$.Media);return{Relationships:{data:(()=>{return B.forEach((W,k)=>{$.Document.Relationships.addRelationship(Y+k,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${W.fileName}`)}),$.Document.Relationships.addRelationship($.Document.Relationships.RelationshipCount+1,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable","fontTable.xml"),F0(this.formatter.format($.Document.Relationships,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/document.xml.rels"},Document:{data:(()=>{let W=this.imageReplacer.replace(Z,B,Y);return this.numberingReplacer.replace(W,$.Numbering.ConcreteNumbering)})(),path:"word/document.xml"},Styles:{data:(()=>{let W=F0(this.formatter.format($.Styles,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}});return this.numberingReplacer.replace(W,$.Numbering.ConcreteNumbering)})(),path:"word/styles.xml"},Properties:{data:F0(this.formatter.format($.CoreProperties,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/core.xml"},Numbering:{data:F0(this.formatter.format($.Numbering,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/numbering.xml"},FileRelationships:{data:F0(this.formatter.format($.FileRelationships,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"_rels/.rels"},HeaderRelationships:$.Headers.map((W,k)=>{let D=F0(this.formatter.format(W.View,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}});return this.imageReplacer.getMediaData(D,$.Media).forEach((H,O)=>{W.Relationships.addRelationship(O,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${H.fileName}`)}),{data:F0(this.formatter.format(W.Relationships,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:`word/_rels/header${k+1}.xml.rels`}}),FooterRelationships:$.Footers.map((W,k)=>{let D=F0(this.formatter.format(W.View,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}});return this.imageReplacer.getMediaData(D,$.Media).forEach((H,O)=>{W.Relationships.addRelationship(O,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${H.fileName}`)}),{data:F0(this.formatter.format(W.Relationships,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:`word/_rels/footer${k+1}.xml.rels`}}),Headers:$.Headers.map((W,k)=>{let D=F0(this.formatter.format(W.View,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),C=this.imageReplacer.getMediaData(D,$.Media),H=this.imageReplacer.replace(D,C,0);return{data:this.numberingReplacer.replace(H,$.Numbering.ConcreteNumbering),path:`word/header${k+1}.xml`}}),Footers:$.Footers.map((W,k)=>{let D=F0(this.formatter.format(W.View,{viewWrapper:W,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),C=this.imageReplacer.getMediaData(D,$.Media),H=this.imageReplacer.replace(D,C,0);return{data:this.numberingReplacer.replace(H,$.Numbering.ConcreteNumbering),path:`word/footer${k+1}.xml`}}),ContentTypes:{data:F0(this.formatter.format($.ContentTypes,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"[Content_Types].xml"},CustomProperties:{data:F0(this.formatter.format($.CustomProperties,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/custom.xml"},AppProperties:{data:F0(this.formatter.format($.AppProperties,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"docProps/app.xml"},FootNotes:{data:(()=>{let W=this.imageReplacer.replace(Q,z,X);return this.numberingReplacer.replace(W,$.Numbering.ConcreteNumbering)})(),path:"word/footnotes.xml"},FootNotesRelationships:{data:(()=>{return z.forEach((W,k)=>{$.FootNotes.Relationships.addRelationship(X+k,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${W.fileName}`)}),F0(this.formatter.format($.FootNotes.Relationships,{viewWrapper:$.FootNotes,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/footnotes.xml.rels"},Endnotes:{data:F0(this.formatter.format($.Endnotes.View,{viewWrapper:$.Endnotes,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"word/endnotes.xml"},EndnotesRelationships:{data:F0(this.formatter.format($.Endnotes.Relationships,{viewWrapper:$.Endnotes,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}),path:"word/_rels/endnotes.xml.rels"},Settings:{data:F0(this.formatter.format($.Settings,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/settings.xml"},Comments:{data:(()=>{let W=this.imageReplacer.replace(G,F,J);return this.numberingReplacer.replace(W,$.Numbering.ConcreteNumbering)})(),path:"word/comments.xml"},CommentsRelationships:{data:(()=>{return F.forEach((W,k)=>{$.Comments.Relationships.addRelationship(J+k,"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",`media/${W.fileName}`)}),F0(this.formatter.format($.Comments.Relationships,{viewWrapper:{View:$.Comments,Relationships:$.Comments.Relationships},file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}})})(),path:"word/_rels/comments.xml.rels"},FontTable:{data:F0(this.formatter.format($.FontTable.View,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{standalone:"yes",encoding:"UTF-8"}}),path:"word/fontTable.xml"},FontTableRelationships:{data:(()=>F0(this.formatter.format($.FontTable.Relationships,{viewWrapper:$.Document,file:$,stack:[]}),{indent:U,declaration:{encoding:"UTF-8"}}))(),path:"word/_rels/fontTable.xml.rels"}}}}var X7={NONE:"",WITH_2_BLANKS:" ",WITH_4_BLANKS:" ",WITH_TAB:"\t"},mZ=($)=>$===!0?X7.WITH_2_BLANKS:$===!1?void 0:$,V7=class ${static pack(U,Y,Z){return b9(this,arguments,function*(J,G,X,Q=[]){return this.compiler.compile(J,mZ(X),Q).generateAsync({type:G,mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",compression:"DEFLATE"})})}static toString(U,Y,Z=[]){return $.pack(U,"string",Y,Z)}static toBuffer(U,Y,Z=[]){return $.pack(U,"nodebuffer",Y,Z)}static toBase64String(U,Y,Z=[]){return $.pack(U,"base64",Y,Z)}static toBlob(U,Y,Z=[]){return $.pack(U,"blob",Y,Z)}static toArrayBuffer(U,Y,Z=[]){return $.pack(U,"arraybuffer",Y,Z)}static toStream(U,Y,Z=[]){let J=new $B.Stream;return this.compiler.compile(U,mZ(Y),Z).generateAsync({type:"nodebuffer",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",compression:"DEFLATE"}).then((X)=>{J.emit("data",X),J.emit("end")}),J}};Y0(V7,"compiler",new q7);var qB=V7,XB=new H8,j8=($)=>{return $8.xml2js($,{compact:!1,captureSpacesBetweenElements:!0})},B7=($)=>{var U;return(U=j8(F0(XB.format(new a2({text:$})))).elements[0].elements)!=null?U:[]},L7=($)=>R0(W0({},$),{attributes:{"xml:space":"preserve"}}),zU=($,U)=>{var Y,Z;return(Z=(Y=$.elements)==null?void 0:Y.filter((J)=>J.name===U)[0].elements)!=null?Z:[]},h2=($,U,Y)=>{let Z=zU($,"Types");if(Z.some((G)=>{var X,Q;return G.type==="element"&&G.name==="Default"&&((X=G==null?void 0:G.attributes)==null?void 0:X.ContentType)===U&&((Q=G==null?void 0:G.attributes)==null?void 0:Q.Extension)===Y}))return;Z.push({attributes:{ContentType:U,Extension:Y},name:"Default",type:"element"})},VB=($)=>{let U=parseInt($.substring(3),10);return isNaN(U)?0:U},BB=($)=>{return zU($,"Relationships").map((Y)=>{var Z,J,G;return VB((G=(J=(Z=Y.attributes)==null?void 0:Z.Id)==null?void 0:J.toString())!=null?G:"")}).reduce((Y,Z)=>Math.max(Y,Z),0)+1},lZ=($,U,Y,Z,J)=>{let G=zU($,"Relationships");return G.push({attributes:{Id:`rId${U}`,Type:Y,Target:Z,TargetMode:J},name:"Relationship",type:"element"}),G};class M7 extends Error{constructor($){super(`Token ${$} not found`);this.name="TokenNotFoundError"}}var LB=($,U)=>{var Y,Z,J,G;for(let X=0;X<((Y=$.elements)!=null?Y:[]).length;X++){let Q=$.elements[X];if(Q.type==="element"&&Q.name==="w:r"){let B=((Z=Q.elements)!=null?Z:[]).filter((F)=>F.type==="element"&&F.name==="w:t");for(let F of B){if(!((J=F.elements)==null?void 0:J[0]))continue;if((G=F.elements[0].text)==null?void 0:G.includes(U))return X}}}throw new M7(U)},MB=($,U)=>{var Y,Z;let J=-1,G=(Z=(Y=$.elements)==null?void 0:Y.map((B,F)=>{var z,W,k;if(J!==-1)return B;if(B.type==="element"&&B.name==="w:t"){let C=((k=(W=(z=B.elements)==null?void 0:z[0])==null?void 0:W.text)!=null?k:"").split(U),H=C.map((O)=>R0(W0(W0({},B),L7(B)),{elements:B7(O)}));if(C.length>1)J=F;return H}else return B}).flat())!=null?Z:[],X=R0(W0({},JSON.parse(JSON.stringify($))),{elements:G.slice(0,J+1)}),Q=R0(W0({},JSON.parse(JSON.stringify($))),{elements:G.slice(J+1)});return{left:X,right:Q}},J1={START:0,MIDDLE:1,END:2},IB=({paragraphElement:$,renderedParagraph:U,originalText:Y,replacementText:Z})=>{let J=U.text.indexOf(Y),G=J+Y.length-1,X=J1.START;for(let Q of U.runs)for(let{text:B,index:F,start:z,end:W}of Q.parts)switch(X){case J1.START:if(J>=z&&J<=W){let k=J-z,D=Math.min(G,W)-z,C=Q.text.substring(k,D+1);if(C==="")continue;let H=B.replace(C,Z);H9($.elements[Q.index].elements[F],H),X=J1.MIDDLE;continue}break;case J1.MIDDLE:if(G<=W){let k=B.substring(G-z+1);H9($.elements[Q.index].elements[F],k);let D=$.elements[Q.index].elements[F];$.elements[Q.index].elements[F]=L7(D),X=J1.END}else H9($.elements[Q.index].elements[F],"");break}return $},H9=($,U)=>{return $.elements=B7(U),$},wB=($)=>{if($.element.name!=="w:p")throw Error(`Invalid node type: ${$.element.name}`);if(!$.element.elements)return{text:"",runs:[],index:-1,pathToParagraph:[]};let U=0,Y=$.element.elements.map((J,G)=>({element:J,i:G})).filter(({element:J})=>J.name==="w:r").map(({element:J,i:G})=>{let X=WB(J,G,U);return U+=X.text.length,X}).filter((J)=>!!J);return{text:Y.reduce((J,G)=>J+G.text,""),runs:Y,index:$.index,pathToParagraph:I7($)}},WB=($,U,Y)=>{if(!$.elements)return{text:"",parts:[],index:-1,start:Y,end:Y};let Z=Y,J=$.elements.map((X,Q)=>{var B,F;return X.name==="w:t"&&X.elements&&X.elements.length>0?{text:(F=(B=X.elements[0].text)==null?void 0:B.toString())!=null?F:"",index:Q,start:Z,end:(()=>{var z,W;return Z+=((W=(z=X.elements[0].text)==null?void 0:z.toString())!=null?W:"").length-1,Z})()}:void 0}).filter((X)=>!!X).map((X)=>X);return{text:J.reduce((X,Q)=>X+Q.text,""),parts:J,index:U,start:Y,end:Z}},I7=($)=>$.parent?[...I7($.parent),$.index]:[$.index],aZ=($)=>{var U,Y;return(Y=(U=$.element.elements)==null?void 0:U.map((Z,J)=>({element:Z,index:J,parent:$})))!=null?Y:[]},w7=($)=>{let U=[],Y=[...aZ({element:$,index:0,parent:void 0})],Z;while(Y.length>0){if(Z=Y.shift(),Z.element.name==="w:p")U=[...U,wB(Z)];Y.push(...aZ(Z))}return U},HB=($,U)=>w7($).filter((Y)=>Y.text.includes(U)),jB=new H8,j9="ɵ",zB=({json:$,patch:U,patchText:Y,context:Z,keepOriginalStyles:J=!0})=>{let G=HB($,Y);if(G.length===0)return{element:$,didFindOccurrence:!1};for(let X of G){let Q=U.children.map((B)=>j8(F0(jB.format(B,Z)))).map((B)=>B.elements[0]);switch(U.type){case y9.DOCUMENT:{let B=FB($,X.pathToParagraph),F=NB(X.pathToParagraph);B.elements.splice(F,1,...Q);break}case y9.PARAGRAPH:default:{let B=W7($,X.pathToParagraph);IB({paragraphElement:B,renderedParagraph:X,originalText:Y,replacementText:j9});let F=LB(B,j9),z=B.elements[F],{left:W,right:k}=MB(z,j9),D=Q,C=k;if(J){let H=z.elements.filter((O)=>O.type==="element"&&O.name==="w:rPr");D=Q.map((O)=>{var V;return R0(W0({},O),{elements:[...H,...(V=O.elements)!=null?V:[]]})}),C=R0(W0({},k),{elements:[...H,...k.elements]})}B.elements.splice(F,1,W,...D,C);break}}}return{element:$,didFindOccurrence:!0}},W7=($,U)=>{let Y=$;for(let Z=1;ZW7($,U.slice(0,U.length-1)),NB=($)=>$[$.length-1],y9={DOCUMENT:"file",PARAGRAPH:"paragraph"},pZ=new jU,RB=new Uint8Array([255,254]),DB=new Uint8Array([254,255]),iZ=($,U)=>{if($.length!==U.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==U[Y])return!1;return!0},AB=($)=>b9(null,[$],function*({outputType:U,data:Y,patches:Z,keepOriginalStyles:J,placeholderDelimiters:G={start:"{{",end:"}}"},recursive:X=!0}){var Q,B,F;let z=Y instanceof c2?Y:yield c2.loadAsync(Y),W=new Map,k={Media:new w8},D=new Map,C=[],H=[],O=!1,V=new Map;for(let[M,L]of Object.entries(z.files)){let A=yield L.async("uint8array"),y=A.slice(0,2);if(iZ(y,RB)||iZ(y,DB)){V.set(M,A);continue}if(!M.endsWith(".xml")&&!M.endsWith(".rels")){V.set(M,A);continue}let g=j8(yield L.async("text"));if(M==="word/document.xml"){let d=(Q=g.elements)==null?void 0:Q.find((E)=>E.name==="w:document");if(d&&d.attributes){for(let E of["mc","wp","r","w15","m"])d.attributes[`xmlns:${E}`]=p1[E];d.attributes["mc:Ignorable"]=`${d.attributes["mc:Ignorable"]||""} w15`.trim()}}if(M.startsWith("word/")&&!M.endsWith(".xml.rels")){let d={file:k,viewWrapper:{Relationships:{addRelationship:(S,h,N,a)=>{H.push({key:M,hyperlink:{id:S,link:N}})}}},stack:[]};if(W.set(M,d),!(G==null?void 0:G.start.trim())||!(G==null?void 0:G.end.trim()))throw Error("Both start and end delimiters must be non-empty strings.");let{start:E,end:s}=G;for(let[S,h]of Object.entries(Z)){let N=`${E}${S}${s}`;while(!0){let{didFindOccurrence:a}=zB({json:g,patch:R0(W0({},h),{children:h.children.map(($0)=>{if($0 instanceof K8){let m=new _2($0.options.children,R1());return H.push({key:M,hyperlink:{id:m.linkId,link:$0.options.link}}),m}else return $0})}),patchText:N,context:d,keepOriginalStyles:J});if(!X||!a)break}}let V0=pZ.getMediaData(JSON.stringify(g),d.file.Media);if(V0.length>0)O=!0,C.push({key:M,mediaDatas:V0})}D.set(M,g)}for(let{key:M,mediaDatas:L}of C){let A=`word/_rels/${M.split("/").pop()}.rels`,y=(B=D.get(A))!=null?B:rZ();D.set(A,y);let g=BB(y),d=pZ.replace(JSON.stringify(D.get(M)),L,g);D.set(M,JSON.parse(d));for(let E=0;E{return $8.js2xml($,{attributeValueFn:(Y)=>String(Y).replace(/&(?!amp;|lt;|gt;|quot;|apos;)/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")})},rZ=()=>({declaration:{attributes:{version:"1.0",encoding:"UTF-8",standalone:"yes"}},elements:[{type:"element",name:"Relationships",attributes:{xmlns:"http://schemas.openxmlformats.org/package/2006/relationships"},elements:[]}]}),TB=($)=>b9(null,[$],function*({data:U}){let Y=U instanceof c2?U:yield c2.loadAsync(U),Z=new Set;for(let[J,G]of Object.entries(Y.files)){if(!J.endsWith(".xml")&&!J.endsWith(".rels"))continue;if(J.startsWith("word/")&&!J.endsWith(".xml.rels")){let X=j8(yield G.async("text"));w7(X).forEach((Q)=>CB(Q.text).forEach((B)=>Z.add(B)))}}return Array.from(Z)}),CB=($)=>{var U;let Y=new RegExp("(?<=\\{\\{).+?(?=\\}\\})","gs");return(U=$.match(Y))!=null?U:[]};if(typeof globalThis.Buffer>"u")globalThis.Buffer=G0;if(typeof globalThis.process>"u")globalThis.process=OB;globalThis.__bundles=globalThis.__bundles||{};globalThis.__bundles.docx=FU;})(); diff --git a/apps/sim/lib/execution/sandbox/bundles/pdf-lib.cjs b/apps/sim/lib/execution/sandbox/bundles/pdf-lib.cjs index 78b81395b66..f56f8e9699a 100644 --- a/apps/sim/lib/execution/sandbox/bundles/pdf-lib.cjs +++ b/apps/sim/lib/execution/sandbox/bundles/pdf-lib.cjs @@ -1,7 +1,7 @@ // sandbox bundle: pdf-lib // generated by apps/sim/lib/execution/sandbox/bundles/build.ts // do not edit by hand. run `bun run build:sandbox-bundles` to regenerate. -(()=>{var dK=Object.create;var{getPrototypeOf:nK,defineProperty:fq,getOwnPropertyNames:rK}=Object;var iK=Object.prototype.hasOwnProperty;function aK(q){return this[q]}var oK,sK,$8=(q,X,V)=>{var K=q!=null&&typeof q==="object";if(K){var Q=X?oK??=new WeakMap:sK??=new WeakMap,Y=Q.get(q);if(Y)return Y}V=q!=null?dK(nK(q)):{};let J=X||!q||!q.__esModule?fq(V,"default",{value:q,enumerable:!0}):V;for(let G of rK(q))if(!iK.call(J,G))fq(J,G,{get:aK.bind(q,G),enumerable:!0});if(K)Q.set(q,J);return J};var g0=(q,X)=>()=>(X||q((X={exports:{}}).exports,X),X.exports);var tK=(q)=>q;function eK(q,X){this[q]=tK.bind(null,X)}var qQ=(q,X)=>{for(var V in X)fq(q,V,{get:X[V],enumerable:!0,configurable:!0,set:eK.bind(X,V)})};var gX=g0((b3,uX)=>{var w0=uX.exports={},F2,P2;function sq(){throw Error("setTimeout has not been defined")}function tq(){throw Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function")F2=setTimeout;else F2=sq}catch(q){F2=sq}try{if(typeof clearTimeout==="function")P2=clearTimeout;else P2=tq}catch(q){P2=tq}})();function FX(q){if(F2===setTimeout)return setTimeout(q,0);if((F2===sq||!F2)&&setTimeout)return F2=setTimeout,setTimeout(q,0);try{return F2(q,0)}catch(X){try{return F2.call(null,q,0)}catch(V){return F2.call(this,q,0)}}}function FQ(q){if(P2===clearTimeout)return clearTimeout(q);if((P2===tq||!P2)&&clearTimeout)return P2=clearTimeout,clearTimeout(q);try{return P2(q)}catch(X){try{return P2.call(null,q)}catch(V){return P2.call(this,q)}}}var o2=[],$5=!1,d6,h1=-1;function PQ(){if(!$5||!d6)return;if($5=!1,d6.length)o2=d6.concat(o2);else h1=-1;if(o2.length)PX()}function PX(){if($5)return;var q=FX(PQ);$5=!0;var X=o2.length;while(X){d6=o2,o2=[];while(++h11)for(var V=1;V{var _Q=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function cQ(q,X){return Object.prototype.hasOwnProperty.call(q,X)}r0.assign=function(q){var X=Array.prototype.slice.call(arguments,1);while(X.length){var V=X.shift();if(!V)continue;if(typeof V!=="object")throw TypeError(V+"must be non-object");for(var K in V)if(cQ(V,K))q[K]=V[K]}return q};r0.shrinkBuf=function(q,X){if(q.length===X)return q;if(q.subarray)return q.subarray(0,X);return q.length=X,q};var pQ={arraySet:function(q,X,V,K,Q){if(X.subarray&&q.subarray){q.set(X.subarray(V,V+K),Q);return}for(var Y=0;Y{var nQ=t2(),rQ=4,pX=0,dX=1,iQ=2;function u5(q){var X=q.length;while(--X>=0)q[X]=0}var aQ=0,sX=1,oQ=2,sQ=3,tQ=258,N4=29,p8=256,f8=p8+1+N4,D5=30,S4=19,tX=2*f8+1,i6=15,T4=16,eQ=7,y4=256,eX=16,qV=17,XV=18,A4=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],g1=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],qY=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],VV=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],XY=512,e2=Array((f8+2)*2);u5(e2);var m8=Array(D5*2);u5(m8);var l8=Array(XY);u5(l8);var _8=Array(tQ-sQ+1);u5(_8);var $4=Array(N4);u5($4);var x1=Array(D5);u5(x1);function v4(q,X,V,K,Q){this.static_tree=q,this.extra_bits=X,this.extra_base=V,this.elems=K,this.max_length=Q,this.has_stree=q&&q.length}var KV,QV,YV;function R4(q,X){this.dyn_tree=q,this.max_code=0,this.stat_desc=X}function JV(q){return q<256?l8[q]:l8[256+(q>>>7)]}function c8(q,X){q.pending_buf[q.pending++]=X&255,q.pending_buf[q.pending++]=X>>>8&255}function q2(q,X,V){if(q.bi_valid>T4-V)q.bi_buf|=X<>T4-q.bi_valid,q.bi_valid+=V-T4;else q.bi_buf|=X<>>=1,V<<=1;while(--X>0);return V>>>1}function VY(q){if(q.bi_valid===16)c8(q,q.bi_buf),q.bi_buf=0,q.bi_valid=0;else if(q.bi_valid>=8)q.pending_buf[q.pending++]=q.bi_buf&255,q.bi_buf>>=8,q.bi_valid-=8}function KY(q,X){var{dyn_tree:V,max_code:K}=X,Q=X.stat_desc.static_tree,Y=X.stat_desc.has_stree,J=X.stat_desc.extra_bits,G=X.stat_desc.extra_base,W=X.stat_desc.max_length,Z,H,U,z,k,M,j=0;for(z=0;z<=i6;z++)q.bl_count[z]=0;V[q.heap[q.heap_max]*2+1]=0;for(Z=q.heap_max+1;ZW)z=W,j++;if(V[H*2+1]=z,H>K)continue;if(q.bl_count[z]++,k=0,H>=G)k=J[H-G];if(M=V[H*2],q.opt_len+=M*(z+k),Y)q.static_len+=M*(Q[H*2+1]+k)}if(j===0)return;do{z=W-1;while(q.bl_count[z]===0)z--;q.bl_count[z]--,q.bl_count[z+1]+=2,q.bl_count[W]--,j-=2}while(j>0);for(z=W;z!==0;z--){H=q.bl_count[z];while(H!==0){if(U=q.heap[--Z],U>K)continue;if(V[U*2+1]!==z)q.opt_len+=(z-V[U*2+1])*V[U*2],V[U*2+1]=z;H--}}}function ZV(q,X,V){var K=Array(i6+1),Q=0,Y,J;for(Y=1;Y<=i6;Y++)K[Y]=Q=Q+V[Y-1]<<1;for(J=0;J<=X;J++){var G=q[J*2+1];if(G===0)continue;q[J*2]=GV(K[G]++,G)}}function QY(){var q,X,V,K,Q,Y=Array(i6+1);V=0;for(K=0;K>=7;for(;K8)c8(q,q.bi_buf);else if(q.bi_valid>0)q.pending_buf[q.pending++]=q.bi_buf;q.bi_buf=0,q.bi_valid=0}function YY(q,X,V,K){if(HV(q),K)c8(q,V),c8(q,~V);nQ.arraySet(q.pending_buf,q.window,X,V,q.pending),q.pending+=V}function nX(q,X,V,K){var Q=X*2,Y=V*2;return q[Q]>1;J>=1;J--)O4(q,V,J);Z=Y;do J=q.heap[1],q.heap[1]=q.heap[q.heap_len--],O4(q,V,1),G=q.heap[1],q.heap[--q.heap_max]=J,q.heap[--q.heap_max]=G,V[Z*2]=V[J*2]+V[G*2],q.depth[Z]=(q.depth[J]>=q.depth[G]?q.depth[J]:q.depth[G])+1,V[J*2+1]=V[G*2+1]=Z,q.heap[1]=Z++,O4(q,V,1);while(q.heap_len>=2);q.heap[--q.heap_max]=q.heap[1],KY(q,X),ZV(V,W,q.bl_count)}function iX(q,X,V){var K,Q=-1,Y,J=X[1],G=0,W=7,Z=4;if(J===0)W=138,Z=3;X[(V+1)*2+1]=65535;for(K=0;K<=V;K++){if(Y=J,J=X[(K+1)*2+1],++G=3;X--)if(q.bl_tree[VV[X]*2+1]!==0)break;return q.opt_len+=3*(X+1)+5+5+4,X}function GY(q,X,V,K){var Q;q2(q,X-257,5),q2(q,V-1,5),q2(q,K-4,4);for(Q=0;Q>>=1)if(X&1&&q.dyn_ltree[V*2]!==0)return pX;if(q.dyn_ltree[18]!==0||q.dyn_ltree[20]!==0||q.dyn_ltree[26]!==0)return dX;for(V=32;V0){if(q.strm.data_type===iQ)q.strm.data_type=ZY(q);if(w4(q,q.l_desc),w4(q,q.d_desc),J=JY(q),Q=q.opt_len+3+7>>>3,Y=q.static_len+3+7>>>3,Y<=Q)Q=Y}else Q=Y=V+5;if(V+4<=Q&&X!==-1)UV(q,X,V,K);else if(q.strategy===rQ||Y===Q)q2(q,(sX<<1)+(K?1:0),3),rX(q,e2,m8);else q2(q,(oQ<<1)+(K?1:0),3),GY(q,q.l_desc.max_code+1,q.d_desc.max_code+1,J+1),rX(q,q.dyn_ltree,q.dyn_dtree);if(WV(q),K)HV(q)}function zY(q,X,V){if(q.pending_buf[q.d_buf+q.last_lit*2]=X>>>8&255,q.pending_buf[q.d_buf+q.last_lit*2+1]=X&255,q.pending_buf[q.l_buf+q.last_lit]=V&255,q.last_lit++,X===0)q.dyn_ltree[V*2]++;else q.matches++,X--,q.dyn_ltree[(_8[V]+p8+1)*2]++,q.dyn_dtree[JV(X)*2]++;return q.last_lit===q.lit_bufsize-1}g5._tr_init=WY;g5._tr_stored_block=UV;g5._tr_flush_block=UY;g5._tr_tally=zY;g5._tr_align=HY});var C4=g0((t3,MV)=>{function MY(q,X,V,K){var Q=q&65535|0,Y=q>>>16&65535|0,J=0;while(V!==0){J=V>2000?2000:V,V-=J;do Q=Q+X[K++]|0,Y=Y+Q|0;while(--J);Q%=65521,Y%=65521}return Q|Y<<16|0}MV.exports=MY});var h4=g0((e3,kV)=>{function kY(){var q,X=[];for(var V=0;V<256;V++){q=V;for(var K=0;K<8;K++)q=q&1?3988292384^q>>>1:q>>>1;X[V]=q}return X}var IY=kY();function EY(q,X,V,K){var Q=IY,Y=K+V;q^=-1;for(var J=K;J>>8^Q[(q^X[J])&255];return q^-1}kV.exports=EY});var b1=g0((qW,IV)=>{IV.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var AV=g0((m2)=>{var i0=t2(),H2=zV(),BV=C4(),B6=h4(),jY=b1(),t6=0,LY=1,BY=3,A6=4,EV=5,b2=0,jV=1,U2=-2,TY=-3,F4=-5,vY=-1,RY=1,m1=2,OY=3,AY=4,wY=0,NY=2,c1=8,SY=9,yY=15,$Y=8,CY=29,hY=256,D4=hY+1+CY,FY=30,PY=19,DY=2*D4+1,uY=15,H0=3,R6=258,O2=R6+H0+1,gY=32,p1=42,u4=69,f1=73,l1=91,_1=103,a6=113,n8=666,h0=1,r8=2,o6=3,m5=4,xY=3;function O6(q,X){return q.msg=jY[X],X}function LV(q){return(q<<1)-(q>4?9:0)}function v6(q){var X=q.length;while(--X>=0)q[X]=0}function T6(q){var X=q.state,V=X.pending;if(V>q.avail_out)V=q.avail_out;if(V===0)return;if(i0.arraySet(q.output,X.pending_buf,X.pending_out,V,q.next_out),q.next_out+=V,X.pending_out+=V,q.total_out+=V,q.avail_out-=V,X.pending-=V,X.pending===0)X.pending_out=0}function x0(q,X){H2._tr_flush_block(q,q.block_start>=0?q.block_start:-1,q.strstart-q.block_start,X),q.block_start=q.strstart,T6(q.strm)}function U0(q,X){q.pending_buf[q.pending++]=X}function d8(q,X){q.pending_buf[q.pending++]=X>>>8&255,q.pending_buf[q.pending++]=X&255}function bY(q,X,V,K){var Q=q.avail_in;if(Q>K)Q=K;if(Q===0)return 0;if(q.avail_in-=Q,i0.arraySet(X,q.input,q.next_in,Q,V),q.state.wrap===1)q.adler=BV(q.adler,X,Q,V);else if(q.state.wrap===2)q.adler=B6(q.adler,X,Q,V);return q.next_in+=Q,q.total_in+=Q,Q}function TV(q,X){var{max_chain_length:V,strstart:K}=q,Q,Y,J=q.prev_length,G=q.nice_match,W=q.strstart>q.w_size-O2?q.strstart-(q.w_size-O2):0,Z=q.window,H=q.w_mask,U=q.prev,z=q.strstart+R6,k=Z[K+J-1],M=Z[K+J];if(q.prev_length>=q.good_match)V>>=2;if(G>q.lookahead)G=q.lookahead;do{if(Q=X,Z[Q+J]!==M||Z[Q+J-1]!==k||Z[Q]!==Z[K]||Z[++Q]!==Z[K+1])continue;K+=2,Q++;do;while(Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&KJ){if(q.match_start=X,J=Y,Y>=G)break;k=Z[K+J-1],M=Z[K+J]}}while((X=U[X&H])>W&&--V!==0);if(J<=q.lookahead)return J;return q.lookahead}function s6(q){var X=q.w_size,V,K,Q,Y,J;do{if(Y=q.window_size-q.lookahead-q.strstart,q.strstart>=X+(X-O2)){i0.arraySet(q.window,q.window,X,X,0),q.match_start-=X,q.strstart-=X,q.block_start-=X,K=q.hash_size,V=K;do Q=q.head[--V],q.head[V]=Q>=X?Q-X:0;while(--K);K=X,V=K;do Q=q.prev[--V],q.prev[V]=Q>=X?Q-X:0;while(--K);Y+=X}if(q.strm.avail_in===0)break;if(K=bY(q.strm,q.window,q.strstart+q.lookahead,Y),q.lookahead+=K,q.lookahead+q.insert>=H0){J=q.strstart-q.insert,q.ins_h=q.window[J],q.ins_h=(q.ins_h<q.pending_buf_size-5)V=q.pending_buf_size-5;for(;;){if(q.lookahead<=1){if(s6(q),q.lookahead===0&&X===t6)return h0;if(q.lookahead===0)break}q.strstart+=q.lookahead,q.lookahead=0;var K=q.block_start+V;if(q.strstart===0||q.strstart>=K){if(q.lookahead=q.strstart-K,q.strstart=K,x0(q,!1),q.strm.avail_out===0)return h0}if(q.strstart-q.block_start>=q.w_size-O2){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===A6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.strstart>q.block_start){if(x0(q,!1),q.strm.avail_out===0)return h0}return h0}function P4(q,X){var V,K;for(;;){if(q.lookahead=H0)q.ins_h=(q.ins_h<=H0)if(K=H2._tr_tally(q,q.strstart-q.match_start,q.match_length-H0),q.lookahead-=q.match_length,q.match_length<=q.max_lazy_match&&q.lookahead>=H0){q.match_length--;do q.strstart++,q.ins_h=(q.ins_h<=H0)q.ins_h=(q.ins_h<4096))q.match_length=H0-1}if(q.prev_length>=H0&&q.match_length<=q.prev_length){Q=q.strstart+q.lookahead-H0,K=H2._tr_tally(q,q.strstart-1-q.prev_match,q.prev_length-H0),q.lookahead-=q.prev_length-1,q.prev_length-=2;do if(++q.strstart<=Q)q.ins_h=(q.ins_h<=H0&&q.strstart>0){if(Q=q.strstart-1,K=J[Q],K===J[++Q]&&K===J[++Q]&&K===J[++Q]){Y=q.strstart+R6;do;while(K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&Qq.lookahead)q.match_length=q.lookahead}}if(q.match_length>=H0)V=H2._tr_tally(q,1,q.match_length-H0),q.lookahead-=q.match_length,q.strstart+=q.match_length,q.match_length=0;else V=H2._tr_tally(q,0,q.window[q.strstart]),q.lookahead--,q.strstart++;if(V){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===A6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.last_lit){if(x0(q,!1),q.strm.avail_out===0)return h0}return r8}function lY(q,X){var V;for(;;){if(q.lookahead===0){if(s6(q),q.lookahead===0){if(X===t6)return h0;break}}if(q.match_length=0,V=H2._tr_tally(q,0,q.window[q.strstart]),q.lookahead--,q.strstart++,V){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===A6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.last_lit){if(x0(q,!1),q.strm.avail_out===0)return h0}return r8}function x2(q,X,V,K,Q){this.good_length=q,this.max_lazy=X,this.nice_length=V,this.max_chain=K,this.func=Q}var b5;b5=[new x2(0,0,0,0,mY),new x2(4,4,8,4,P4),new x2(4,5,16,8,P4),new x2(4,6,32,32,P4),new x2(4,4,16,16,x5),new x2(8,16,32,32,x5),new x2(8,16,128,128,x5),new x2(8,32,128,256,x5),new x2(32,128,258,1024,x5),new x2(32,258,258,4096,x5)];function _Y(q){q.window_size=2*q.w_size,v6(q.head),q.max_lazy_match=b5[q.level].max_lazy,q.good_match=b5[q.level].good_length,q.nice_match=b5[q.level].nice_length,q.max_chain_length=b5[q.level].max_chain,q.strstart=0,q.block_start=0,q.lookahead=0,q.insert=0,q.match_length=q.prev_length=H0-1,q.match_available=0,q.ins_h=0}function cY(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=c1,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i0.Buf16(DY*2),this.dyn_dtree=new i0.Buf16((2*FY+1)*2),this.bl_tree=new i0.Buf16((2*PY+1)*2),v6(this.dyn_ltree),v6(this.dyn_dtree),v6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i0.Buf16(uY+1),this.heap=new i0.Buf16(2*D4+1),v6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i0.Buf16(2*D4+1),v6(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function vV(q){var X;if(!q||!q.state)return O6(q,U2);if(q.total_in=q.total_out=0,q.data_type=NY,X=q.state,X.pending=0,X.pending_out=0,X.wrap<0)X.wrap=-X.wrap;return X.status=X.wrap?p1:a6,q.adler=X.wrap===2?0:1,X.last_flush=t6,H2._tr_init(X),b2}function RV(q){var X=vV(q);if(X===b2)_Y(q.state);return X}function pY(q,X){if(!q||!q.state)return U2;if(q.state.wrap!==2)return U2;return q.state.gzhead=X,b2}function OV(q,X,V,K,Q,Y){if(!q)return U2;var J=1;if(X===vY)X=6;if(K<0)J=0,K=-K;else if(K>15)J=2,K-=16;if(Q<1||Q>SY||V!==c1||K<8||K>15||X<0||X>9||Y<0||Y>AY)return O6(q,U2);if(K===8)K=9;var G=new cY;return q.state=G,G.strm=q,G.wrap=J,G.gzhead=null,G.w_bits=K,G.w_size=1<EV||X<0)return q?O6(q,U2):U2;if(K=q.state,!q.output||!q.input&&q.avail_in!==0||K.status===n8&&X!==A6)return O6(q,q.avail_out===0?F4:U2);if(K.strm=q,V=K.last_flush,K.last_flush=X,K.status===p1)if(K.wrap===2)if(q.adler=0,U0(K,31),U0(K,139),U0(K,8),!K.gzhead)U0(K,0),U0(K,0),U0(K,0),U0(K,0),U0(K,0),U0(K,K.level===9?2:K.strategy>=m1||K.level<2?4:0),U0(K,xY),K.status=a6;else{if(U0(K,(K.gzhead.text?1:0)+(K.gzhead.hcrc?2:0)+(!K.gzhead.extra?0:4)+(!K.gzhead.name?0:8)+(!K.gzhead.comment?0:16)),U0(K,K.gzhead.time&255),U0(K,K.gzhead.time>>8&255),U0(K,K.gzhead.time>>16&255),U0(K,K.gzhead.time>>24&255),U0(K,K.level===9?2:K.strategy>=m1||K.level<2?4:0),U0(K,K.gzhead.os&255),K.gzhead.extra&&K.gzhead.extra.length)U0(K,K.gzhead.extra.length&255),U0(K,K.gzhead.extra.length>>8&255);if(K.gzhead.hcrc)q.adler=B6(q.adler,K.pending_buf,K.pending,0);K.gzindex=0,K.status=u4}else{var J=c1+(K.w_bits-8<<4)<<8,G=-1;if(K.strategy>=m1||K.level<2)G=0;else if(K.level<6)G=1;else if(K.level===6)G=2;else G=3;if(J|=G<<6,K.strstart!==0)J|=gY;if(J+=31-J%31,K.status=a6,d8(K,J),K.strstart!==0)d8(K,q.adler>>>16),d8(K,q.adler&65535);q.adler=1}if(K.status===u4)if(K.gzhead.extra){Q=K.pending;while(K.gzindex<(K.gzhead.extra.length&65535)){if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size)break}U0(K,K.gzhead.extra[K.gzindex]&255),K.gzindex++}if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(K.gzindex===K.gzhead.extra.length)K.gzindex=0,K.status=f1}else K.status=f1;if(K.status===f1)if(K.gzhead.name){Q=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size){Y=1;break}}if(K.gzindexQ)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(Y===0)K.gzindex=0,K.status=l1}else K.status=l1;if(K.status===l1)if(K.gzhead.comment){Q=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size){Y=1;break}}if(K.gzindexQ)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(Y===0)K.status=_1}else K.status=_1;if(K.status===_1)if(K.gzhead.hcrc){if(K.pending+2>K.pending_buf_size)T6(q);if(K.pending+2<=K.pending_buf_size)U0(K,q.adler&255),U0(K,q.adler>>8&255),q.adler=0,K.status=a6}else K.status=a6;if(K.pending!==0){if(T6(q),q.avail_out===0)return K.last_flush=-1,b2}else if(q.avail_in===0&&LV(X)<=LV(V)&&X!==A6)return O6(q,F4);if(K.status===n8&&q.avail_in!==0)return O6(q,F4);if(q.avail_in!==0||K.lookahead!==0||X!==t6&&K.status!==n8){var W=K.strategy===m1?lY(K,X):K.strategy===OY?fY(K,X):b5[K.level].func(K,X);if(W===o6||W===m5)K.status=n8;if(W===h0||W===o6){if(q.avail_out===0)K.last_flush=-1;return b2}if(W===r8){if(X===LY)H2._tr_align(K);else if(X!==EV){if(H2._tr_stored_block(K,0,0,!1),X===BY){if(v6(K.head),K.lookahead===0)K.strstart=0,K.block_start=0,K.insert=0}}if(T6(q),q.avail_out===0)return K.last_flush=-1,b2}}if(X!==A6)return b2;if(K.wrap<=0)return jV;if(K.wrap===2)U0(K,q.adler&255),U0(K,q.adler>>8&255),U0(K,q.adler>>16&255),U0(K,q.adler>>24&255),U0(K,q.total_in&255),U0(K,q.total_in>>8&255),U0(K,q.total_in>>16&255),U0(K,q.total_in>>24&255);else d8(K,q.adler>>>16),d8(K,q.adler&65535);if(T6(q),K.wrap>0)K.wrap=-K.wrap;return K.pending!==0?b2:jV}function rY(q){var X;if(!q||!q.state)return U2;if(X=q.state.status,X!==p1&&X!==u4&&X!==f1&&X!==l1&&X!==_1&&X!==a6&&X!==n8)return O6(q,U2);return q.state=null,X===a6?O6(q,TY):b2}function iY(q,X){var V=X.length,K,Q,Y,J,G,W,Z,H;if(!q||!q.state)return U2;if(K=q.state,J=K.wrap,J===2||J===1&&K.status!==p1||K.lookahead)return U2;if(J===1)q.adler=BV(q.adler,X,V,0);if(K.wrap=0,V>=K.w_size){if(J===0)v6(K.head),K.strstart=0,K.block_start=0,K.insert=0;H=new i0.Buf8(K.w_size),i0.arraySet(H,X,V-K.w_size,K.w_size,0),X=H,V=K.w_size}G=q.avail_in,W=q.next_in,Z=q.input,q.avail_in=V,q.next_in=0,q.input=X,s6(K);while(K.lookahead>=H0){Q=K.strstart,Y=K.lookahead-(H0-1);do K.ins_h=(K.ins_h<{var d1=t2(),wV=!0,NV=!0;try{String.fromCharCode.apply(null,[0])}catch(q){wV=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(q){NV=!1}var i8=new d1.Buf8(256);for(f2=0;f2<256;f2++)i8[f2]=f2>=252?6:f2>=248?5:f2>=240?4:f2>=224?3:f2>=192?2:1;var f2;i8[254]=i8[254]=1;f5.string2buf=function(q){var X,V,K,Q,Y,J=q.length,G=0;for(Q=0;Q>>6,X[Y++]=128|V&63;else if(V<65536)X[Y++]=224|V>>>12,X[Y++]=128|V>>>6&63,X[Y++]=128|V&63;else X[Y++]=240|V>>>18,X[Y++]=128|V>>>12&63,X[Y++]=128|V>>>6&63,X[Y++]=128|V&63}return X};function SV(q,X){if(X<65534){if(q.subarray&&NV||!q.subarray&&wV)return String.fromCharCode.apply(null,d1.shrinkBuf(q,X))}var V="";for(var K=0;K4){G[K++]=65533,V+=Y-1;continue}Q&=Y===2?31:Y===3?15:7;while(Y>1&&V1){G[K++]=65533;continue}if(Q<65536)G[K++]=Q;else Q-=65536,G[K++]=55296|Q>>10&1023,G[K++]=56320|Q&1023}return SV(G,K)};f5.utf8border=function(q,X){var V;if(X=X||q.length,X>q.length)X=q.length;V=X-1;while(V>=0&&(q[V]&192)===128)V--;if(V<0)return X;if(V===0)return X;return V+i8[q[V]]>X?V:X}});var x4=g0((KW,yV)=>{function aY(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}yV.exports=aY});var FV=g0((s8)=>{var a8=AV(),o8=t2(),m4=g4(),f4=b1(),oY=x4(),hV=Object.prototype.toString,sY=0,b4=4,l5=0,$V=1,CV=2,tY=-1,eY=0,qJ=8;function e6(q){if(!(this instanceof e6))return new e6(q);this.options=o8.assign({level:tY,method:qJ,chunkSize:16384,windowBits:15,memLevel:8,strategy:eY,to:""},q||{});var X=this.options;if(X.raw&&X.windowBits>0)X.windowBits=-X.windowBits;else if(X.gzip&&X.windowBits>0&&X.windowBits<16)X.windowBits+=16;this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new oY,this.strm.avail_out=0;var V=a8.deflateInit2(this.strm,X.level,X.method,X.windowBits,X.memLevel,X.strategy);if(V!==l5)throw Error(f4[V]);if(X.header)a8.deflateSetHeader(this.strm,X.header);if(X.dictionary){var K;if(typeof X.dictionary==="string")K=m4.string2buf(X.dictionary);else if(hV.call(X.dictionary)==="[object ArrayBuffer]")K=new Uint8Array(X.dictionary);else K=X.dictionary;if(V=a8.deflateSetDictionary(this.strm,K),V!==l5)throw Error(f4[V]);this._dict_set=!0}}e6.prototype.push=function(q,X){var V=this.strm,K=this.options.chunkSize,Q,Y;if(this.ended)return!1;if(Y=X===~~X?X:X===!0?b4:sY,typeof q==="string")V.input=m4.string2buf(q);else if(hV.call(q)==="[object ArrayBuffer]")V.input=new Uint8Array(q);else V.input=q;V.next_in=0,V.avail_in=V.input.length;do{if(V.avail_out===0)V.output=new o8.Buf8(K),V.next_out=0,V.avail_out=K;if(Q=a8.deflate(V,Y),Q!==$V&&Q!==l5)return this.onEnd(Q),this.ended=!0,!1;if(V.avail_out===0||V.avail_in===0&&(Y===b4||Y===CV))if(this.options.to==="string")this.onData(m4.buf2binstring(o8.shrinkBuf(V.output,V.next_out)));else this.onData(o8.shrinkBuf(V.output,V.next_out))}while((V.avail_in>0||V.avail_out===0)&&Q!==$V);if(Y===b4)return Q=a8.deflateEnd(this.strm),this.onEnd(Q),this.ended=!0,Q===l5;if(Y===CV)return this.onEnd(l5),V.avail_out=0,!0;return!0};e6.prototype.onData=function(q){this.chunks.push(q)};e6.prototype.onEnd=function(q){if(q===l5)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=o8.flattenChunks(this.chunks);this.chunks=[],this.err=q,this.msg=this.strm.msg};function l4(q,X){var V=new e6(X);if(V.push(q,!0),V.err)throw V.msg||f4[V.err];return V.result}function XJ(q,X){return X=X||{},X.raw=!0,l4(q,X)}function VJ(q,X){return X=X||{},X.gzip=!0,l4(q,X)}s8.Deflate=e6;s8.deflate=l4;s8.deflateRaw=XJ;s8.gzip=VJ});var DV=g0((YW,PV)=>{var n1=30,KJ=12;PV.exports=function(X,V){var K,Q,Y,J,G,W,Z,H,U,z,k,M,j,B,L,O,N,R,v,A,$,S,h,b,C;K=X.state,Q=X.next_in,b=X.input,Y=Q+(X.avail_in-5),J=X.next_out,C=X.output,G=J-(V-X.avail_out),W=J+(X.avail_out-257),Z=K.dmax,H=K.wsize,U=K.whave,z=K.wnext,k=K.window,M=K.hold,j=K.bits,B=K.lencode,L=K.distcode,O=(1<>>24,M>>>=v,j-=v,v=R>>>16&255,v===0)C[J++]=R&65535;else if(v&16){if(A=R&65535,v&=15,v){if(j>>=v,j-=v}if(j<15)M+=b[Q++]<>>24,M>>>=v,j-=v,v=R>>>16&255,v&16){if($=R&65535,v&=15,jZ){X.msg="invalid distance too far back",K.mode=n1;break q}if(M>>>=v,j-=v,v=J-G,$>v){if(v=$-v,v>U){if(K.sane){X.msg="invalid distance too far back",K.mode=n1;break q}}if(S=0,h=k,z===0){if(S+=H-v,v2)C[J++]=h[S++],C[J++]=h[S++],C[J++]=h[S++],A-=3;if(A){if(C[J++]=h[S++],A>1)C[J++]=h[S++]}}else{S=J-$;do C[J++]=C[S++],C[J++]=C[S++],C[J++]=C[S++],A-=3;while(A>2);if(A){if(C[J++]=C[S++],A>1)C[J++]=C[S++]}}}else if((v&64)===0){R=L[(R&65535)+(M&(1<>3,Q-=A,j-=A<<3,M&=(1<{var uV=t2(),_5=15,gV=852,xV=592,bV=0,_4=1,mV=2,QJ=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],YJ=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],JJ=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],GJ=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];fV.exports=function(X,V,K,Q,Y,J,G,W){var Z=W.bits,H=0,U=0,z=0,k=0,M=0,j=0,B=0,L=0,O=0,N=0,R,v,A,$,S,h=null,b=0,C,D=new uV.Buf16(_5+1),l=new uV.Buf16(_5+1),u=null,q0=0,J0,r,I0;for(H=0;H<=_5;H++)D[H]=0;for(U=0;U=1;k--)if(D[k]!==0)break;if(M>k)M=k;if(k===0)return Y[J++]=20971520,Y[J++]=20971520,W.bits=1,0;for(z=1;z0&&(X===bV||k!==1))return-1;l[1]=0;for(H=1;H<_5;H++)l[H+1]=l[H]+D[H];for(U=0;UgV||X===mV&&O>xV)return 1;for(;;){if(J0=H-B,G[U]C)r=u[q0+G[U]],I0=h[b+G[U]];else r=96,I0=0;R=1<>B)+v]=J0<<24|r<<16|I0|0;while(v!==0);R=1<>=1;if(R!==0)N&=R-1,N+=R;else N=0;if(U++,--D[H]===0){if(H===k)break;H=V[K+G[U]]}if(H>M&&(N&$)!==A){if(B===0)B=M;S+=z,j=H-B,L=1<gV||X===mV&&O>xV)return 1;A=N&$,Y[A]=M<<24|j<<16|S-J|0}}if(N!==0)Y[S+N]=H-B<<24|4194304|0;return W.bits=M,0}});var R9=g0((A2)=>{var Q2=t2(),i4=C4(),l2=h4(),ZJ=DV(),t8=lV(),WJ=0,M9=1,k9=2,_V=4,HJ=5,r1=6,q5=0,UJ=1,zJ=2,z2=-2,I9=-3,a4=-4,MJ=-5,cV=8,E9=1,pV=2,dV=3,nV=4,rV=5,iV=6,aV=7,oV=8,sV=9,tV=10,o1=11,q6=12,c4=13,eV=14,p4=15,q9=16,X9=17,V9=18,K9=19,i1=20,a1=21,Q9=22,Y9=23,J9=24,G9=25,Z9=26,d4=27,W9=28,H9=29,L0=30,o4=31,kJ=32,IJ=852,EJ=592,jJ=15,LJ=jJ;function U9(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function BJ(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Q2.Buf16(320),this.work=new Q2.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function j9(q){var X;if(!q||!q.state)return z2;if(X=q.state,q.total_in=q.total_out=X.total=0,q.msg="",X.wrap)q.adler=X.wrap&1;return X.mode=E9,X.last=0,X.havedict=0,X.dmax=32768,X.head=null,X.hold=0,X.bits=0,X.lencode=X.lendyn=new Q2.Buf32(IJ),X.distcode=X.distdyn=new Q2.Buf32(EJ),X.sane=1,X.back=-1,q5}function L9(q){var X;if(!q||!q.state)return z2;return X=q.state,X.wsize=0,X.whave=0,X.wnext=0,j9(q)}function B9(q,X){var V,K;if(!q||!q.state)return z2;if(K=q.state,X<0)V=0,X=-X;else if(V=(X>>4)+1,X<48)X&=15;if(X&&(X<8||X>15))return z2;if(K.window!==null&&K.wbits!==X)K.window=null;return K.wrap=V,K.wbits=X,L9(q)}function T9(q,X){var V,K;if(!q)return z2;if(K=new BJ,q.state=K,K.window=null,V=B9(q,X),V!==q5)q.state=null;return V}function TJ(q){return T9(q,LJ)}var z9=!0,n4,r4;function vJ(q){if(z9){var X;n4=new Q2.Buf32(512),r4=new Q2.Buf32(32),X=0;while(X<144)q.lens[X++]=8;while(X<256)q.lens[X++]=9;while(X<280)q.lens[X++]=7;while(X<288)q.lens[X++]=8;t8(M9,q.lens,0,288,n4,0,q.work,{bits:9}),X=0;while(X<32)q.lens[X++]=5;t8(k9,q.lens,0,32,r4,0,q.work,{bits:5}),z9=!1}q.lencode=n4,q.lenbits=9,q.distcode=r4,q.distbits=5}function v9(q,X,V,K){var Q,Y=q.state;if(Y.window===null)Y.wsize=1<=Y.wsize)Q2.arraySet(Y.window,X,V-Y.wsize,Y.wsize,0),Y.wnext=0,Y.whave=Y.wsize;else{if(Q=Y.wsize-Y.wnext,Q>K)Q=K;if(Q2.arraySet(Y.window,X,V-K,Q,Y.wnext),K-=Q,K)Q2.arraySet(Y.window,X,V-K,K,0),Y.wnext=K,Y.whave=Y.wsize;else{if(Y.wnext+=Q,Y.wnext===Y.wsize)Y.wnext=0;if(Y.whave>>8&255,V.check=l2(V.check,h,2,0),Z=0,H=0,V.mode=pV;break}if(V.flags=0,V.head)V.head.done=!1;if(!(V.wrap&1)||(((Z&255)<<8)+(Z>>8))%31){q.msg="incorrect header check",V.mode=L0;break}if((Z&15)!==cV){q.msg="unknown compression method",V.mode=L0;break}if(Z>>>=4,H-=4,$=(Z&15)+8,V.wbits===0)V.wbits=$;else if($>V.wbits){q.msg="invalid window size",V.mode=L0;break}V.dmax=1<<$,q.adler=V.check=1,V.mode=Z&512?tV:q6,Z=0,H=0;break;case pV:while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>8&1;if(V.flags&512)h[0]=Z&255,h[1]=Z>>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0,V.mode=dV;case dV:while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>8&255,h[2]=Z>>>16&255,h[3]=Z>>>24&255,V.check=l2(V.check,h,4,0);Z=0,H=0,V.mode=nV;case nV:while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>8;if(V.flags&512)h[0]=Z&255,h[1]=Z>>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0,V.mode=rV;case rV:if(V.flags&1024){while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0}else if(V.head)V.head.extra=null;V.mode=iV;case iV:if(V.flags&1024){if(k=V.length,k>G)k=G;if(k){if(V.head){if($=V.head.extra_len-V.length,!V.head.extra)V.head.extra=Array(V.head.extra_len);Q2.arraySet(V.head.extra,K,Y,k,$)}if(V.flags&512)V.check=l2(V.check,K,k,Y);G-=k,Y+=k,V.length-=k}if(V.length)break q}V.length=0,V.mode=aV;case aV:if(V.flags&2048){if(G===0)break q;k=0;do if($=K[Y+k++],V.head&&$&&V.length<65536)V.head.name+=String.fromCharCode($);while($&&k>9&1,V.head.done=!0;q.adler=V.check=0,V.mode=q6;break;case tV:while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>=H&7,H-=H&7,V.mode=d4;break}while(H<3){if(G===0)break q;G--,Z+=K[Y++]<>>=1,H-=1,Z&3){case 0:V.mode=eV;break;case 1:if(vJ(V),V.mode=i1,X===r1){Z>>>=2,H-=2;break q}break;case 2:V.mode=X9;break;case 3:q.msg="invalid block type",V.mode=L0}Z>>>=2,H-=2;break;case eV:Z>>>=H&7,H-=H&7;while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>16^65535)){q.msg="invalid stored block lengths",V.mode=L0;break}if(V.length=Z&65535,Z=0,H=0,V.mode=p4,X===r1)break q;case p4:V.mode=q9;case q9:if(k=V.length,k){if(k>G)k=G;if(k>W)k=W;if(k===0)break q;Q2.arraySet(Q,K,Y,k,J),G-=k,Y+=k,W-=k,J+=k,V.length-=k;break}V.mode=q6;break;case X9:while(H<14){if(G===0)break q;G--,Z+=K[Y++]<>>=5,H-=5,V.ndist=(Z&31)+1,Z>>>=5,H-=5,V.ncode=(Z&15)+4,Z>>>=4,H-=4,V.nlen>286||V.ndist>30){q.msg="too many length or distance symbols",V.mode=L0;break}V.have=0,V.mode=V9;case V9:while(V.have>>=3,H-=3}while(V.have<19)V.lens[D[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,b={bits:V.lenbits},S=t8(WJ,V.lens,0,19,V.lencode,0,V.work,b),V.lenbits=b.bits,S){q.msg="invalid code lengths set",V.mode=L0;break}V.have=0,V.mode=K9;case K9:while(V.have>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=L,H-=L,V.lens[V.have++]=N;else{if(N===16){C=L+2;while(H>>=L,H-=L,V.have===0){q.msg="invalid bit length repeat",V.mode=L0;break}$=V.lens[V.have-1],k=3+(Z&3),Z>>>=2,H-=2}else if(N===17){C=L+3;while(H>>=L,H-=L,$=0,k=3+(Z&7),Z>>>=3,H-=3}else{C=L+7;while(H>>=L,H-=L,$=0,k=11+(Z&127),Z>>>=7,H-=7}if(V.have+k>V.nlen+V.ndist){q.msg="invalid bit length repeat",V.mode=L0;break}while(k--)V.lens[V.have++]=$}}if(V.mode===L0)break;if(V.lens[256]===0){q.msg="invalid code -- missing end-of-block",V.mode=L0;break}if(V.lenbits=9,b={bits:V.lenbits},S=t8(M9,V.lens,0,V.nlen,V.lencode,0,V.work,b),V.lenbits=b.bits,S){q.msg="invalid literal/lengths set",V.mode=L0;break}if(V.distbits=6,V.distcode=V.distdyn,b={bits:V.distbits},S=t8(k9,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,b),V.distbits=b.bits,S){q.msg="invalid distances set",V.mode=L0;break}if(V.mode=i1,X===r1)break q;case i1:V.mode=a1;case a1:if(G>=6&&W>=258){if(q.next_out=J,q.avail_out=W,q.next_in=Y,q.avail_in=G,V.hold=Z,V.bits=H,ZJ(q,z),J=q.next_out,Q=q.output,W=q.avail_out,Y=q.next_in,K=q.input,G=q.avail_in,Z=V.hold,H=V.bits,V.mode===q6)V.back=-1;break}V.back=0;for(;;){if(B=V.lencode[Z&(1<>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>R)],L=B>>>24,O=B>>>16&255,N=B&65535,R+L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=R,H-=R,V.back+=R}if(Z>>>=L,H-=L,V.back+=L,V.length=N,O===0){V.mode=Z9;break}if(O&32){V.back=-1,V.mode=q6;break}if(O&64){q.msg="invalid literal/length code",V.mode=L0;break}V.extra=O&15,V.mode=Q9;case Q9:if(V.extra){C=V.extra;while(H>>=V.extra,H-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=Y9;case Y9:for(;;){if(B=V.distcode[Z&(1<>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>R)],L=B>>>24,O=B>>>16&255,N=B&65535,R+L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=R,H-=R,V.back+=R}if(Z>>>=L,H-=L,V.back+=L,O&64){q.msg="invalid distance code",V.mode=L0;break}V.offset=N,V.extra=O&15,V.mode=J9;case J9:if(V.extra){C=V.extra;while(H>>=V.extra,H-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){q.msg="invalid distance too far back",V.mode=L0;break}V.mode=G9;case G9:if(W===0)break q;if(k=z-W,V.offset>k){if(k=V.offset-k,k>V.whave){if(V.sane){q.msg="invalid distance too far back",V.mode=L0;break}}if(k>V.wnext)k-=V.wnext,M=V.wsize-k;else M=V.wnext-k;if(k>V.length)k=V.length;j=V.window}else j=Q,M=J-V.offset,k=V.length;if(k>W)k=W;W-=k,V.length-=k;do Q[J++]=j[M++];while(--k);if(V.length===0)V.mode=a1;break;case Z9:if(W===0)break q;Q[J++]=V.length,W--,V.mode=a1;break;case d4:if(V.wrap){while(H<32){if(G===0)break q;G--,Z|=K[Y++]<{O9.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var w9=g0((WW,A9)=>{function NJ(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}A9.exports=NJ});var S9=g0((q1)=>{var c5=R9(),e8=t2(),s1=g4(),N0=s4(),t4=b1(),SJ=x4(),yJ=w9(),N9=Object.prototype.toString;function X5(q){if(!(this instanceof X5))return new X5(q);this.options=e8.assign({chunkSize:16384,windowBits:0,to:""},q||{});var X=this.options;if(X.raw&&X.windowBits>=0&&X.windowBits<16){if(X.windowBits=-X.windowBits,X.windowBits===0)X.windowBits=-15}if(X.windowBits>=0&&X.windowBits<16&&!(q&&q.windowBits))X.windowBits+=32;if(X.windowBits>15&&X.windowBits<48){if((X.windowBits&15)===0)X.windowBits|=15}this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new SJ,this.strm.avail_out=0;var V=c5.inflateInit2(this.strm,X.windowBits);if(V!==N0.Z_OK)throw Error(t4[V]);if(this.header=new yJ,c5.inflateGetHeader(this.strm,this.header),X.dictionary){if(typeof X.dictionary==="string")X.dictionary=s1.string2buf(X.dictionary);else if(N9.call(X.dictionary)==="[object ArrayBuffer]")X.dictionary=new Uint8Array(X.dictionary);if(X.raw){if(V=c5.inflateSetDictionary(this.strm,X.dictionary),V!==N0.Z_OK)throw Error(t4[V])}}}X5.prototype.push=function(q,X){var V=this.strm,K=this.options.chunkSize,Q=this.options.dictionary,Y,J,G,W,Z,H=!1;if(this.ended)return!1;if(J=X===~~X?X:X===!0?N0.Z_FINISH:N0.Z_NO_FLUSH,typeof q==="string")V.input=s1.binstring2buf(q);else if(N9.call(q)==="[object ArrayBuffer]")V.input=new Uint8Array(q);else V.input=q;V.next_in=0,V.avail_in=V.input.length;do{if(V.avail_out===0)V.output=new e8.Buf8(K),V.next_out=0,V.avail_out=K;if(Y=c5.inflate(V,N0.Z_NO_FLUSH),Y===N0.Z_NEED_DICT&&Q)Y=c5.inflateSetDictionary(this.strm,Q);if(Y===N0.Z_BUF_ERROR&&H===!0)Y=N0.Z_OK,H=!1;if(Y!==N0.Z_STREAM_END&&Y!==N0.Z_OK)return this.onEnd(Y),this.ended=!0,!1;if(V.next_out){if(V.avail_out===0||Y===N0.Z_STREAM_END||V.avail_in===0&&(J===N0.Z_FINISH||J===N0.Z_SYNC_FLUSH))if(this.options.to==="string"){if(G=s1.utf8border(V.output,V.next_out),W=V.next_out-G,Z=s1.buf2string(V.output,G),V.next_out=W,V.avail_out=K-W,W)e8.arraySet(V.output,V.output,G,W,0);this.onData(Z)}else this.onData(e8.shrinkBuf(V.output,V.next_out))}if(V.avail_in===0&&V.avail_out===0)H=!0}while((V.avail_in>0||V.avail_out===0)&&Y!==N0.Z_STREAM_END);if(Y===N0.Z_STREAM_END)J=N0.Z_FINISH;if(J===N0.Z_FINISH)return Y=c5.inflateEnd(this.strm),this.onEnd(Y),this.ended=!0,Y===N0.Z_OK;if(J===N0.Z_SYNC_FLUSH)return this.onEnd(N0.Z_OK),V.avail_out=0,!0;return!0};X5.prototype.onData=function(q){this.chunks.push(q)};X5.prototype.onEnd=function(q){if(q===N0.Z_OK)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=e8.flattenChunks(this.chunks);this.chunks=[],this.err=q,this.msg=this.strm.msg};function e4(q,X){var V=new X5(X);if(V.push(q,!0),V.err)throw V.msg||t4[V.err];return V.result}function $J(q,X){return X=X||{},X.raw=!0,e4(q,X)}q1.Inflate=X5;q1.inflate=e4;q1.inflateRaw=$J;q1.ungzip=e4});var X1=g0((UW,$9)=>{var CJ=t2().assign,hJ=FV(),FJ=S9(),PJ=s4(),y9={};CJ(y9,hJ,FJ,PJ);$9.exports=y9});var zX=globalThis;if(typeof zX.global>"u")zX.global=globalThis;var C2=[],W2=[],lq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(c6=0,MX=lq.length;c60)throw Error("Invalid string. Length must be a multiple of 4");var V=q.indexOf("=");if(V===-1)V=X;var K=V===X?0:4-V%4;return[V,K]}function VQ(q,X){return(q+X)*3/4-X}function KQ(q){var X,V=XQ(q),K=V[0],Q=V[1],Y=new Uint8Array(VQ(K,Q)),J=0,G=Q>0?K-4:K,W;for(W=0;W>16&255,Y[J++]=X>>8&255,Y[J++]=X&255;if(Q===2)X=W2[q.charCodeAt(W)]<<2|W2[q.charCodeAt(W+1)]>>4,Y[J++]=X&255;if(Q===1)X=W2[q.charCodeAt(W)]<<10|W2[q.charCodeAt(W+1)]<<4|W2[q.charCodeAt(W+2)]>>2,Y[J++]=X>>8&255,Y[J++]=X&255;return Y}function QQ(q){return C2[q>>18&63]+C2[q>>12&63]+C2[q>>6&63]+C2[q&63]}function YQ(q,X,V){var K,Q=[];for(var Y=X;YG?G:J+Y));if(K===1)X=q[V-1],Q.push(C2[X>>2]+C2[X<<4&63]+"==");else if(K===2)X=(q[V-2]<<8)+q[V-1],Q.push(C2[X>>10]+C2[X>>4&63]+C2[X<<2&63]+"=");return Q.join("")}function $1(q,X,V,K,Q){var Y,J,G=Q*8-K-1,W=(1<>1,H=-7,U=V?Q-1:0,z=V?-1:1,k=q[X+U];U+=z,Y=k&(1<<-H)-1,k>>=-H,H+=G;for(;H>0;Y=Y*256+q[X+U],U+=z,H-=8);J=Y&(1<<-H)-1,Y>>=-H,H+=K;for(;H>0;J=J*256+q[X+U],U+=z,H-=8);if(Y===0)Y=1-Z;else if(Y===W)return J?NaN:(k?-1:1)*(1/0);else J=J+Math.pow(2,K),Y=Y-Z;return(k?-1:1)*J*Math.pow(2,Y-K)}function BX(q,X,V,K,Q,Y){var J,G,W,Z=Y*8-Q-1,H=(1<>1,z=Q===23?Math.pow(2,-24)-Math.pow(2,-77):0,k=K?0:Y-1,M=K?1:-1,j=X<0||X===0&&1/X<0?1:0;if(X=Math.abs(X),isNaN(X)||X===1/0)G=isNaN(X)?1:0,J=H;else{if(J=Math.floor(Math.log(X)/Math.LN2),X*(W=Math.pow(2,-J))<1)J--,W*=2;if(J+U>=1)X+=z/W;else X+=z*Math.pow(2,1-U);if(X*W>=2)J++,W/=2;if(J+U>=H)G=0,J=H;else if(J+U>=1)G=(X*W-1)*Math.pow(2,Q),J=J+U;else G=X*Math.pow(2,U-1)*Math.pow(2,Q),J=0}for(;Q>=8;q[V+k]=G&255,k+=M,G/=256,Q-=8);J=J<0;q[V+k]=J&255,k+=M,J/=256,Z-=8);q[V+k-M]|=j*128}var IX=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null,JQ=50,_q=2147483647;var{btoa:$3,atob:C3,File:h3,Blob:F3}=globalThis;function a2(q){if(q>_q)throw RangeError('The value "'+q+'" is invalid for option "size"');let X=new Uint8Array(q);return Object.setPrototypeOf(X,y.prototype),X}function rq(q,X,V){return class extends V{constructor(){super();Object.defineProperty(this,"message",{value:X.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${q}]`,this.stack,delete this.name}get code(){return q}set code(K){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:K,writable:!0})}toString(){return`${this.name} [${q}]: ${this.message}`}}}var GQ=rq("ERR_BUFFER_OUT_OF_BOUNDS",function(q){if(q)return`${q} is outside of buffer bounds`;return"Attempt to access memory outside buffer bounds"},RangeError),ZQ=rq("ERR_INVALID_ARG_TYPE",function(q,X){return`The "${q}" argument must be of type number. Received type ${typeof X}`},TypeError),cq=rq("ERR_OUT_OF_RANGE",function(q,X,V){let K=`The value of "${q}" is out of range.`,Q=V;if(Number.isInteger(V)&&Math.abs(V)>4294967296)Q=LX(String(V));else if(typeof V==="bigint"){if(Q=String(V),V>BigInt(2)**BigInt(32)||V<-(BigInt(2)**BigInt(32)))Q=LX(Q);Q+="n"}return K+=` It must be ${X}. Received ${Q}`,K},RangeError);function y(q,X,V){if(typeof q==="number"){if(typeof X==="string")throw TypeError('The "string" argument must be of type string. Received type number');return iq(q)}return TX(q,X,V)}Object.defineProperty(y.prototype,"parent",{enumerable:!0,get:function(){if(!y.isBuffer(this))return;return this.buffer}});Object.defineProperty(y.prototype,"offset",{enumerable:!0,get:function(){if(!y.isBuffer(this))return;return this.byteOffset}});y.poolSize=8192;function TX(q,X,V){if(typeof q==="string")return HQ(q,X);if(ArrayBuffer.isView(q))return UQ(q);if(q==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof q);if(h2(q,ArrayBuffer)||q&&h2(q.buffer,ArrayBuffer))return dq(q,X,V);if(typeof SharedArrayBuffer<"u"&&(h2(q,SharedArrayBuffer)||q&&h2(q.buffer,SharedArrayBuffer)))return dq(q,X,V);if(typeof q==="number")throw TypeError('The "value" argument must not be of type number. Received type number');let K=q.valueOf&&q.valueOf();if(K!=null&&K!==q)return y.from(K,X,V);let Q=zQ(q);if(Q)return Q;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof q[Symbol.toPrimitive]==="function")return y.from(q[Symbol.toPrimitive]("string"),X,V);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof q)}y.from=function(q,X,V){return TX(q,X,V)};Object.setPrototypeOf(y.prototype,Uint8Array.prototype);Object.setPrototypeOf(y,Uint8Array);function vX(q){if(typeof q!=="number")throw TypeError('"size" argument must be of type number');else if(q<0)throw RangeError('The value "'+q+'" is invalid for option "size"')}function WQ(q,X,V){if(vX(q),q<=0)return a2(q);if(X!==void 0)return typeof V==="string"?a2(q).fill(X,V):a2(q).fill(X);return a2(q)}y.alloc=function(q,X,V){return WQ(q,X,V)};function iq(q){return vX(q),a2(q<0?0:aq(q)|0)}y.allocUnsafe=function(q){return iq(q)};y.allocUnsafeSlow=function(q){return iq(q)};function HQ(q,X){if(typeof X!=="string"||X==="")X="utf8";if(!y.isEncoding(X))throw TypeError("Unknown encoding: "+X);let V=RX(q,X)|0,K=a2(V),Q=K.write(q,X);if(Q!==V)K=K.slice(0,Q);return K}function pq(q){let X=q.length<0?0:aq(q.length)|0,V=a2(X);for(let K=0;K=_q)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_q.toString(16)+" bytes");return q|0}y.isBuffer=function(q){return q!=null&&q._isBuffer===!0&&q!==y.prototype};y.compare=function(q,X){if(h2(q,Uint8Array))q=y.from(q,q.offset,q.byteLength);if(h2(X,Uint8Array))X=y.from(X,X.offset,X.byteLength);if(!y.isBuffer(q)||!y.isBuffer(X))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(q===X)return 0;let V=q.length,K=X.length;for(let Q=0,Y=Math.min(V,K);QK.length){if(!y.isBuffer(Y))Y=y.from(Y);Y.copy(K,Q)}else Uint8Array.prototype.set.call(K,Y,Q);else if(!y.isBuffer(Y))throw TypeError('"list" argument must be an Array of Buffers');else Y.copy(K,Q);Q+=Y.length}return K};function RX(q,X){if(y.isBuffer(q))return q.length;if(ArrayBuffer.isView(q)||h2(q,ArrayBuffer))return q.byteLength;if(typeof q!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof q);let V=q.length,K=arguments.length>2&&arguments[2]===!0;if(!K&&V===0)return 0;let Q=!1;for(;;)switch(X){case"ascii":case"latin1":case"binary":return V;case"utf8":case"utf-8":return nq(q).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V*2;case"hex":return V>>>1;case"base64":return hX(q).length;default:if(Q)return K?-1:nq(q).length;X=(""+X).toLowerCase(),Q=!0}}y.byteLength=RX;function MQ(q,X,V){let K=!1;if(X===void 0||X<0)X=0;if(X>this.length)return"";if(V===void 0||V>this.length)V=this.length;if(V<=0)return"";if(V>>>=0,X>>>=0,V<=X)return"";if(!q)q="utf8";while(!0)switch(q){case"hex":return OQ(this,X,V);case"utf8":case"utf-8":return AX(this,X,V);case"ascii":return vQ(this,X,V);case"latin1":case"binary":return RQ(this,X,V);case"base64":return BQ(this,X,V);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return AQ(this,X,V);default:if(K)throw TypeError("Unknown encoding: "+q);q=(q+"").toLowerCase(),K=!0}}y.prototype._isBuffer=!0;function p6(q,X,V){let K=q[X];q[X]=q[V],q[V]=K}y.prototype.swap16=function(){let q=this.length;if(q%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let X=0;XX)q+=" ... ";return""};if(IX)y.prototype[IX]=y.prototype.inspect;y.prototype.compare=function(q,X,V,K,Q){if(h2(q,Uint8Array))q=y.from(q,q.offset,q.byteLength);if(!y.isBuffer(q))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof q);if(X===void 0)X=0;if(V===void 0)V=q?q.length:0;if(K===void 0)K=0;if(Q===void 0)Q=this.length;if(X<0||V>q.length||K<0||Q>this.length)throw RangeError("out of range index");if(K>=Q&&X>=V)return 0;if(K>=Q)return-1;if(X>=V)return 1;if(X>>>=0,V>>>=0,K>>>=0,Q>>>=0,this===q)return 0;let Y=Q-K,J=V-X,G=Math.min(Y,J),W=this.slice(K,Q),Z=q.slice(X,V);for(let H=0;H2147483647)V=2147483647;else if(V<-2147483648)V=-2147483648;if(V=+V,Number.isNaN(V))V=Q?0:q.length-1;if(V<0)V=q.length+V;if(V>=q.length)if(Q)return-1;else V=q.length-1;else if(V<0)if(Q)V=0;else return-1;if(typeof X==="string")X=y.from(X,K);if(y.isBuffer(X)){if(X.length===0)return-1;return EX(q,X,V,K,Q)}else if(typeof X==="number"){if(X=X&255,typeof Uint8Array.prototype.indexOf==="function")if(Q)return Uint8Array.prototype.indexOf.call(q,X,V);else return Uint8Array.prototype.lastIndexOf.call(q,X,V);return EX(q,[X],V,K,Q)}throw TypeError("val must be string, number or Buffer")}function EX(q,X,V,K,Q){let Y=1,J=q.length,G=X.length;if(K!==void 0){if(K=String(K).toLowerCase(),K==="ucs2"||K==="ucs-2"||K==="utf16le"||K==="utf-16le"){if(q.length<2||X.length<2)return-1;Y=2,J/=2,G/=2,V/=2}}function W(H,U){if(Y===1)return H[U];else return H.readUInt16BE(U*Y)}let Z;if(Q){let H=-1;for(Z=V;ZJ)V=J-G;for(Z=V;Z>=0;Z--){let H=!0;for(let U=0;UQ)K=Q;let Y=X.length;if(K>Y/2)K=Y/2;let J;for(J=0;J>>0,isFinite(V)){if(V=V>>>0,K===void 0)K="utf8"}else K=V,V=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Q=this.length-X;if(V===void 0||V>Q)V=Q;if(q.length>0&&(V<0||X<0)||X>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!K)K="utf8";let Y=!1;for(;;)switch(K){case"hex":return kQ(this,q,X,V);case"utf8":case"utf-8":return IQ(this,q,X,V);case"ascii":case"latin1":case"binary":return EQ(this,q,X,V);case"base64":return jQ(this,q,X,V);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return LQ(this,q,X,V);default:if(Y)throw TypeError("Unknown encoding: "+K);K=(""+K).toLowerCase(),Y=!0}};y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function BQ(q,X,V){if(X===0&&V===q.length)return kX(q);else return kX(q.slice(X,V))}function AX(q,X,V){V=Math.min(q.length,V);let K=[],Q=X;while(Q239?4:Y>223?3:Y>191?2:1;if(Q+G<=V){let W,Z,H,U;switch(G){case 1:if(Y<128)J=Y;break;case 2:if(W=q[Q+1],(W&192)===128){if(U=(Y&31)<<6|W&63,U>127)J=U}break;case 3:if(W=q[Q+1],Z=q[Q+2],(W&192)===128&&(Z&192)===128){if(U=(Y&15)<<12|(W&63)<<6|Z&63,U>2047&&(U<55296||U>57343))J=U}break;case 4:if(W=q[Q+1],Z=q[Q+2],H=q[Q+3],(W&192)===128&&(Z&192)===128&&(H&192)===128){if(U=(Y&15)<<18|(W&63)<<12|(Z&63)<<6|H&63,U>65535&&U<1114112)J=U}}}if(J===null)J=65533,G=1;else if(J>65535)J-=65536,K.push(J>>>10&1023|55296),J=56320|J&1023;K.push(J),Q+=G}return TQ(K)}var jX=4096;function TQ(q){let X=q.length;if(X<=jX)return String.fromCharCode.apply(String,q);let V="",K=0;while(KK)V=K;let Q="";for(let Y=X;YV)q=V;if(X<0){if(X+=V,X<0)X=0}else if(X>V)X=V;if(XV)throw RangeError("Trying to access beyond buffer length")}y.prototype.readUintLE=y.prototype.readUIntLE=function(q,X,V){if(q=q>>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q],Q=1,Y=0;while(++Y>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q+--X],Q=1;while(X>0&&(Q*=256))K+=this[q+--X]*Q;return K};y.prototype.readUint8=y.prototype.readUInt8=function(q,X){if(q=q>>>0,!X)D0(q,1,this.length);return this[q]};y.prototype.readUint16LE=y.prototype.readUInt16LE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);return this[q]|this[q+1]<<8};y.prototype.readUint16BE=y.prototype.readUInt16BE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);return this[q]<<8|this[q+1]};y.prototype.readUint32LE=y.prototype.readUInt32LE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return(this[q]|this[q+1]<<8|this[q+2]<<16)+this[q+3]*16777216};y.prototype.readUint32BE=y.prototype.readUInt32BE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]*16777216+(this[q+1]<<16|this[q+2]<<8|this[q+3])};y.prototype.readBigUInt64LE=M6(function(q){q=q>>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=X+this[++q]*256+this[++q]*65536+this[++q]*16777216,Q=this[++q]+this[++q]*256+this[++q]*65536+V*16777216;return BigInt(K)+(BigInt(Q)<>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=X*16777216+this[++q]*65536+this[++q]*256+this[++q],Q=this[++q]*16777216+this[++q]*65536+this[++q]*256+V;return(BigInt(K)<>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q],Q=1,Y=0;while(++Y=Q)K-=Math.pow(2,8*X);return K};y.prototype.readIntBE=function(q,X,V){if(q=q>>>0,X=X>>>0,!V)D0(q,X,this.length);let K=X,Q=1,Y=this[q+--K];while(K>0&&(Q*=256))Y+=this[q+--K]*Q;if(Q*=128,Y>=Q)Y-=Math.pow(2,8*X);return Y};y.prototype.readInt8=function(q,X){if(q=q>>>0,!X)D0(q,1,this.length);if(!(this[q]&128))return this[q];return(255-this[q]+1)*-1};y.prototype.readInt16LE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);let V=this[q]|this[q+1]<<8;return V&32768?V|4294901760:V};y.prototype.readInt16BE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);let V=this[q+1]|this[q]<<8;return V&32768?V|4294901760:V};y.prototype.readInt32LE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]|this[q+1]<<8|this[q+2]<<16|this[q+3]<<24};y.prototype.readInt32BE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]<<24|this[q+1]<<16|this[q+2]<<8|this[q+3]};y.prototype.readBigInt64LE=M6(function(q){q=q>>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=this[q+4]+this[q+5]*256+this[q+6]*65536+(V<<24);return(BigInt(K)<>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=(X<<24)+this[++q]*65536+this[++q]*256+this[++q];return(BigInt(K)<>>0,!X)D0(q,4,this.length);return $1(this,q,!0,23,4)};y.prototype.readFloatBE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return $1(this,q,!1,23,4)};y.prototype.readDoubleLE=function(q,X){if(q=q>>>0,!X)D0(q,8,this.length);return $1(this,q,!0,52,8)};y.prototype.readDoubleBE=function(q,X){if(q=q>>>0,!X)D0(q,8,this.length);return $1(this,q,!1,52,8)};function s0(q,X,V,K,Q,Y){if(!y.isBuffer(q))throw TypeError('"buffer" argument must be a Buffer instance');if(X>Q||Xq.length)throw RangeError("Index out of range")}y.prototype.writeUintLE=y.prototype.writeUIntLE=function(q,X,V,K){if(q=+q,X=X>>>0,V=V>>>0,!K){let J=Math.pow(2,8*V)-1;s0(this,q,X,V,J,0)}let Q=1,Y=0;this[X]=q&255;while(++Y>>0,V=V>>>0,!K){let J=Math.pow(2,8*V)-1;s0(this,q,X,V,J,0)}let Q=V-1,Y=1;this[X+Q]=q&255;while(--Q>=0&&(Y*=256))this[X+Q]=q/Y&255;return X+V};y.prototype.writeUint8=y.prototype.writeUInt8=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,1,255,0);return this[X]=q&255,X+1};y.prototype.writeUint16LE=y.prototype.writeUInt16LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,65535,0);return this[X]=q&255,this[X+1]=q>>>8,X+2};y.prototype.writeUint16BE=y.prototype.writeUInt16BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,65535,0);return this[X]=q>>>8,this[X+1]=q&255,X+2};y.prototype.writeUint32LE=y.prototype.writeUInt32LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,4294967295,0);return this[X+3]=q>>>24,this[X+2]=q>>>16,this[X+1]=q>>>8,this[X]=q&255,X+4};y.prototype.writeUint32BE=y.prototype.writeUInt32BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,4294967295,0);return this[X]=q>>>24,this[X+1]=q>>>16,this[X+2]=q>>>8,this[X+3]=q&255,X+4};function wX(q,X,V,K,Q){CX(X,K,Q,q,V,7);let Y=Number(X&BigInt(4294967295));q[V++]=Y,Y=Y>>8,q[V++]=Y,Y=Y>>8,q[V++]=Y,Y=Y>>8,q[V++]=Y;let J=Number(X>>BigInt(32)&BigInt(4294967295));return q[V++]=J,J=J>>8,q[V++]=J,J=J>>8,q[V++]=J,J=J>>8,q[V++]=J,V}function NX(q,X,V,K,Q){CX(X,K,Q,q,V,7);let Y=Number(X&BigInt(4294967295));q[V+7]=Y,Y=Y>>8,q[V+6]=Y,Y=Y>>8,q[V+5]=Y,Y=Y>>8,q[V+4]=Y;let J=Number(X>>BigInt(32)&BigInt(4294967295));return q[V+3]=J,J=J>>8,q[V+2]=J,J=J>>8,q[V+1]=J,J=J>>8,q[V]=J,V+8}y.prototype.writeBigUInt64LE=M6(function(q,X=0){return wX(this,q,X,BigInt(0),BigInt("0xffffffffffffffff"))});y.prototype.writeBigUInt64BE=M6(function(q,X=0){return NX(this,q,X,BigInt(0),BigInt("0xffffffffffffffff"))});y.prototype.writeIntLE=function(q,X,V,K){if(q=+q,X=X>>>0,!K){let G=Math.pow(2,8*V-1);s0(this,q,X,V,G-1,-G)}let Q=0,Y=1,J=0;this[X]=q&255;while(++Q>0)-J&255}return X+V};y.prototype.writeIntBE=function(q,X,V,K){if(q=+q,X=X>>>0,!K){let G=Math.pow(2,8*V-1);s0(this,q,X,V,G-1,-G)}let Q=V-1,Y=1,J=0;this[X+Q]=q&255;while(--Q>=0&&(Y*=256)){if(q<0&&J===0&&this[X+Q+1]!==0)J=1;this[X+Q]=(q/Y>>0)-J&255}return X+V};y.prototype.writeInt8=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,1,127,-128);if(q<0)q=255+q+1;return this[X]=q&255,X+1};y.prototype.writeInt16LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,32767,-32768);return this[X]=q&255,this[X+1]=q>>>8,X+2};y.prototype.writeInt16BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,32767,-32768);return this[X]=q>>>8,this[X+1]=q&255,X+2};y.prototype.writeInt32LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,2147483647,-2147483648);return this[X]=q&255,this[X+1]=q>>>8,this[X+2]=q>>>16,this[X+3]=q>>>24,X+4};y.prototype.writeInt32BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,2147483647,-2147483648);if(q<0)q=4294967295+q+1;return this[X]=q>>>24,this[X+1]=q>>>16,this[X+2]=q>>>8,this[X+3]=q&255,X+4};y.prototype.writeBigInt64LE=M6(function(q,X=0){return wX(this,q,X,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});y.prototype.writeBigInt64BE=M6(function(q,X=0){return NX(this,q,X,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function SX(q,X,V,K,Q,Y){if(V+K>q.length)throw RangeError("Index out of range");if(V<0)throw RangeError("Index out of range")}function yX(q,X,V,K,Q){if(X=+X,V=V>>>0,!Q)SX(q,X,V,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return BX(q,X,V,K,23,4),V+4}y.prototype.writeFloatLE=function(q,X,V){return yX(this,q,X,!0,V)};y.prototype.writeFloatBE=function(q,X,V){return yX(this,q,X,!1,V)};function $X(q,X,V,K,Q){if(X=+X,V=V>>>0,!Q)SX(q,X,V,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return BX(q,X,V,K,52,8),V+8}y.prototype.writeDoubleLE=function(q,X,V){return $X(this,q,X,!0,V)};y.prototype.writeDoubleBE=function(q,X,V){return $X(this,q,X,!1,V)};y.prototype.copy=function(q,X,V,K){if(!y.isBuffer(q))throw TypeError("argument should be a Buffer");if(!V)V=0;if(!K&&K!==0)K=this.length;if(X>=q.length)X=q.length;if(!X)X=0;if(K>0&&K=this.length)throw RangeError("Index out of range");if(K<0)throw RangeError("sourceEnd out of bounds");if(K>this.length)K=this.length;if(q.length-X>>0,V=V===void 0?this.length:V>>>0,!q)q=0;let Q;if(typeof q==="number")for(Q=X;Q=K+4;V-=3)X=`_${q.slice(V-3,V)}${X}`;return`${q.slice(0,V)}${X}`}function wQ(q,X,V){if(y5(X,"offset"),q[X]===void 0||q[X+V]===void 0)C8(X,q.length-(V+1))}function CX(q,X,V,K,Q,Y){if(q>V||q3)if(X===0||X===BigInt(0))G=`>= 0${J} and < 2${J} ** ${(Y+1)*8}${J}`;else G=`>= -(2${J} ** ${(Y+1)*8-1}${J}) and < 2 ** ${(Y+1)*8-1}${J}`;else G=`>= ${X}${J} and <= ${V}${J}`;throw new cq("value",G,q)}wQ(K,Q,Y)}function y5(q,X){if(typeof q!=="number")throw new ZQ(X,"number",q)}function C8(q,X,V){if(Math.floor(q)!==q)throw y5(q,V),new cq(V||"offset","an integer",q);if(X<0)throw new GQ;throw new cq(V||"offset",`>= ${V?1:0} and <= ${X}`,q)}var NQ=/[^+/0-9A-Za-z-_]/g;function SQ(q){if(q=q.split("=")[0],q=q.trim().replace(NQ,""),q.length<2)return"";while(q.length%4!==0)q=q+"=";return q}function nq(q,X){X=X||1/0;let V,K=q.length,Q=null,Y=[];for(let J=0;J55295&&V<57344){if(!Q){if(V>56319){if((X-=3)>-1)Y.push(239,191,189);continue}else if(J+1===K){if((X-=3)>-1)Y.push(239,191,189);continue}Q=V;continue}if(V<56320){if((X-=3)>-1)Y.push(239,191,189);Q=V;continue}V=(Q-55296<<10|V-56320)+65536}else if(Q){if((X-=3)>-1)Y.push(239,191,189)}if(Q=null,V<128){if((X-=1)<0)break;Y.push(V)}else if(V<2048){if((X-=2)<0)break;Y.push(V>>6|192,V&63|128)}else if(V<65536){if((X-=3)<0)break;Y.push(V>>12|224,V>>6&63|128,V&63|128)}else if(V<1114112){if((X-=4)<0)break;Y.push(V>>18|240,V>>12&63|128,V>>6&63|128,V&63|128)}else throw Error("Invalid code point")}return Y}function yQ(q){let X=[];for(let V=0;V>8,Q=V%256,Y.push(Q),Y.push(K)}return Y}function hX(q){return KQ(SQ(q))}function C1(q,X,V,K){let Q;for(Q=0;Q=X.length||Q>=q.length)break;X[Q+V]=q[Q]}return Q}function h2(q,X){return q instanceof X||q!=null&&q.constructor!=null&&q.constructor.name!=null&&q.constructor.name===X.name}var CQ=function(){let q=Array(256);for(let X=0;X<16;++X){let V=X*16;for(let K=0;K<16;++K)q[V+K]="0123456789abcdef"[X]+"0123456789abcdef"[K]}return q}();function M6(q){return typeof BigInt>"u"?hQ:q}function hQ(){throw Error("BigInt not supported")}function oq(q){return()=>{throw Error(q+" is not implemented for node:buffer browser polyfill")}}var P3=oq("resolveObjectURL"),D3=oq("isUtf8");var u3=oq("transcode");var N3=$8(gX(),1);var UX={};qQ(UX,{waitForTick:()=>R2,values:()=>d5,utf8Encode:()=>mQ,utf16Encode:()=>E4,utf16Decode:()=>x8,typedArrayFor:()=>D8,translate:()=>c0,toUint8Array:()=>r6,toRadians:()=>O0,toHexStringOfMinLength:()=>D2,toHexString:()=>u2,toDegrees:()=>k1,toCodePoint:()=>K4,toCharCode:()=>s,sum:()=>z4,stroke:()=>B5,square:()=>lZ,sortedUniq:()=>U4,skewRadians:()=>k8,skewDegrees:()=>bZ,sizeInBytes:()=>P5,singleQuote:()=>t9,showText:()=>L1,setWordSpacing:()=>pZ,setTextRise:()=>nZ,setTextRenderingMode:()=>rZ,setTextMatrix:()=>FK,setStrokingRgbColor:()=>g7,setStrokingGrayscaleColor:()=>D7,setStrokingColor:()=>v5,setStrokingCmykColor:()=>b7,setLineWidth:()=>L5,setLineJoin:()=>fZ,setLineHeight:()=>F7,setLineCap:()=>I8,setGraphicsState:()=>i2,setFontAndSize:()=>T5,setFillingRgbColor:()=>u7,setFillingGrayscaleColor:()=>P7,setFillingColor:()=>E2,setFillingCmykColor:()=>x7,setDashPattern:()=>j5,setCharacterSqueeze:()=>dZ,setCharacterSpacing:()=>cZ,scale:()=>g6,rotateRectangle:()=>y7,rotateRadians:()=>x6,rotateInPlace:()=>j2,rotateDegrees:()=>M8,rotateAndSkewTextRadiansAndTranslate:()=>j8,rotateAndSkewTextDegreesAndTranslate:()=>iZ,rgb:()=>Y0,reverseArray:()=>I6,restoreDashPattern:()=>mZ,reduceRotation:()=>I2,rectanglesAreEqual:()=>n5,rectangle:()=>hK,range:()=>M4,radiansToDegrees:()=>CK,radians:()=>gZ,pushGraphicsState:()=>B0,popGraphicsState:()=>T0,pluckIndices:()=>k4,pdfDocEncodingDecode:()=>J1,parseDate:()=>P8,padStart:()=>e0,numberToString:()=>B4,normalizeAppearance:()=>G2,nextLine:()=>h7,newlineChars:()=>gQ,moveTo:()=>J2,moveText:()=>_Z,mergeUint8Arrays:()=>W4,mergeLines:()=>F1,mergeIntoTypedArray:()=>Z4,lowSurrogate:()=>u1,lineTo:()=>S0,lineSplit:()=>F8,layoutSinglelineText:()=>v8,layoutMultilineText:()=>uq,layoutCombedText:()=>KX,last:()=>n6,isWithinBMP:()=>j4,isType:()=>XK,isStandardFont:()=>e1,isNewlineChar:()=>Y4,highSurrogate:()=>D1,hasUtf16BOM:()=>b8,hasSurrogates:()=>L4,grayscale:()=>Sq,getType:()=>qK,findLastMatch:()=>F5,fillAndStroke:()=>j1,fill:()=>E1,escapedNewlineChars:()=>mX,escapeRegExp:()=>bX,error:()=>L6,endText:()=>T1,endPath:()=>Aq,endMarkedContent:()=>Nq,encodeToBase64:()=>X4,drawTextLines:()=>Fq,drawTextField:()=>Pq,drawText:()=>eZ,drawSvgPath:()=>d7,drawRectangle:()=>b6,drawRadioButton:()=>T8,drawPage:()=>c7,drawOptionList:()=>n7,drawObject:()=>L8,drawLinesOfText:()=>_7,drawLine:()=>p7,drawImage:()=>A1,drawEllipsePath:()=>xK,drawEllipse:()=>O1,drawCheckMark:()=>bK,drawCheckBox:()=>B8,drawButton:()=>hq,degreesToRadians:()=>H6,degrees:()=>p,defaultTextFieldAppearanceProvider:()=>GX,defaultRadioGroupAppearanceProvider:()=>YX,defaultOptionListAppearanceProvider:()=>WX,defaultDropdownAppearanceProvider:()=>ZX,defaultCheckBoxAppearanceProvider:()=>QX,defaultButtonAppearanceProvider:()=>JX,decodePDFRawStream:()=>V8,decodeFromBase64DataUri:()=>V4,decodeFromBase64:()=>q4,createValueErrorMsg:()=>e9,createTypeErrorMsg:()=>VK,createPDFAcroFields:()=>Z8,createPDFAcroField:()=>kq,copyStringIntoBuffer:()=>k0,concatTransformationMatrix:()=>I1,componentsToColor:()=>l0,colorToComponents:()=>$q,cmyk:()=>yq,closePath:()=>N2,clipEvenOdd:()=>xZ,clip:()=>Oq,cleanText:()=>k6,charSplit:()=>J4,charFromHexCode:()=>Q4,charFromCode:()=>t0,charAtIndex:()=>P1,canBeConvertedToUint8Array:()=>I4,bytesFor:()=>j6,byAscendingId:()=>H4,breakTextIntoLines:()=>G4,beginText:()=>B1,beginMarkedContent:()=>wq,backtick:()=>$0,assertRangeOrUndefined:()=>X2,assertRange:()=>b0,assertPositive:()=>X6,assertOrUndefined:()=>F,assertMultiple:()=>Y1,assertIsSubset:()=>V7,assertIsOneOfOrUndefined:()=>a0,assertIsOneOf:()=>M2,assertIs:()=>T,assertInteger:()=>K7,assertEachIs:()=>Q1,asPDFNumber:()=>f,asPDFName:()=>z8,asNumber:()=>t,arrayAsString:()=>u8,appendQuadraticCurve:()=>E8,appendBezierCurve:()=>p0,adjustDimsForRotation:()=>r2,addRandomSuffix:()=>uQ,ViewerPreferences:()=>W1,UnsupportedEncodingError:()=>Q7,UnrecognizedStreamTypeError:()=>J7,UnexpectedObjectTypeError:()=>w6,UnexpectedFieldTypeError:()=>z6,UnbalancedParenthesisError:()=>E7,TextRenderingMode:()=>C7,TextAlignment:()=>v0,StandardFonts:()=>N5,StandardFontValues:()=>o9,StandardFontEmbedder:()=>$6,StalledParserError:()=>j7,RotationTypes:()=>E5,RichTextFieldReadError:()=>e7,ReparseError:()=>Q5,RemovePageFromEmptyDocumentError:()=>o7,ReadingDirection:()=>U5,PrivateConstructorError:()=>K5,PrintScaling:()=>z5,PngEmbedder:()=>X8,ParseSpeeds:()=>w1,PageSizes:()=>HX,PageEmbeddingMismatchedContextError:()=>G7,PDFXRefStreamParser:()=>Lq,PDFWriter:()=>o5,PDFWidgetAnnotation:()=>M5,PDFTrailerDict:()=>Qq,PDFTrailer:()=>S6,PDFTextField:()=>w5,PDFString:()=>K0,PDFStreamWriter:()=>Jq,PDFStreamParsingError:()=>I7,PDFStream:()=>E0,PDFSignature:()=>O8,PDFRef:()=>a,PDFRawStream:()=>w2,PDFRadioGroup:()=>l6,PDFParsingError:()=>V6,PDFParser:()=>Bq,PDFPageTree:()=>H8,PDFPageLeaf:()=>_0,PDFPageEmbedder:()=>K8,PDFPage:()=>y0,PDFOptionList:()=>A5,PDFOperatorNames:()=>X0,PDFOperator:()=>e,PDFObjectStreamParser:()=>jq,PDFObjectStream:()=>a5,PDFObjectParsingError:()=>M7,PDFObjectParser:()=>U8,PDFObjectCopier:()=>Z1,PDFObject:()=>z0,PDFNumber:()=>x,PDFNull:()=>F0,PDFName:()=>I,PDFJavaScript:()=>xq,PDFInvalidObjectParsingError:()=>k7,PDFInvalidObject:()=>s5,PDFImage:()=>R5,PDFHexString:()=>g,PDFHeader:()=>_2,PDFForm:()=>gq,PDFFont:()=>A0,PDFFlateStream:()=>N6,PDFField:()=>d0,PDFEmbeddedPage:()=>R8,PDFDropdown:()=>O5,PDFDocument:()=>o0,PDFDict:()=>m,PDFCrossRefStream:()=>Yq,PDFCrossRefSection:()=>i5,PDFContext:()=>Z5,PDFContentStream:()=>p2,PDFCheckBox:()=>f6,PDFCatalog:()=>W8,PDFButton:()=>S5,PDFBool:()=>c2,PDFArrayIsNotRectangleError:()=>Z7,PDFArray:()=>i,PDFAnnotation:()=>Mq,PDFAcroText:()=>J6,PDFAcroTerminal:()=>K2,PDFAcroSignature:()=>F6,PDFAcroRadioButton:()=>Z6,PDFAcroPushButton:()=>G6,PDFAcroNonTerminal:()=>Y6,PDFAcroListBox:()=>W6,PDFAcroForm:()=>P6,PDFAcroField:()=>Y8,PDFAcroComboBox:()=>Q6,PDFAcroChoice:()=>G8,PDFAcroCheckBox:()=>K6,PDFAcroButton:()=>h6,NumberParsingError:()=>Vq,NonFullScreenPageMode:()=>H5,NoSuchFieldError:()=>s7,NextByteAssertionError:()=>z7,MultiSelectValueError:()=>W7,MissingTfOperatorError:()=>U7,MissingPageContentsEmbeddingError:()=>Y7,MissingPDFHeaderError:()=>L7,MissingOnValueCheckError:()=>X3,MissingKeywordError:()=>B7,MissingDAEntryError:()=>H7,MissingCatalogError:()=>qG,MethodNotImplementedError:()=>u0,LineJoinStyle:()=>$7,LineCapStyle:()=>u6,JpegEmbedder:()=>q8,InvalidTargetIndexError:()=>qq,InvalidPDFDateStringError:()=>G1,InvalidMaxLengthError:()=>VX,InvalidFieldNamePartError:()=>t7,InvalidAcroFieldValueError:()=>J5,IndexOutOfBoundsError:()=>Y5,ImageAlignment:()=>T2,ForeignPageError:()=>a7,FontkitNotRegisteredError:()=>i7,FileEmbedder:()=>Wq,FieldExistsAsNonTerminalError:()=>V3,FieldAlreadyExistsError:()=>Dq,ExceededMaxLengthError:()=>XX,EncryptedPDFError:()=>r7,Duplex:()=>Q8,CustomFontSubsetEmbedder:()=>Zq,CustomFontEmbedder:()=>C6,CorruptPageTreeError:()=>Xq,CombedTextLayoutError:()=>qX,ColorTypes:()=>U6,CharCodes:()=>E,Cache:()=>m0,BlendMode:()=>S2,AppearanceCharacteristics:()=>J8,AnnotationFlags:()=>I5,AcroTextFlags:()=>j0,AcroFieldFlags:()=>Y2,AcroChoiceFlags:()=>G0,AcroButtonFlags:()=>f0,AFRelationship:()=>t5});/*! ***************************************************************************** +(()=>{var dK=Object.create;var{getPrototypeOf:nK,defineProperty:fq,getOwnPropertyNames:rK}=Object;var iK=Object.prototype.hasOwnProperty;function aK(q){return this[q]}var oK,sK,$8=(q,X,V)=>{var K=q!=null&&typeof q==="object";if(K){var Q=X?oK??=new WeakMap:sK??=new WeakMap,Y=Q.get(q);if(Y)return Y}V=q!=null?dK(nK(q)):{};let J=X||!q||!q.__esModule?fq(V,"default",{value:q,enumerable:!0}):V;for(let G of rK(q))if(!iK.call(J,G))fq(J,G,{get:aK.bind(q,G),enumerable:!0});if(K)Q.set(q,J);return J};var g0=(q,X)=>()=>(X||q((X={exports:{}}).exports,X),X.exports);var tK=(q)=>q;function eK(q,X){this[q]=tK.bind(null,X)}var qQ=(q,X)=>{for(var V in X)fq(q,V,{get:X[V],enumerable:!0,configurable:!0,set:eK.bind(X,V)})};var gX=g0((b3,uX)=>{var A0=uX.exports={},F2,P2;function sq(){throw Error("setTimeout has not been defined")}function tq(){throw Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function")F2=setTimeout;else F2=sq}catch(q){F2=sq}try{if(typeof clearTimeout==="function")P2=clearTimeout;else P2=tq}catch(q){P2=tq}})();function FX(q){if(F2===setTimeout)return setTimeout(q,0);if((F2===sq||!F2)&&setTimeout)return F2=setTimeout,setTimeout(q,0);try{return F2(q,0)}catch(X){try{return F2.call(null,q,0)}catch(V){return F2.call(this,q,0)}}}function FQ(q){if(P2===clearTimeout)return clearTimeout(q);if((P2===tq||!P2)&&clearTimeout)return P2=clearTimeout,clearTimeout(q);try{return P2(q)}catch(X){try{return P2.call(null,q)}catch(V){return P2.call(this,q)}}}var o2=[],$5=!1,d6,h1=-1;function PQ(){if(!$5||!d6)return;if($5=!1,d6.length)o2=d6.concat(o2);else h1=-1;if(o2.length)PX()}function PX(){if($5)return;var q=FX(PQ);$5=!0;var X=o2.length;while(X){d6=o2,o2=[];while(++h11)for(var V=1;V{var _Q=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function cQ(q,X){return Object.prototype.hasOwnProperty.call(q,X)}r0.assign=function(q){var X=Array.prototype.slice.call(arguments,1);while(X.length){var V=X.shift();if(!V)continue;if(typeof V!=="object")throw TypeError(V+"must be non-object");for(var K in V)if(cQ(V,K))q[K]=V[K]}return q};r0.shrinkBuf=function(q,X){if(q.length===X)return q;if(q.subarray)return q.subarray(0,X);return q.length=X,q};var pQ={arraySet:function(q,X,V,K,Q){if(X.subarray&&q.subarray){q.set(X.subarray(V,V+K),Q);return}for(var Y=0;Y{var nQ=t2(),rQ=4,pX=0,dX=1,iQ=2;function u5(q){var X=q.length;while(--X>=0)q[X]=0}var aQ=0,sX=1,oQ=2,sQ=3,tQ=258,N4=29,p8=256,f8=p8+1+N4,D5=30,S4=19,tX=2*f8+1,i6=15,T4=16,eQ=7,y4=256,eX=16,qV=17,XV=18,w4=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],g1=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],qY=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],VV=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],XY=512,e2=Array((f8+2)*2);u5(e2);var m8=Array(D5*2);u5(m8);var l8=Array(XY);u5(l8);var _8=Array(tQ-sQ+1);u5(_8);var $4=Array(N4);u5($4);var x1=Array(D5);u5(x1);function v4(q,X,V,K,Q){this.static_tree=q,this.extra_bits=X,this.extra_base=V,this.elems=K,this.max_length=Q,this.has_stree=q&&q.length}var KV,QV,YV;function R4(q,X){this.dyn_tree=q,this.max_code=0,this.stat_desc=X}function JV(q){return q<256?l8[q]:l8[256+(q>>>7)]}function c8(q,X){q.pending_buf[q.pending++]=X&255,q.pending_buf[q.pending++]=X>>>8&255}function q2(q,X,V){if(q.bi_valid>T4-V)q.bi_buf|=X<>T4-q.bi_valid,q.bi_valid+=V-T4;else q.bi_buf|=X<>>=1,V<<=1;while(--X>0);return V>>>1}function VY(q){if(q.bi_valid===16)c8(q,q.bi_buf),q.bi_buf=0,q.bi_valid=0;else if(q.bi_valid>=8)q.pending_buf[q.pending++]=q.bi_buf&255,q.bi_buf>>=8,q.bi_valid-=8}function KY(q,X){var{dyn_tree:V,max_code:K}=X,Q=X.stat_desc.static_tree,Y=X.stat_desc.has_stree,J=X.stat_desc.extra_bits,G=X.stat_desc.extra_base,W=X.stat_desc.max_length,Z,H,U,z,k,M,j=0;for(z=0;z<=i6;z++)q.bl_count[z]=0;V[q.heap[q.heap_max]*2+1]=0;for(Z=q.heap_max+1;ZW)z=W,j++;if(V[H*2+1]=z,H>K)continue;if(q.bl_count[z]++,k=0,H>=G)k=J[H-G];if(M=V[H*2],q.opt_len+=M*(z+k),Y)q.static_len+=M*(Q[H*2+1]+k)}if(j===0)return;do{z=W-1;while(q.bl_count[z]===0)z--;q.bl_count[z]--,q.bl_count[z+1]+=2,q.bl_count[W]--,j-=2}while(j>0);for(z=W;z!==0;z--){H=q.bl_count[z];while(H!==0){if(U=q.heap[--Z],U>K)continue;if(V[U*2+1]!==z)q.opt_len+=(z-V[U*2+1])*V[U*2],V[U*2+1]=z;H--}}}function ZV(q,X,V){var K=Array(i6+1),Q=0,Y,J;for(Y=1;Y<=i6;Y++)K[Y]=Q=Q+V[Y-1]<<1;for(J=0;J<=X;J++){var G=q[J*2+1];if(G===0)continue;q[J*2]=GV(K[G]++,G)}}function QY(){var q,X,V,K,Q,Y=Array(i6+1);V=0;for(K=0;K>=7;for(;K8)c8(q,q.bi_buf);else if(q.bi_valid>0)q.pending_buf[q.pending++]=q.bi_buf;q.bi_buf=0,q.bi_valid=0}function YY(q,X,V,K){if(HV(q),K)c8(q,V),c8(q,~V);nQ.arraySet(q.pending_buf,q.window,X,V,q.pending),q.pending+=V}function nX(q,X,V,K){var Q=X*2,Y=V*2;return q[Q]>1;J>=1;J--)O4(q,V,J);Z=Y;do J=q.heap[1],q.heap[1]=q.heap[q.heap_len--],O4(q,V,1),G=q.heap[1],q.heap[--q.heap_max]=J,q.heap[--q.heap_max]=G,V[Z*2]=V[J*2]+V[G*2],q.depth[Z]=(q.depth[J]>=q.depth[G]?q.depth[J]:q.depth[G])+1,V[J*2+1]=V[G*2+1]=Z,q.heap[1]=Z++,O4(q,V,1);while(q.heap_len>=2);q.heap[--q.heap_max]=q.heap[1],KY(q,X),ZV(V,W,q.bl_count)}function iX(q,X,V){var K,Q=-1,Y,J=X[1],G=0,W=7,Z=4;if(J===0)W=138,Z=3;X[(V+1)*2+1]=65535;for(K=0;K<=V;K++){if(Y=J,J=X[(K+1)*2+1],++G=3;X--)if(q.bl_tree[VV[X]*2+1]!==0)break;return q.opt_len+=3*(X+1)+5+5+4,X}function GY(q,X,V,K){var Q;q2(q,X-257,5),q2(q,V-1,5),q2(q,K-4,4);for(Q=0;Q>>=1)if(X&1&&q.dyn_ltree[V*2]!==0)return pX;if(q.dyn_ltree[18]!==0||q.dyn_ltree[20]!==0||q.dyn_ltree[26]!==0)return dX;for(V=32;V0){if(q.strm.data_type===iQ)q.strm.data_type=ZY(q);if(A4(q,q.l_desc),A4(q,q.d_desc),J=JY(q),Q=q.opt_len+3+7>>>3,Y=q.static_len+3+7>>>3,Y<=Q)Q=Y}else Q=Y=V+5;if(V+4<=Q&&X!==-1)UV(q,X,V,K);else if(q.strategy===rQ||Y===Q)q2(q,(sX<<1)+(K?1:0),3),rX(q,e2,m8);else q2(q,(oQ<<1)+(K?1:0),3),GY(q,q.l_desc.max_code+1,q.d_desc.max_code+1,J+1),rX(q,q.dyn_ltree,q.dyn_dtree);if(WV(q),K)HV(q)}function zY(q,X,V){if(q.pending_buf[q.d_buf+q.last_lit*2]=X>>>8&255,q.pending_buf[q.d_buf+q.last_lit*2+1]=X&255,q.pending_buf[q.l_buf+q.last_lit]=V&255,q.last_lit++,X===0)q.dyn_ltree[V*2]++;else q.matches++,X--,q.dyn_ltree[(_8[V]+p8+1)*2]++,q.dyn_dtree[JV(X)*2]++;return q.last_lit===q.lit_bufsize-1}g5._tr_init=WY;g5._tr_stored_block=UV;g5._tr_flush_block=UY;g5._tr_tally=zY;g5._tr_align=HY});var C4=g0((t3,MV)=>{function MY(q,X,V,K){var Q=q&65535|0,Y=q>>>16&65535|0,J=0;while(V!==0){J=V>2000?2000:V,V-=J;do Q=Q+X[K++]|0,Y=Y+Q|0;while(--J);Q%=65521,Y%=65521}return Q|Y<<16|0}MV.exports=MY});var h4=g0((e3,kV)=>{function kY(){var q,X=[];for(var V=0;V<256;V++){q=V;for(var K=0;K<8;K++)q=q&1?3988292384^q>>>1:q>>>1;X[V]=q}return X}var IY=kY();function EY(q,X,V,K){var Q=IY,Y=K+V;q^=-1;for(var J=K;J>>8^Q[(q^X[J])&255];return q^-1}kV.exports=EY});var b1=g0((qW,IV)=>{IV.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var wV=g0((m2)=>{var i0=t2(),H2=zV(),BV=C4(),B6=h4(),jY=b1(),t6=0,LY=1,BY=3,w6=4,EV=5,b2=0,jV=1,U2=-2,TY=-3,F4=-5,vY=-1,RY=1,m1=2,OY=3,wY=4,AY=0,NY=2,c1=8,SY=9,yY=15,$Y=8,CY=29,hY=256,D4=hY+1+CY,FY=30,PY=19,DY=2*D4+1,uY=15,H0=3,R6=258,O2=R6+H0+1,gY=32,p1=42,u4=69,f1=73,l1=91,_1=103,a6=113,n8=666,h0=1,r8=2,o6=3,m5=4,xY=3;function O6(q,X){return q.msg=jY[X],X}function LV(q){return(q<<1)-(q>4?9:0)}function v6(q){var X=q.length;while(--X>=0)q[X]=0}function T6(q){var X=q.state,V=X.pending;if(V>q.avail_out)V=q.avail_out;if(V===0)return;if(i0.arraySet(q.output,X.pending_buf,X.pending_out,V,q.next_out),q.next_out+=V,X.pending_out+=V,q.total_out+=V,q.avail_out-=V,X.pending-=V,X.pending===0)X.pending_out=0}function x0(q,X){H2._tr_flush_block(q,q.block_start>=0?q.block_start:-1,q.strstart-q.block_start,X),q.block_start=q.strstart,T6(q.strm)}function U0(q,X){q.pending_buf[q.pending++]=X}function d8(q,X){q.pending_buf[q.pending++]=X>>>8&255,q.pending_buf[q.pending++]=X&255}function bY(q,X,V,K){var Q=q.avail_in;if(Q>K)Q=K;if(Q===0)return 0;if(q.avail_in-=Q,i0.arraySet(X,q.input,q.next_in,Q,V),q.state.wrap===1)q.adler=BV(q.adler,X,Q,V);else if(q.state.wrap===2)q.adler=B6(q.adler,X,Q,V);return q.next_in+=Q,q.total_in+=Q,Q}function TV(q,X){var{max_chain_length:V,strstart:K}=q,Q,Y,J=q.prev_length,G=q.nice_match,W=q.strstart>q.w_size-O2?q.strstart-(q.w_size-O2):0,Z=q.window,H=q.w_mask,U=q.prev,z=q.strstart+R6,k=Z[K+J-1],M=Z[K+J];if(q.prev_length>=q.good_match)V>>=2;if(G>q.lookahead)G=q.lookahead;do{if(Q=X,Z[Q+J]!==M||Z[Q+J-1]!==k||Z[Q]!==Z[K]||Z[++Q]!==Z[K+1])continue;K+=2,Q++;do;while(Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&Z[++K]===Z[++Q]&&KJ){if(q.match_start=X,J=Y,Y>=G)break;k=Z[K+J-1],M=Z[K+J]}}while((X=U[X&H])>W&&--V!==0);if(J<=q.lookahead)return J;return q.lookahead}function s6(q){var X=q.w_size,V,K,Q,Y,J;do{if(Y=q.window_size-q.lookahead-q.strstart,q.strstart>=X+(X-O2)){i0.arraySet(q.window,q.window,X,X,0),q.match_start-=X,q.strstart-=X,q.block_start-=X,K=q.hash_size,V=K;do Q=q.head[--V],q.head[V]=Q>=X?Q-X:0;while(--K);K=X,V=K;do Q=q.prev[--V],q.prev[V]=Q>=X?Q-X:0;while(--K);Y+=X}if(q.strm.avail_in===0)break;if(K=bY(q.strm,q.window,q.strstart+q.lookahead,Y),q.lookahead+=K,q.lookahead+q.insert>=H0){J=q.strstart-q.insert,q.ins_h=q.window[J],q.ins_h=(q.ins_h<q.pending_buf_size-5)V=q.pending_buf_size-5;for(;;){if(q.lookahead<=1){if(s6(q),q.lookahead===0&&X===t6)return h0;if(q.lookahead===0)break}q.strstart+=q.lookahead,q.lookahead=0;var K=q.block_start+V;if(q.strstart===0||q.strstart>=K){if(q.lookahead=q.strstart-K,q.strstart=K,x0(q,!1),q.strm.avail_out===0)return h0}if(q.strstart-q.block_start>=q.w_size-O2){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===w6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.strstart>q.block_start){if(x0(q,!1),q.strm.avail_out===0)return h0}return h0}function P4(q,X){var V,K;for(;;){if(q.lookahead=H0)q.ins_h=(q.ins_h<=H0)if(K=H2._tr_tally(q,q.strstart-q.match_start,q.match_length-H0),q.lookahead-=q.match_length,q.match_length<=q.max_lazy_match&&q.lookahead>=H0){q.match_length--;do q.strstart++,q.ins_h=(q.ins_h<=H0)q.ins_h=(q.ins_h<4096))q.match_length=H0-1}if(q.prev_length>=H0&&q.match_length<=q.prev_length){Q=q.strstart+q.lookahead-H0,K=H2._tr_tally(q,q.strstart-1-q.prev_match,q.prev_length-H0),q.lookahead-=q.prev_length-1,q.prev_length-=2;do if(++q.strstart<=Q)q.ins_h=(q.ins_h<=H0&&q.strstart>0){if(Q=q.strstart-1,K=J[Q],K===J[++Q]&&K===J[++Q]&&K===J[++Q]){Y=q.strstart+R6;do;while(K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&K===J[++Q]&&Qq.lookahead)q.match_length=q.lookahead}}if(q.match_length>=H0)V=H2._tr_tally(q,1,q.match_length-H0),q.lookahead-=q.match_length,q.strstart+=q.match_length,q.match_length=0;else V=H2._tr_tally(q,0,q.window[q.strstart]),q.lookahead--,q.strstart++;if(V){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===w6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.last_lit){if(x0(q,!1),q.strm.avail_out===0)return h0}return r8}function lY(q,X){var V;for(;;){if(q.lookahead===0){if(s6(q),q.lookahead===0){if(X===t6)return h0;break}}if(q.match_length=0,V=H2._tr_tally(q,0,q.window[q.strstart]),q.lookahead--,q.strstart++,V){if(x0(q,!1),q.strm.avail_out===0)return h0}}if(q.insert=0,X===w6){if(x0(q,!0),q.strm.avail_out===0)return o6;return m5}if(q.last_lit){if(x0(q,!1),q.strm.avail_out===0)return h0}return r8}function x2(q,X,V,K,Q){this.good_length=q,this.max_lazy=X,this.nice_length=V,this.max_chain=K,this.func=Q}var b5;b5=[new x2(0,0,0,0,mY),new x2(4,4,8,4,P4),new x2(4,5,16,8,P4),new x2(4,6,32,32,P4),new x2(4,4,16,16,x5),new x2(8,16,32,32,x5),new x2(8,16,128,128,x5),new x2(8,32,128,256,x5),new x2(32,128,258,1024,x5),new x2(32,258,258,4096,x5)];function _Y(q){q.window_size=2*q.w_size,v6(q.head),q.max_lazy_match=b5[q.level].max_lazy,q.good_match=b5[q.level].good_length,q.nice_match=b5[q.level].nice_length,q.max_chain_length=b5[q.level].max_chain,q.strstart=0,q.block_start=0,q.lookahead=0,q.insert=0,q.match_length=q.prev_length=H0-1,q.match_available=0,q.ins_h=0}function cY(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=c1,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i0.Buf16(DY*2),this.dyn_dtree=new i0.Buf16((2*FY+1)*2),this.bl_tree=new i0.Buf16((2*PY+1)*2),v6(this.dyn_ltree),v6(this.dyn_dtree),v6(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i0.Buf16(uY+1),this.heap=new i0.Buf16(2*D4+1),v6(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i0.Buf16(2*D4+1),v6(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function vV(q){var X;if(!q||!q.state)return O6(q,U2);if(q.total_in=q.total_out=0,q.data_type=NY,X=q.state,X.pending=0,X.pending_out=0,X.wrap<0)X.wrap=-X.wrap;return X.status=X.wrap?p1:a6,q.adler=X.wrap===2?0:1,X.last_flush=t6,H2._tr_init(X),b2}function RV(q){var X=vV(q);if(X===b2)_Y(q.state);return X}function pY(q,X){if(!q||!q.state)return U2;if(q.state.wrap!==2)return U2;return q.state.gzhead=X,b2}function OV(q,X,V,K,Q,Y){if(!q)return U2;var J=1;if(X===vY)X=6;if(K<0)J=0,K=-K;else if(K>15)J=2,K-=16;if(Q<1||Q>SY||V!==c1||K<8||K>15||X<0||X>9||Y<0||Y>wY)return O6(q,U2);if(K===8)K=9;var G=new cY;return q.state=G,G.strm=q,G.wrap=J,G.gzhead=null,G.w_bits=K,G.w_size=1<EV||X<0)return q?O6(q,U2):U2;if(K=q.state,!q.output||!q.input&&q.avail_in!==0||K.status===n8&&X!==w6)return O6(q,q.avail_out===0?F4:U2);if(K.strm=q,V=K.last_flush,K.last_flush=X,K.status===p1)if(K.wrap===2)if(q.adler=0,U0(K,31),U0(K,139),U0(K,8),!K.gzhead)U0(K,0),U0(K,0),U0(K,0),U0(K,0),U0(K,0),U0(K,K.level===9?2:K.strategy>=m1||K.level<2?4:0),U0(K,xY),K.status=a6;else{if(U0(K,(K.gzhead.text?1:0)+(K.gzhead.hcrc?2:0)+(!K.gzhead.extra?0:4)+(!K.gzhead.name?0:8)+(!K.gzhead.comment?0:16)),U0(K,K.gzhead.time&255),U0(K,K.gzhead.time>>8&255),U0(K,K.gzhead.time>>16&255),U0(K,K.gzhead.time>>24&255),U0(K,K.level===9?2:K.strategy>=m1||K.level<2?4:0),U0(K,K.gzhead.os&255),K.gzhead.extra&&K.gzhead.extra.length)U0(K,K.gzhead.extra.length&255),U0(K,K.gzhead.extra.length>>8&255);if(K.gzhead.hcrc)q.adler=B6(q.adler,K.pending_buf,K.pending,0);K.gzindex=0,K.status=u4}else{var J=c1+(K.w_bits-8<<4)<<8,G=-1;if(K.strategy>=m1||K.level<2)G=0;else if(K.level<6)G=1;else if(K.level===6)G=2;else G=3;if(J|=G<<6,K.strstart!==0)J|=gY;if(J+=31-J%31,K.status=a6,d8(K,J),K.strstart!==0)d8(K,q.adler>>>16),d8(K,q.adler&65535);q.adler=1}if(K.status===u4)if(K.gzhead.extra){Q=K.pending;while(K.gzindex<(K.gzhead.extra.length&65535)){if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size)break}U0(K,K.gzhead.extra[K.gzindex]&255),K.gzindex++}if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(K.gzindex===K.gzhead.extra.length)K.gzindex=0,K.status=f1}else K.status=f1;if(K.status===f1)if(K.gzhead.name){Q=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size){Y=1;break}}if(K.gzindexQ)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(Y===0)K.gzindex=0,K.status=l1}else K.status=l1;if(K.status===l1)if(K.gzhead.comment){Q=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>Q)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(T6(q),Q=K.pending,K.pending===K.pending_buf_size){Y=1;break}}if(K.gzindexQ)q.adler=B6(q.adler,K.pending_buf,K.pending-Q,Q);if(Y===0)K.status=_1}else K.status=_1;if(K.status===_1)if(K.gzhead.hcrc){if(K.pending+2>K.pending_buf_size)T6(q);if(K.pending+2<=K.pending_buf_size)U0(K,q.adler&255),U0(K,q.adler>>8&255),q.adler=0,K.status=a6}else K.status=a6;if(K.pending!==0){if(T6(q),q.avail_out===0)return K.last_flush=-1,b2}else if(q.avail_in===0&&LV(X)<=LV(V)&&X!==w6)return O6(q,F4);if(K.status===n8&&q.avail_in!==0)return O6(q,F4);if(q.avail_in!==0||K.lookahead!==0||X!==t6&&K.status!==n8){var W=K.strategy===m1?lY(K,X):K.strategy===OY?fY(K,X):b5[K.level].func(K,X);if(W===o6||W===m5)K.status=n8;if(W===h0||W===o6){if(q.avail_out===0)K.last_flush=-1;return b2}if(W===r8){if(X===LY)H2._tr_align(K);else if(X!==EV){if(H2._tr_stored_block(K,0,0,!1),X===BY){if(v6(K.head),K.lookahead===0)K.strstart=0,K.block_start=0,K.insert=0}}if(T6(q),q.avail_out===0)return K.last_flush=-1,b2}}if(X!==w6)return b2;if(K.wrap<=0)return jV;if(K.wrap===2)U0(K,q.adler&255),U0(K,q.adler>>8&255),U0(K,q.adler>>16&255),U0(K,q.adler>>24&255),U0(K,q.total_in&255),U0(K,q.total_in>>8&255),U0(K,q.total_in>>16&255),U0(K,q.total_in>>24&255);else d8(K,q.adler>>>16),d8(K,q.adler&65535);if(T6(q),K.wrap>0)K.wrap=-K.wrap;return K.pending!==0?b2:jV}function rY(q){var X;if(!q||!q.state)return U2;if(X=q.state.status,X!==p1&&X!==u4&&X!==f1&&X!==l1&&X!==_1&&X!==a6&&X!==n8)return O6(q,U2);return q.state=null,X===a6?O6(q,TY):b2}function iY(q,X){var V=X.length,K,Q,Y,J,G,W,Z,H;if(!q||!q.state)return U2;if(K=q.state,J=K.wrap,J===2||J===1&&K.status!==p1||K.lookahead)return U2;if(J===1)q.adler=BV(q.adler,X,V,0);if(K.wrap=0,V>=K.w_size){if(J===0)v6(K.head),K.strstart=0,K.block_start=0,K.insert=0;H=new i0.Buf8(K.w_size),i0.arraySet(H,X,V-K.w_size,K.w_size,0),X=H,V=K.w_size}G=q.avail_in,W=q.next_in,Z=q.input,q.avail_in=V,q.next_in=0,q.input=X,s6(K);while(K.lookahead>=H0){Q=K.strstart,Y=K.lookahead-(H0-1);do K.ins_h=(K.ins_h<{var d1=t2(),AV=!0,NV=!0;try{String.fromCharCode.apply(null,[0])}catch(q){AV=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(q){NV=!1}var i8=new d1.Buf8(256);for(f2=0;f2<256;f2++)i8[f2]=f2>=252?6:f2>=248?5:f2>=240?4:f2>=224?3:f2>=192?2:1;var f2;i8[254]=i8[254]=1;f5.string2buf=function(q){var X,V,K,Q,Y,J=q.length,G=0;for(Q=0;Q>>6,X[Y++]=128|V&63;else if(V<65536)X[Y++]=224|V>>>12,X[Y++]=128|V>>>6&63,X[Y++]=128|V&63;else X[Y++]=240|V>>>18,X[Y++]=128|V>>>12&63,X[Y++]=128|V>>>6&63,X[Y++]=128|V&63}return X};function SV(q,X){if(X<65534){if(q.subarray&&NV||!q.subarray&&AV)return String.fromCharCode.apply(null,d1.shrinkBuf(q,X))}var V="";for(var K=0;K4){G[K++]=65533,V+=Y-1;continue}Q&=Y===2?31:Y===3?15:7;while(Y>1&&V1){G[K++]=65533;continue}if(Q<65536)G[K++]=Q;else Q-=65536,G[K++]=55296|Q>>10&1023,G[K++]=56320|Q&1023}return SV(G,K)};f5.utf8border=function(q,X){var V;if(X=X||q.length,X>q.length)X=q.length;V=X-1;while(V>=0&&(q[V]&192)===128)V--;if(V<0)return X;if(V===0)return X;return V+i8[q[V]]>X?V:X}});var x4=g0((KW,yV)=>{function aY(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}yV.exports=aY});var FV=g0((s8)=>{var a8=wV(),o8=t2(),m4=g4(),f4=b1(),oY=x4(),hV=Object.prototype.toString,sY=0,b4=4,l5=0,$V=1,CV=2,tY=-1,eY=0,qJ=8;function e6(q){if(!(this instanceof e6))return new e6(q);this.options=o8.assign({level:tY,method:qJ,chunkSize:16384,windowBits:15,memLevel:8,strategy:eY,to:""},q||{});var X=this.options;if(X.raw&&X.windowBits>0)X.windowBits=-X.windowBits;else if(X.gzip&&X.windowBits>0&&X.windowBits<16)X.windowBits+=16;this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new oY,this.strm.avail_out=0;var V=a8.deflateInit2(this.strm,X.level,X.method,X.windowBits,X.memLevel,X.strategy);if(V!==l5)throw Error(f4[V]);if(X.header)a8.deflateSetHeader(this.strm,X.header);if(X.dictionary){var K;if(typeof X.dictionary==="string")K=m4.string2buf(X.dictionary);else if(hV.call(X.dictionary)==="[object ArrayBuffer]")K=new Uint8Array(X.dictionary);else K=X.dictionary;if(V=a8.deflateSetDictionary(this.strm,K),V!==l5)throw Error(f4[V]);this._dict_set=!0}}e6.prototype.push=function(q,X){var V=this.strm,K=this.options.chunkSize,Q,Y;if(this.ended)return!1;if(Y=X===~~X?X:X===!0?b4:sY,typeof q==="string")V.input=m4.string2buf(q);else if(hV.call(q)==="[object ArrayBuffer]")V.input=new Uint8Array(q);else V.input=q;V.next_in=0,V.avail_in=V.input.length;do{if(V.avail_out===0)V.output=new o8.Buf8(K),V.next_out=0,V.avail_out=K;if(Q=a8.deflate(V,Y),Q!==$V&&Q!==l5)return this.onEnd(Q),this.ended=!0,!1;if(V.avail_out===0||V.avail_in===0&&(Y===b4||Y===CV))if(this.options.to==="string")this.onData(m4.buf2binstring(o8.shrinkBuf(V.output,V.next_out)));else this.onData(o8.shrinkBuf(V.output,V.next_out))}while((V.avail_in>0||V.avail_out===0)&&Q!==$V);if(Y===b4)return Q=a8.deflateEnd(this.strm),this.onEnd(Q),this.ended=!0,Q===l5;if(Y===CV)return this.onEnd(l5),V.avail_out=0,!0;return!0};e6.prototype.onData=function(q){this.chunks.push(q)};e6.prototype.onEnd=function(q){if(q===l5)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=o8.flattenChunks(this.chunks);this.chunks=[],this.err=q,this.msg=this.strm.msg};function l4(q,X){var V=new e6(X);if(V.push(q,!0),V.err)throw V.msg||f4[V.err];return V.result}function XJ(q,X){return X=X||{},X.raw=!0,l4(q,X)}function VJ(q,X){return X=X||{},X.gzip=!0,l4(q,X)}s8.Deflate=e6;s8.deflate=l4;s8.deflateRaw=XJ;s8.gzip=VJ});var DV=g0((YW,PV)=>{var n1=30,KJ=12;PV.exports=function(X,V){var K,Q,Y,J,G,W,Z,H,U,z,k,M,j,B,L,O,N,R,v,w,$,S,h,b,C;K=X.state,Q=X.next_in,b=X.input,Y=Q+(X.avail_in-5),J=X.next_out,C=X.output,G=J-(V-X.avail_out),W=J+(X.avail_out-257),Z=K.dmax,H=K.wsize,U=K.whave,z=K.wnext,k=K.window,M=K.hold,j=K.bits,B=K.lencode,L=K.distcode,O=(1<>>24,M>>>=v,j-=v,v=R>>>16&255,v===0)C[J++]=R&65535;else if(v&16){if(w=R&65535,v&=15,v){if(j>>=v,j-=v}if(j<15)M+=b[Q++]<>>24,M>>>=v,j-=v,v=R>>>16&255,v&16){if($=R&65535,v&=15,jZ){X.msg="invalid distance too far back",K.mode=n1;break q}if(M>>>=v,j-=v,v=J-G,$>v){if(v=$-v,v>U){if(K.sane){X.msg="invalid distance too far back",K.mode=n1;break q}}if(S=0,h=k,z===0){if(S+=H-v,v2)C[J++]=h[S++],C[J++]=h[S++],C[J++]=h[S++],w-=3;if(w){if(C[J++]=h[S++],w>1)C[J++]=h[S++]}}else{S=J-$;do C[J++]=C[S++],C[J++]=C[S++],C[J++]=C[S++],w-=3;while(w>2);if(w){if(C[J++]=C[S++],w>1)C[J++]=C[S++]}}}else if((v&64)===0){R=L[(R&65535)+(M&(1<>3,Q-=w,j-=w<<3,M&=(1<{var uV=t2(),_5=15,gV=852,xV=592,bV=0,_4=1,mV=2,QJ=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],YJ=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],JJ=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],GJ=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];fV.exports=function(X,V,K,Q,Y,J,G,W){var Z=W.bits,H=0,U=0,z=0,k=0,M=0,j=0,B=0,L=0,O=0,N=0,R,v,w,$,S,h=null,b=0,C,D=new uV.Buf16(_5+1),l=new uV.Buf16(_5+1),u=null,q0=0,J0,r,I0;for(H=0;H<=_5;H++)D[H]=0;for(U=0;U=1;k--)if(D[k]!==0)break;if(M>k)M=k;if(k===0)return Y[J++]=20971520,Y[J++]=20971520,W.bits=1,0;for(z=1;z0&&(X===bV||k!==1))return-1;l[1]=0;for(H=1;H<_5;H++)l[H+1]=l[H]+D[H];for(U=0;UgV||X===mV&&O>xV)return 1;for(;;){if(J0=H-B,G[U]C)r=u[q0+G[U]],I0=h[b+G[U]];else r=96,I0=0;R=1<>B)+v]=J0<<24|r<<16|I0|0;while(v!==0);R=1<>=1;if(R!==0)N&=R-1,N+=R;else N=0;if(U++,--D[H]===0){if(H===k)break;H=V[K+G[U]]}if(H>M&&(N&$)!==w){if(B===0)B=M;S+=z,j=H-B,L=1<gV||X===mV&&O>xV)return 1;w=N&$,Y[w]=M<<24|j<<16|S-J|0}}if(N!==0)Y[S+N]=H-B<<24|4194304|0;return W.bits=M,0}});var R9=g0((w2)=>{var Q2=t2(),i4=C4(),l2=h4(),ZJ=DV(),t8=lV(),WJ=0,M9=1,k9=2,_V=4,HJ=5,r1=6,q5=0,UJ=1,zJ=2,z2=-2,I9=-3,a4=-4,MJ=-5,cV=8,E9=1,pV=2,dV=3,nV=4,rV=5,iV=6,aV=7,oV=8,sV=9,tV=10,o1=11,q6=12,c4=13,eV=14,p4=15,q9=16,X9=17,V9=18,K9=19,i1=20,a1=21,Q9=22,Y9=23,J9=24,G9=25,Z9=26,d4=27,W9=28,H9=29,L0=30,o4=31,kJ=32,IJ=852,EJ=592,jJ=15,LJ=jJ;function U9(q){return(q>>>24&255)+(q>>>8&65280)+((q&65280)<<8)+((q&255)<<24)}function BJ(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Q2.Buf16(320),this.work=new Q2.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function j9(q){var X;if(!q||!q.state)return z2;if(X=q.state,q.total_in=q.total_out=X.total=0,q.msg="",X.wrap)q.adler=X.wrap&1;return X.mode=E9,X.last=0,X.havedict=0,X.dmax=32768,X.head=null,X.hold=0,X.bits=0,X.lencode=X.lendyn=new Q2.Buf32(IJ),X.distcode=X.distdyn=new Q2.Buf32(EJ),X.sane=1,X.back=-1,q5}function L9(q){var X;if(!q||!q.state)return z2;return X=q.state,X.wsize=0,X.whave=0,X.wnext=0,j9(q)}function B9(q,X){var V,K;if(!q||!q.state)return z2;if(K=q.state,X<0)V=0,X=-X;else if(V=(X>>4)+1,X<48)X&=15;if(X&&(X<8||X>15))return z2;if(K.window!==null&&K.wbits!==X)K.window=null;return K.wrap=V,K.wbits=X,L9(q)}function T9(q,X){var V,K;if(!q)return z2;if(K=new BJ,q.state=K,K.window=null,V=B9(q,X),V!==q5)q.state=null;return V}function TJ(q){return T9(q,LJ)}var z9=!0,n4,r4;function vJ(q){if(z9){var X;n4=new Q2.Buf32(512),r4=new Q2.Buf32(32),X=0;while(X<144)q.lens[X++]=8;while(X<256)q.lens[X++]=9;while(X<280)q.lens[X++]=7;while(X<288)q.lens[X++]=8;t8(M9,q.lens,0,288,n4,0,q.work,{bits:9}),X=0;while(X<32)q.lens[X++]=5;t8(k9,q.lens,0,32,r4,0,q.work,{bits:5}),z9=!1}q.lencode=n4,q.lenbits=9,q.distcode=r4,q.distbits=5}function v9(q,X,V,K){var Q,Y=q.state;if(Y.window===null)Y.wsize=1<=Y.wsize)Q2.arraySet(Y.window,X,V-Y.wsize,Y.wsize,0),Y.wnext=0,Y.whave=Y.wsize;else{if(Q=Y.wsize-Y.wnext,Q>K)Q=K;if(Q2.arraySet(Y.window,X,V-K,Q,Y.wnext),K-=Q,K)Q2.arraySet(Y.window,X,V-K,K,0),Y.wnext=K,Y.whave=Y.wsize;else{if(Y.wnext+=Q,Y.wnext===Y.wsize)Y.wnext=0;if(Y.whave>>8&255,V.check=l2(V.check,h,2,0),Z=0,H=0,V.mode=pV;break}if(V.flags=0,V.head)V.head.done=!1;if(!(V.wrap&1)||(((Z&255)<<8)+(Z>>8))%31){q.msg="incorrect header check",V.mode=L0;break}if((Z&15)!==cV){q.msg="unknown compression method",V.mode=L0;break}if(Z>>>=4,H-=4,$=(Z&15)+8,V.wbits===0)V.wbits=$;else if($>V.wbits){q.msg="invalid window size",V.mode=L0;break}V.dmax=1<<$,q.adler=V.check=1,V.mode=Z&512?tV:q6,Z=0,H=0;break;case pV:while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>8&1;if(V.flags&512)h[0]=Z&255,h[1]=Z>>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0,V.mode=dV;case dV:while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>8&255,h[2]=Z>>>16&255,h[3]=Z>>>24&255,V.check=l2(V.check,h,4,0);Z=0,H=0,V.mode=nV;case nV:while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>8;if(V.flags&512)h[0]=Z&255,h[1]=Z>>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0,V.mode=rV;case rV:if(V.flags&1024){while(H<16){if(G===0)break q;G--,Z+=K[Y++]<>>8&255,V.check=l2(V.check,h,2,0);Z=0,H=0}else if(V.head)V.head.extra=null;V.mode=iV;case iV:if(V.flags&1024){if(k=V.length,k>G)k=G;if(k){if(V.head){if($=V.head.extra_len-V.length,!V.head.extra)V.head.extra=Array(V.head.extra_len);Q2.arraySet(V.head.extra,K,Y,k,$)}if(V.flags&512)V.check=l2(V.check,K,k,Y);G-=k,Y+=k,V.length-=k}if(V.length)break q}V.length=0,V.mode=aV;case aV:if(V.flags&2048){if(G===0)break q;k=0;do if($=K[Y+k++],V.head&&$&&V.length<65536)V.head.name+=String.fromCharCode($);while($&&k>9&1,V.head.done=!0;q.adler=V.check=0,V.mode=q6;break;case tV:while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>=H&7,H-=H&7,V.mode=d4;break}while(H<3){if(G===0)break q;G--,Z+=K[Y++]<>>=1,H-=1,Z&3){case 0:V.mode=eV;break;case 1:if(vJ(V),V.mode=i1,X===r1){Z>>>=2,H-=2;break q}break;case 2:V.mode=X9;break;case 3:q.msg="invalid block type",V.mode=L0}Z>>>=2,H-=2;break;case eV:Z>>>=H&7,H-=H&7;while(H<32){if(G===0)break q;G--,Z+=K[Y++]<>>16^65535)){q.msg="invalid stored block lengths",V.mode=L0;break}if(V.length=Z&65535,Z=0,H=0,V.mode=p4,X===r1)break q;case p4:V.mode=q9;case q9:if(k=V.length,k){if(k>G)k=G;if(k>W)k=W;if(k===0)break q;Q2.arraySet(Q,K,Y,k,J),G-=k,Y+=k,W-=k,J+=k,V.length-=k;break}V.mode=q6;break;case X9:while(H<14){if(G===0)break q;G--,Z+=K[Y++]<>>=5,H-=5,V.ndist=(Z&31)+1,Z>>>=5,H-=5,V.ncode=(Z&15)+4,Z>>>=4,H-=4,V.nlen>286||V.ndist>30){q.msg="too many length or distance symbols",V.mode=L0;break}V.have=0,V.mode=V9;case V9:while(V.have>>=3,H-=3}while(V.have<19)V.lens[D[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,b={bits:V.lenbits},S=t8(WJ,V.lens,0,19,V.lencode,0,V.work,b),V.lenbits=b.bits,S){q.msg="invalid code lengths set",V.mode=L0;break}V.have=0,V.mode=K9;case K9:while(V.have>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=L,H-=L,V.lens[V.have++]=N;else{if(N===16){C=L+2;while(H>>=L,H-=L,V.have===0){q.msg="invalid bit length repeat",V.mode=L0;break}$=V.lens[V.have-1],k=3+(Z&3),Z>>>=2,H-=2}else if(N===17){C=L+3;while(H>>=L,H-=L,$=0,k=3+(Z&7),Z>>>=3,H-=3}else{C=L+7;while(H>>=L,H-=L,$=0,k=11+(Z&127),Z>>>=7,H-=7}if(V.have+k>V.nlen+V.ndist){q.msg="invalid bit length repeat",V.mode=L0;break}while(k--)V.lens[V.have++]=$}}if(V.mode===L0)break;if(V.lens[256]===0){q.msg="invalid code -- missing end-of-block",V.mode=L0;break}if(V.lenbits=9,b={bits:V.lenbits},S=t8(M9,V.lens,0,V.nlen,V.lencode,0,V.work,b),V.lenbits=b.bits,S){q.msg="invalid literal/lengths set",V.mode=L0;break}if(V.distbits=6,V.distcode=V.distdyn,b={bits:V.distbits},S=t8(k9,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,b),V.distbits=b.bits,S){q.msg="invalid distances set",V.mode=L0;break}if(V.mode=i1,X===r1)break q;case i1:V.mode=a1;case a1:if(G>=6&&W>=258){if(q.next_out=J,q.avail_out=W,q.next_in=Y,q.avail_in=G,V.hold=Z,V.bits=H,ZJ(q,z),J=q.next_out,Q=q.output,W=q.avail_out,Y=q.next_in,K=q.input,G=q.avail_in,Z=V.hold,H=V.bits,V.mode===q6)V.back=-1;break}V.back=0;for(;;){if(B=V.lencode[Z&(1<>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>R)],L=B>>>24,O=B>>>16&255,N=B&65535,R+L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=R,H-=R,V.back+=R}if(Z>>>=L,H-=L,V.back+=L,V.length=N,O===0){V.mode=Z9;break}if(O&32){V.back=-1,V.mode=q6;break}if(O&64){q.msg="invalid literal/length code",V.mode=L0;break}V.extra=O&15,V.mode=Q9;case Q9:if(V.extra){C=V.extra;while(H>>=V.extra,H-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=Y9;case Y9:for(;;){if(B=V.distcode[Z&(1<>>24,O=B>>>16&255,N=B&65535,L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>R)],L=B>>>24,O=B>>>16&255,N=B&65535,R+L<=H)break;if(G===0)break q;G--,Z+=K[Y++]<>>=R,H-=R,V.back+=R}if(Z>>>=L,H-=L,V.back+=L,O&64){q.msg="invalid distance code",V.mode=L0;break}V.offset=N,V.extra=O&15,V.mode=J9;case J9:if(V.extra){C=V.extra;while(H>>=V.extra,H-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){q.msg="invalid distance too far back",V.mode=L0;break}V.mode=G9;case G9:if(W===0)break q;if(k=z-W,V.offset>k){if(k=V.offset-k,k>V.whave){if(V.sane){q.msg="invalid distance too far back",V.mode=L0;break}}if(k>V.wnext)k-=V.wnext,M=V.wsize-k;else M=V.wnext-k;if(k>V.length)k=V.length;j=V.window}else j=Q,M=J-V.offset,k=V.length;if(k>W)k=W;W-=k,V.length-=k;do Q[J++]=j[M++];while(--k);if(V.length===0)V.mode=a1;break;case Z9:if(W===0)break q;Q[J++]=V.length,W--,V.mode=a1;break;case d4:if(V.wrap){while(H<32){if(G===0)break q;G--,Z|=K[Y++]<{O9.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var A9=g0((WW,w9)=>{function NJ(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}w9.exports=NJ});var S9=g0((q1)=>{var c5=R9(),e8=t2(),s1=g4(),N0=s4(),t4=b1(),SJ=x4(),yJ=A9(),N9=Object.prototype.toString;function X5(q){if(!(this instanceof X5))return new X5(q);this.options=e8.assign({chunkSize:16384,windowBits:0,to:""},q||{});var X=this.options;if(X.raw&&X.windowBits>=0&&X.windowBits<16){if(X.windowBits=-X.windowBits,X.windowBits===0)X.windowBits=-15}if(X.windowBits>=0&&X.windowBits<16&&!(q&&q.windowBits))X.windowBits+=32;if(X.windowBits>15&&X.windowBits<48){if((X.windowBits&15)===0)X.windowBits|=15}this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new SJ,this.strm.avail_out=0;var V=c5.inflateInit2(this.strm,X.windowBits);if(V!==N0.Z_OK)throw Error(t4[V]);if(this.header=new yJ,c5.inflateGetHeader(this.strm,this.header),X.dictionary){if(typeof X.dictionary==="string")X.dictionary=s1.string2buf(X.dictionary);else if(N9.call(X.dictionary)==="[object ArrayBuffer]")X.dictionary=new Uint8Array(X.dictionary);if(X.raw){if(V=c5.inflateSetDictionary(this.strm,X.dictionary),V!==N0.Z_OK)throw Error(t4[V])}}}X5.prototype.push=function(q,X){var V=this.strm,K=this.options.chunkSize,Q=this.options.dictionary,Y,J,G,W,Z,H=!1;if(this.ended)return!1;if(J=X===~~X?X:X===!0?N0.Z_FINISH:N0.Z_NO_FLUSH,typeof q==="string")V.input=s1.binstring2buf(q);else if(N9.call(q)==="[object ArrayBuffer]")V.input=new Uint8Array(q);else V.input=q;V.next_in=0,V.avail_in=V.input.length;do{if(V.avail_out===0)V.output=new e8.Buf8(K),V.next_out=0,V.avail_out=K;if(Y=c5.inflate(V,N0.Z_NO_FLUSH),Y===N0.Z_NEED_DICT&&Q)Y=c5.inflateSetDictionary(this.strm,Q);if(Y===N0.Z_BUF_ERROR&&H===!0)Y=N0.Z_OK,H=!1;if(Y!==N0.Z_STREAM_END&&Y!==N0.Z_OK)return this.onEnd(Y),this.ended=!0,!1;if(V.next_out){if(V.avail_out===0||Y===N0.Z_STREAM_END||V.avail_in===0&&(J===N0.Z_FINISH||J===N0.Z_SYNC_FLUSH))if(this.options.to==="string"){if(G=s1.utf8border(V.output,V.next_out),W=V.next_out-G,Z=s1.buf2string(V.output,G),V.next_out=W,V.avail_out=K-W,W)e8.arraySet(V.output,V.output,G,W,0);this.onData(Z)}else this.onData(e8.shrinkBuf(V.output,V.next_out))}if(V.avail_in===0&&V.avail_out===0)H=!0}while((V.avail_in>0||V.avail_out===0)&&Y!==N0.Z_STREAM_END);if(Y===N0.Z_STREAM_END)J=N0.Z_FINISH;if(J===N0.Z_FINISH)return Y=c5.inflateEnd(this.strm),this.onEnd(Y),this.ended=!0,Y===N0.Z_OK;if(J===N0.Z_SYNC_FLUSH)return this.onEnd(N0.Z_OK),V.avail_out=0,!0;return!0};X5.prototype.onData=function(q){this.chunks.push(q)};X5.prototype.onEnd=function(q){if(q===N0.Z_OK)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=e8.flattenChunks(this.chunks);this.chunks=[],this.err=q,this.msg=this.strm.msg};function e4(q,X){var V=new X5(X);if(V.push(q,!0),V.err)throw V.msg||t4[V.err];return V.result}function $J(q,X){return X=X||{},X.raw=!0,e4(q,X)}q1.Inflate=X5;q1.inflate=e4;q1.inflateRaw=$J;q1.ungzip=e4});var X1=g0((UW,$9)=>{var CJ=t2().assign,hJ=FV(),FJ=S9(),PJ=s4(),y9={};CJ(y9,hJ,FJ,PJ);$9.exports=y9});var zX=globalThis;if(typeof zX.global>"u")zX.global=globalThis;var C2=[],W2=[],lq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(c6=0,MX=lq.length;c60)throw Error("Invalid string. Length must be a multiple of 4");var V=q.indexOf("=");if(V===-1)V=X;var K=V===X?0:4-V%4;return[V,K]}function VQ(q,X){return(q+X)*3/4-X}function KQ(q){var X,V=XQ(q),K=V[0],Q=V[1],Y=new Uint8Array(VQ(K,Q)),J=0,G=Q>0?K-4:K,W;for(W=0;W>16&255,Y[J++]=X>>8&255,Y[J++]=X&255;if(Q===2)X=W2[q.charCodeAt(W)]<<2|W2[q.charCodeAt(W+1)]>>4,Y[J++]=X&255;if(Q===1)X=W2[q.charCodeAt(W)]<<10|W2[q.charCodeAt(W+1)]<<4|W2[q.charCodeAt(W+2)]>>2,Y[J++]=X>>8&255,Y[J++]=X&255;return Y}function QQ(q){return C2[q>>18&63]+C2[q>>12&63]+C2[q>>6&63]+C2[q&63]}function YQ(q,X,V){var K,Q=[];for(var Y=X;YG?G:J+Y));if(K===1)X=q[V-1],Q.push(C2[X>>2]+C2[X<<4&63]+"==");else if(K===2)X=(q[V-2]<<8)+q[V-1],Q.push(C2[X>>10]+C2[X>>4&63]+C2[X<<2&63]+"=");return Q.join("")}function $1(q,X,V,K,Q){var Y,J,G=Q*8-K-1,W=(1<>1,H=-7,U=V?Q-1:0,z=V?-1:1,k=q[X+U];U+=z,Y=k&(1<<-H)-1,k>>=-H,H+=G;for(;H>0;Y=Y*256+q[X+U],U+=z,H-=8);J=Y&(1<<-H)-1,Y>>=-H,H+=K;for(;H>0;J=J*256+q[X+U],U+=z,H-=8);if(Y===0)Y=1-Z;else if(Y===W)return J?NaN:(k?-1:1)*(1/0);else J=J+Math.pow(2,K),Y=Y-Z;return(k?-1:1)*J*Math.pow(2,Y-K)}function BX(q,X,V,K,Q,Y){var J,G,W,Z=Y*8-Q-1,H=(1<>1,z=Q===23?Math.pow(2,-24)-Math.pow(2,-77):0,k=K?0:Y-1,M=K?1:-1,j=X<0||X===0&&1/X<0?1:0;if(X=Math.abs(X),isNaN(X)||X===1/0)G=isNaN(X)?1:0,J=H;else{if(J=Math.floor(Math.log(X)/Math.LN2),X*(W=Math.pow(2,-J))<1)J--,W*=2;if(J+U>=1)X+=z/W;else X+=z*Math.pow(2,1-U);if(X*W>=2)J++,W/=2;if(J+U>=H)G=0,J=H;else if(J+U>=1)G=(X*W-1)*Math.pow(2,Q),J=J+U;else G=X*Math.pow(2,U-1)*Math.pow(2,Q),J=0}for(;Q>=8;q[V+k]=G&255,k+=M,G/=256,Q-=8);J=J<0;q[V+k]=J&255,k+=M,J/=256,Z-=8);q[V+k-M]|=j*128}var IX=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null,JQ=50,_q=2147483647;var{btoa:$3,atob:C3,File:h3,Blob:F3}=globalThis;function a2(q){if(q>_q)throw RangeError('The value "'+q+'" is invalid for option "size"');let X=new Uint8Array(q);return Object.setPrototypeOf(X,y.prototype),X}function rq(q,X,V){return class extends V{constructor(){super();Object.defineProperty(this,"message",{value:X.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${q}]`,this.stack,delete this.name}get code(){return q}set code(K){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:K,writable:!0})}toString(){return`${this.name} [${q}]: ${this.message}`}}}var GQ=rq("ERR_BUFFER_OUT_OF_BOUNDS",function(q){if(q)return`${q} is outside of buffer bounds`;return"Attempt to access memory outside buffer bounds"},RangeError),ZQ=rq("ERR_INVALID_ARG_TYPE",function(q,X){return`The "${q}" argument must be of type number. Received type ${typeof X}`},TypeError),cq=rq("ERR_OUT_OF_RANGE",function(q,X,V){let K=`The value of "${q}" is out of range.`,Q=V;if(Number.isInteger(V)&&Math.abs(V)>4294967296)Q=LX(String(V));else if(typeof V==="bigint"){if(Q=String(V),V>BigInt(2)**BigInt(32)||V<-(BigInt(2)**BigInt(32)))Q=LX(Q);Q+="n"}return K+=` It must be ${X}. Received ${Q}`,K},RangeError);function y(q,X,V){if(typeof q==="number"){if(typeof X==="string")throw TypeError('The "string" argument must be of type string. Received type number');return iq(q)}return TX(q,X,V)}Object.defineProperty(y.prototype,"parent",{enumerable:!0,get:function(){if(!y.isBuffer(this))return;return this.buffer}});Object.defineProperty(y.prototype,"offset",{enumerable:!0,get:function(){if(!y.isBuffer(this))return;return this.byteOffset}});y.poolSize=8192;function TX(q,X,V){if(typeof q==="string")return HQ(q,X);if(ArrayBuffer.isView(q))return UQ(q);if(q==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof q);if(h2(q,ArrayBuffer)||q&&h2(q.buffer,ArrayBuffer))return dq(q,X,V);if(typeof SharedArrayBuffer<"u"&&(h2(q,SharedArrayBuffer)||q&&h2(q.buffer,SharedArrayBuffer)))return dq(q,X,V);if(typeof q==="number")throw TypeError('The "value" argument must not be of type number. Received type number');let K=q.valueOf&&q.valueOf();if(K!=null&&K!==q)return y.from(K,X,V);let Q=zQ(q);if(Q)return Q;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof q[Symbol.toPrimitive]==="function")return y.from(q[Symbol.toPrimitive]("string"),X,V);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof q)}y.from=function(q,X,V){return TX(q,X,V)};Object.setPrototypeOf(y.prototype,Uint8Array.prototype);Object.setPrototypeOf(y,Uint8Array);function vX(q){if(typeof q!=="number")throw TypeError('"size" argument must be of type number');else if(q<0)throw RangeError('The value "'+q+'" is invalid for option "size"')}function WQ(q,X,V){if(vX(q),q<=0)return a2(q);if(X!==void 0)return typeof V==="string"?a2(q).fill(X,V):a2(q).fill(X);return a2(q)}y.alloc=function(q,X,V){return WQ(q,X,V)};function iq(q){return vX(q),a2(q<0?0:aq(q)|0)}y.allocUnsafe=function(q){return iq(q)};y.allocUnsafeSlow=function(q){return iq(q)};function HQ(q,X){if(typeof X!=="string"||X==="")X="utf8";if(!y.isEncoding(X))throw TypeError("Unknown encoding: "+X);let V=RX(q,X)|0,K=a2(V),Q=K.write(q,X);if(Q!==V)K=K.slice(0,Q);return K}function pq(q){let X=q.length<0?0:aq(q.length)|0,V=a2(X);for(let K=0;K=_q)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_q.toString(16)+" bytes");return q|0}y.isBuffer=function(q){return q!=null&&q._isBuffer===!0&&q!==y.prototype};y.compare=function(q,X){if(h2(q,Uint8Array))q=y.from(q,q.offset,q.byteLength);if(h2(X,Uint8Array))X=y.from(X,X.offset,X.byteLength);if(!y.isBuffer(q)||!y.isBuffer(X))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(q===X)return 0;let V=q.length,K=X.length;for(let Q=0,Y=Math.min(V,K);QK.length){if(!y.isBuffer(Y))Y=y.from(Y);Y.copy(K,Q)}else Uint8Array.prototype.set.call(K,Y,Q);else if(!y.isBuffer(Y))throw TypeError('"list" argument must be an Array of Buffers');else Y.copy(K,Q);Q+=Y.length}return K};function RX(q,X){if(y.isBuffer(q))return q.length;if(ArrayBuffer.isView(q)||h2(q,ArrayBuffer))return q.byteLength;if(typeof q!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof q);let V=q.length,K=arguments.length>2&&arguments[2]===!0;if(!K&&V===0)return 0;let Q=!1;for(;;)switch(X){case"ascii":case"latin1":case"binary":return V;case"utf8":case"utf-8":return nq(q).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V*2;case"hex":return V>>>1;case"base64":return hX(q).length;default:if(Q)return K?-1:nq(q).length;X=(""+X).toLowerCase(),Q=!0}}y.byteLength=RX;function MQ(q,X,V){let K=!1;if(X===void 0||X<0)X=0;if(X>this.length)return"";if(V===void 0||V>this.length)V=this.length;if(V<=0)return"";if(V>>>=0,X>>>=0,V<=X)return"";if(!q)q="utf8";while(!0)switch(q){case"hex":return OQ(this,X,V);case"utf8":case"utf-8":return wX(this,X,V);case"ascii":return vQ(this,X,V);case"latin1":case"binary":return RQ(this,X,V);case"base64":return BQ(this,X,V);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return wQ(this,X,V);default:if(K)throw TypeError("Unknown encoding: "+q);q=(q+"").toLowerCase(),K=!0}}y.prototype._isBuffer=!0;function p6(q,X,V){let K=q[X];q[X]=q[V],q[V]=K}y.prototype.swap16=function(){let q=this.length;if(q%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let X=0;XX)q+=" ... ";return""};if(IX)y.prototype[IX]=y.prototype.inspect;y.prototype.compare=function(q,X,V,K,Q){if(h2(q,Uint8Array))q=y.from(q,q.offset,q.byteLength);if(!y.isBuffer(q))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof q);if(X===void 0)X=0;if(V===void 0)V=q?q.length:0;if(K===void 0)K=0;if(Q===void 0)Q=this.length;if(X<0||V>q.length||K<0||Q>this.length)throw RangeError("out of range index");if(K>=Q&&X>=V)return 0;if(K>=Q)return-1;if(X>=V)return 1;if(X>>>=0,V>>>=0,K>>>=0,Q>>>=0,this===q)return 0;let Y=Q-K,J=V-X,G=Math.min(Y,J),W=this.slice(K,Q),Z=q.slice(X,V);for(let H=0;H2147483647)V=2147483647;else if(V<-2147483648)V=-2147483648;if(V=+V,Number.isNaN(V))V=Q?0:q.length-1;if(V<0)V=q.length+V;if(V>=q.length)if(Q)return-1;else V=q.length-1;else if(V<0)if(Q)V=0;else return-1;if(typeof X==="string")X=y.from(X,K);if(y.isBuffer(X)){if(X.length===0)return-1;return EX(q,X,V,K,Q)}else if(typeof X==="number"){if(X=X&255,typeof Uint8Array.prototype.indexOf==="function")if(Q)return Uint8Array.prototype.indexOf.call(q,X,V);else return Uint8Array.prototype.lastIndexOf.call(q,X,V);return EX(q,[X],V,K,Q)}throw TypeError("val must be string, number or Buffer")}function EX(q,X,V,K,Q){let Y=1,J=q.length,G=X.length;if(K!==void 0){if(K=String(K).toLowerCase(),K==="ucs2"||K==="ucs-2"||K==="utf16le"||K==="utf-16le"){if(q.length<2||X.length<2)return-1;Y=2,J/=2,G/=2,V/=2}}function W(H,U){if(Y===1)return H[U];else return H.readUInt16BE(U*Y)}let Z;if(Q){let H=-1;for(Z=V;ZJ)V=J-G;for(Z=V;Z>=0;Z--){let H=!0;for(let U=0;UQ)K=Q;let Y=X.length;if(K>Y/2)K=Y/2;let J;for(J=0;J>>0,isFinite(V)){if(V=V>>>0,K===void 0)K="utf8"}else K=V,V=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let Q=this.length-X;if(V===void 0||V>Q)V=Q;if(q.length>0&&(V<0||X<0)||X>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!K)K="utf8";let Y=!1;for(;;)switch(K){case"hex":return kQ(this,q,X,V);case"utf8":case"utf-8":return IQ(this,q,X,V);case"ascii":case"latin1":case"binary":return EQ(this,q,X,V);case"base64":return jQ(this,q,X,V);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return LQ(this,q,X,V);default:if(Y)throw TypeError("Unknown encoding: "+K);K=(""+K).toLowerCase(),Y=!0}};y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function BQ(q,X,V){if(X===0&&V===q.length)return kX(q);else return kX(q.slice(X,V))}function wX(q,X,V){V=Math.min(q.length,V);let K=[],Q=X;while(Q239?4:Y>223?3:Y>191?2:1;if(Q+G<=V){let W,Z,H,U;switch(G){case 1:if(Y<128)J=Y;break;case 2:if(W=q[Q+1],(W&192)===128){if(U=(Y&31)<<6|W&63,U>127)J=U}break;case 3:if(W=q[Q+1],Z=q[Q+2],(W&192)===128&&(Z&192)===128){if(U=(Y&15)<<12|(W&63)<<6|Z&63,U>2047&&(U<55296||U>57343))J=U}break;case 4:if(W=q[Q+1],Z=q[Q+2],H=q[Q+3],(W&192)===128&&(Z&192)===128&&(H&192)===128){if(U=(Y&15)<<18|(W&63)<<12|(Z&63)<<6|H&63,U>65535&&U<1114112)J=U}}}if(J===null)J=65533,G=1;else if(J>65535)J-=65536,K.push(J>>>10&1023|55296),J=56320|J&1023;K.push(J),Q+=G}return TQ(K)}var jX=4096;function TQ(q){let X=q.length;if(X<=jX)return String.fromCharCode.apply(String,q);let V="",K=0;while(KK)V=K;let Q="";for(let Y=X;YV)q=V;if(X<0){if(X+=V,X<0)X=0}else if(X>V)X=V;if(XV)throw RangeError("Trying to access beyond buffer length")}y.prototype.readUintLE=y.prototype.readUIntLE=function(q,X,V){if(q=q>>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q],Q=1,Y=0;while(++Y>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q+--X],Q=1;while(X>0&&(Q*=256))K+=this[q+--X]*Q;return K};y.prototype.readUint8=y.prototype.readUInt8=function(q,X){if(q=q>>>0,!X)D0(q,1,this.length);return this[q]};y.prototype.readUint16LE=y.prototype.readUInt16LE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);return this[q]|this[q+1]<<8};y.prototype.readUint16BE=y.prototype.readUInt16BE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);return this[q]<<8|this[q+1]};y.prototype.readUint32LE=y.prototype.readUInt32LE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return(this[q]|this[q+1]<<8|this[q+2]<<16)+this[q+3]*16777216};y.prototype.readUint32BE=y.prototype.readUInt32BE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]*16777216+(this[q+1]<<16|this[q+2]<<8|this[q+3])};y.prototype.readBigUInt64LE=M6(function(q){q=q>>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=X+this[++q]*256+this[++q]*65536+this[++q]*16777216,Q=this[++q]+this[++q]*256+this[++q]*65536+V*16777216;return BigInt(K)+(BigInt(Q)<>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=X*16777216+this[++q]*65536+this[++q]*256+this[++q],Q=this[++q]*16777216+this[++q]*65536+this[++q]*256+V;return(BigInt(K)<>>0,X=X>>>0,!V)D0(q,X,this.length);let K=this[q],Q=1,Y=0;while(++Y=Q)K-=Math.pow(2,8*X);return K};y.prototype.readIntBE=function(q,X,V){if(q=q>>>0,X=X>>>0,!V)D0(q,X,this.length);let K=X,Q=1,Y=this[q+--K];while(K>0&&(Q*=256))Y+=this[q+--K]*Q;if(Q*=128,Y>=Q)Y-=Math.pow(2,8*X);return Y};y.prototype.readInt8=function(q,X){if(q=q>>>0,!X)D0(q,1,this.length);if(!(this[q]&128))return this[q];return(255-this[q]+1)*-1};y.prototype.readInt16LE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);let V=this[q]|this[q+1]<<8;return V&32768?V|4294901760:V};y.prototype.readInt16BE=function(q,X){if(q=q>>>0,!X)D0(q,2,this.length);let V=this[q+1]|this[q]<<8;return V&32768?V|4294901760:V};y.prototype.readInt32LE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]|this[q+1]<<8|this[q+2]<<16|this[q+3]<<24};y.prototype.readInt32BE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return this[q]<<24|this[q+1]<<16|this[q+2]<<8|this[q+3]};y.prototype.readBigInt64LE=M6(function(q){q=q>>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=this[q+4]+this[q+5]*256+this[q+6]*65536+(V<<24);return(BigInt(K)<>>0,y5(q,"offset");let X=this[q],V=this[q+7];if(X===void 0||V===void 0)C8(q,this.length-8);let K=(X<<24)+this[++q]*65536+this[++q]*256+this[++q];return(BigInt(K)<>>0,!X)D0(q,4,this.length);return $1(this,q,!0,23,4)};y.prototype.readFloatBE=function(q,X){if(q=q>>>0,!X)D0(q,4,this.length);return $1(this,q,!1,23,4)};y.prototype.readDoubleLE=function(q,X){if(q=q>>>0,!X)D0(q,8,this.length);return $1(this,q,!0,52,8)};y.prototype.readDoubleBE=function(q,X){if(q=q>>>0,!X)D0(q,8,this.length);return $1(this,q,!1,52,8)};function s0(q,X,V,K,Q,Y){if(!y.isBuffer(q))throw TypeError('"buffer" argument must be a Buffer instance');if(X>Q||Xq.length)throw RangeError("Index out of range")}y.prototype.writeUintLE=y.prototype.writeUIntLE=function(q,X,V,K){if(q=+q,X=X>>>0,V=V>>>0,!K){let J=Math.pow(2,8*V)-1;s0(this,q,X,V,J,0)}let Q=1,Y=0;this[X]=q&255;while(++Y>>0,V=V>>>0,!K){let J=Math.pow(2,8*V)-1;s0(this,q,X,V,J,0)}let Q=V-1,Y=1;this[X+Q]=q&255;while(--Q>=0&&(Y*=256))this[X+Q]=q/Y&255;return X+V};y.prototype.writeUint8=y.prototype.writeUInt8=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,1,255,0);return this[X]=q&255,X+1};y.prototype.writeUint16LE=y.prototype.writeUInt16LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,65535,0);return this[X]=q&255,this[X+1]=q>>>8,X+2};y.prototype.writeUint16BE=y.prototype.writeUInt16BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,65535,0);return this[X]=q>>>8,this[X+1]=q&255,X+2};y.prototype.writeUint32LE=y.prototype.writeUInt32LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,4294967295,0);return this[X+3]=q>>>24,this[X+2]=q>>>16,this[X+1]=q>>>8,this[X]=q&255,X+4};y.prototype.writeUint32BE=y.prototype.writeUInt32BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,4294967295,0);return this[X]=q>>>24,this[X+1]=q>>>16,this[X+2]=q>>>8,this[X+3]=q&255,X+4};function AX(q,X,V,K,Q){CX(X,K,Q,q,V,7);let Y=Number(X&BigInt(4294967295));q[V++]=Y,Y=Y>>8,q[V++]=Y,Y=Y>>8,q[V++]=Y,Y=Y>>8,q[V++]=Y;let J=Number(X>>BigInt(32)&BigInt(4294967295));return q[V++]=J,J=J>>8,q[V++]=J,J=J>>8,q[V++]=J,J=J>>8,q[V++]=J,V}function NX(q,X,V,K,Q){CX(X,K,Q,q,V,7);let Y=Number(X&BigInt(4294967295));q[V+7]=Y,Y=Y>>8,q[V+6]=Y,Y=Y>>8,q[V+5]=Y,Y=Y>>8,q[V+4]=Y;let J=Number(X>>BigInt(32)&BigInt(4294967295));return q[V+3]=J,J=J>>8,q[V+2]=J,J=J>>8,q[V+1]=J,J=J>>8,q[V]=J,V+8}y.prototype.writeBigUInt64LE=M6(function(q,X=0){return AX(this,q,X,BigInt(0),BigInt("0xffffffffffffffff"))});y.prototype.writeBigUInt64BE=M6(function(q,X=0){return NX(this,q,X,BigInt(0),BigInt("0xffffffffffffffff"))});y.prototype.writeIntLE=function(q,X,V,K){if(q=+q,X=X>>>0,!K){let G=Math.pow(2,8*V-1);s0(this,q,X,V,G-1,-G)}let Q=0,Y=1,J=0;this[X]=q&255;while(++Q>0)-J&255}return X+V};y.prototype.writeIntBE=function(q,X,V,K){if(q=+q,X=X>>>0,!K){let G=Math.pow(2,8*V-1);s0(this,q,X,V,G-1,-G)}let Q=V-1,Y=1,J=0;this[X+Q]=q&255;while(--Q>=0&&(Y*=256)){if(q<0&&J===0&&this[X+Q+1]!==0)J=1;this[X+Q]=(q/Y>>0)-J&255}return X+V};y.prototype.writeInt8=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,1,127,-128);if(q<0)q=255+q+1;return this[X]=q&255,X+1};y.prototype.writeInt16LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,32767,-32768);return this[X]=q&255,this[X+1]=q>>>8,X+2};y.prototype.writeInt16BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,2,32767,-32768);return this[X]=q>>>8,this[X+1]=q&255,X+2};y.prototype.writeInt32LE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,2147483647,-2147483648);return this[X]=q&255,this[X+1]=q>>>8,this[X+2]=q>>>16,this[X+3]=q>>>24,X+4};y.prototype.writeInt32BE=function(q,X,V){if(q=+q,X=X>>>0,!V)s0(this,q,X,4,2147483647,-2147483648);if(q<0)q=4294967295+q+1;return this[X]=q>>>24,this[X+1]=q>>>16,this[X+2]=q>>>8,this[X+3]=q&255,X+4};y.prototype.writeBigInt64LE=M6(function(q,X=0){return AX(this,q,X,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});y.prototype.writeBigInt64BE=M6(function(q,X=0){return NX(this,q,X,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function SX(q,X,V,K,Q,Y){if(V+K>q.length)throw RangeError("Index out of range");if(V<0)throw RangeError("Index out of range")}function yX(q,X,V,K,Q){if(X=+X,V=V>>>0,!Q)SX(q,X,V,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return BX(q,X,V,K,23,4),V+4}y.prototype.writeFloatLE=function(q,X,V){return yX(this,q,X,!0,V)};y.prototype.writeFloatBE=function(q,X,V){return yX(this,q,X,!1,V)};function $X(q,X,V,K,Q){if(X=+X,V=V>>>0,!Q)SX(q,X,V,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return BX(q,X,V,K,52,8),V+8}y.prototype.writeDoubleLE=function(q,X,V){return $X(this,q,X,!0,V)};y.prototype.writeDoubleBE=function(q,X,V){return $X(this,q,X,!1,V)};y.prototype.copy=function(q,X,V,K){if(!y.isBuffer(q))throw TypeError("argument should be a Buffer");if(!V)V=0;if(!K&&K!==0)K=this.length;if(X>=q.length)X=q.length;if(!X)X=0;if(K>0&&K=this.length)throw RangeError("Index out of range");if(K<0)throw RangeError("sourceEnd out of bounds");if(K>this.length)K=this.length;if(q.length-X>>0,V=V===void 0?this.length:V>>>0,!q)q=0;let Q;if(typeof q==="number")for(Q=X;Q=K+4;V-=3)X=`_${q.slice(V-3,V)}${X}`;return`${q.slice(0,V)}${X}`}function AQ(q,X,V){if(y5(X,"offset"),q[X]===void 0||q[X+V]===void 0)C8(X,q.length-(V+1))}function CX(q,X,V,K,Q,Y){if(q>V||q3)if(X===0||X===BigInt(0))G=`>= 0${J} and < 2${J} ** ${(Y+1)*8}${J}`;else G=`>= -(2${J} ** ${(Y+1)*8-1}${J}) and < 2 ** ${(Y+1)*8-1}${J}`;else G=`>= ${X}${J} and <= ${V}${J}`;throw new cq("value",G,q)}AQ(K,Q,Y)}function y5(q,X){if(typeof q!=="number")throw new ZQ(X,"number",q)}function C8(q,X,V){if(Math.floor(q)!==q)throw y5(q,V),new cq(V||"offset","an integer",q);if(X<0)throw new GQ;throw new cq(V||"offset",`>= ${V?1:0} and <= ${X}`,q)}var NQ=/[^+/0-9A-Za-z-_]/g;function SQ(q){if(q=q.split("=")[0],q=q.trim().replace(NQ,""),q.length<2)return"";while(q.length%4!==0)q=q+"=";return q}function nq(q,X){X=X||1/0;let V,K=q.length,Q=null,Y=[];for(let J=0;J55295&&V<57344){if(!Q){if(V>56319){if((X-=3)>-1)Y.push(239,191,189);continue}else if(J+1===K){if((X-=3)>-1)Y.push(239,191,189);continue}Q=V;continue}if(V<56320){if((X-=3)>-1)Y.push(239,191,189);Q=V;continue}V=(Q-55296<<10|V-56320)+65536}else if(Q){if((X-=3)>-1)Y.push(239,191,189)}if(Q=null,V<128){if((X-=1)<0)break;Y.push(V)}else if(V<2048){if((X-=2)<0)break;Y.push(V>>6|192,V&63|128)}else if(V<65536){if((X-=3)<0)break;Y.push(V>>12|224,V>>6&63|128,V&63|128)}else if(V<1114112){if((X-=4)<0)break;Y.push(V>>18|240,V>>12&63|128,V>>6&63|128,V&63|128)}else throw Error("Invalid code point")}return Y}function yQ(q){let X=[];for(let V=0;V>8,Q=V%256,Y.push(Q),Y.push(K)}return Y}function hX(q){return KQ(SQ(q))}function C1(q,X,V,K){let Q;for(Q=0;Q=X.length||Q>=q.length)break;X[Q+V]=q[Q]}return Q}function h2(q,X){return q instanceof X||q!=null&&q.constructor!=null&&q.constructor.name!=null&&q.constructor.name===X.name}var CQ=function(){let q=Array(256);for(let X=0;X<16;++X){let V=X*16;for(let K=0;K<16;++K)q[V+K]="0123456789abcdef"[X]+"0123456789abcdef"[K]}return q}();function M6(q){return typeof BigInt>"u"?hQ:q}function hQ(){throw Error("BigInt not supported")}function oq(q){return()=>{throw Error(q+" is not implemented for node:buffer browser polyfill")}}var P3=oq("resolveObjectURL"),D3=oq("isUtf8");var u3=oq("transcode");var N3=$8(gX(),1);var UX={};qQ(UX,{waitForTick:()=>R2,values:()=>d5,utf8Encode:()=>mQ,utf16Encode:()=>E4,utf16Decode:()=>x8,typedArrayFor:()=>D8,translate:()=>c0,toUint8Array:()=>r6,toRadians:()=>O0,toHexStringOfMinLength:()=>D2,toHexString:()=>u2,toDegrees:()=>k1,toCodePoint:()=>K4,toCharCode:()=>s,sum:()=>z4,stroke:()=>B5,square:()=>lZ,sortedUniq:()=>U4,skewRadians:()=>k8,skewDegrees:()=>bZ,sizeInBytes:()=>P5,singleQuote:()=>t9,showText:()=>L1,setWordSpacing:()=>pZ,setTextRise:()=>nZ,setTextRenderingMode:()=>rZ,setTextMatrix:()=>FK,setStrokingRgbColor:()=>g7,setStrokingGrayscaleColor:()=>D7,setStrokingColor:()=>v5,setStrokingCmykColor:()=>b7,setLineWidth:()=>L5,setLineJoin:()=>fZ,setLineHeight:()=>F7,setLineCap:()=>I8,setGraphicsState:()=>i2,setFontAndSize:()=>T5,setFillingRgbColor:()=>u7,setFillingGrayscaleColor:()=>P7,setFillingColor:()=>E2,setFillingCmykColor:()=>x7,setDashPattern:()=>j5,setCharacterSqueeze:()=>dZ,setCharacterSpacing:()=>cZ,scale:()=>g6,rotateRectangle:()=>y7,rotateRadians:()=>x6,rotateInPlace:()=>j2,rotateDegrees:()=>M8,rotateAndSkewTextRadiansAndTranslate:()=>j8,rotateAndSkewTextDegreesAndTranslate:()=>iZ,rgb:()=>Y0,reverseArray:()=>I6,restoreDashPattern:()=>mZ,reduceRotation:()=>I2,rectanglesAreEqual:()=>n5,rectangle:()=>hK,range:()=>M4,radiansToDegrees:()=>CK,radians:()=>gZ,pushGraphicsState:()=>B0,popGraphicsState:()=>T0,pluckIndices:()=>k4,pdfDocEncodingDecode:()=>J1,parseDate:()=>P8,padStart:()=>e0,numberToString:()=>B4,normalizeAppearance:()=>G2,nextLine:()=>h7,newlineChars:()=>gQ,moveTo:()=>J2,moveText:()=>_Z,mergeUint8Arrays:()=>W4,mergeLines:()=>F1,mergeIntoTypedArray:()=>Z4,lowSurrogate:()=>u1,lineTo:()=>S0,lineSplit:()=>F8,layoutSinglelineText:()=>v8,layoutMultilineText:()=>uq,layoutCombedText:()=>KX,last:()=>n6,isWithinBMP:()=>j4,isType:()=>XK,isStandardFont:()=>e1,isNewlineChar:()=>Y4,highSurrogate:()=>D1,hasUtf16BOM:()=>b8,hasSurrogates:()=>L4,grayscale:()=>Sq,getType:()=>qK,findLastMatch:()=>F5,fillAndStroke:()=>j1,fill:()=>E1,escapedNewlineChars:()=>mX,escapeRegExp:()=>bX,error:()=>L6,endText:()=>T1,endPath:()=>wq,endMarkedContent:()=>Nq,encodeToBase64:()=>X4,drawTextLines:()=>Fq,drawTextField:()=>Pq,drawText:()=>eZ,drawSvgPath:()=>d7,drawRectangle:()=>b6,drawRadioButton:()=>T8,drawPage:()=>c7,drawOptionList:()=>n7,drawObject:()=>L8,drawLinesOfText:()=>_7,drawLine:()=>p7,drawImage:()=>w1,drawEllipsePath:()=>xK,drawEllipse:()=>O1,drawCheckMark:()=>bK,drawCheckBox:()=>B8,drawButton:()=>hq,degreesToRadians:()=>H6,degrees:()=>p,defaultTextFieldAppearanceProvider:()=>GX,defaultRadioGroupAppearanceProvider:()=>YX,defaultOptionListAppearanceProvider:()=>WX,defaultDropdownAppearanceProvider:()=>ZX,defaultCheckBoxAppearanceProvider:()=>QX,defaultButtonAppearanceProvider:()=>JX,decodePDFRawStream:()=>V8,decodeFromBase64DataUri:()=>V4,decodeFromBase64:()=>q4,createValueErrorMsg:()=>e9,createTypeErrorMsg:()=>VK,createPDFAcroFields:()=>Z8,createPDFAcroField:()=>kq,copyStringIntoBuffer:()=>k0,concatTransformationMatrix:()=>I1,componentsToColor:()=>l0,colorToComponents:()=>$q,cmyk:()=>yq,closePath:()=>N2,clipEvenOdd:()=>xZ,clip:()=>Oq,cleanText:()=>k6,charSplit:()=>J4,charFromHexCode:()=>Q4,charFromCode:()=>t0,charAtIndex:()=>P1,canBeConvertedToUint8Array:()=>I4,bytesFor:()=>j6,byAscendingId:()=>H4,breakTextIntoLines:()=>G4,beginText:()=>B1,beginMarkedContent:()=>Aq,backtick:()=>$0,assertRangeOrUndefined:()=>X2,assertRange:()=>b0,assertPositive:()=>X6,assertOrUndefined:()=>F,assertMultiple:()=>Y1,assertIsSubset:()=>V7,assertIsOneOfOrUndefined:()=>a0,assertIsOneOf:()=>M2,assertIs:()=>T,assertInteger:()=>K7,assertEachIs:()=>Q1,asPDFNumber:()=>f,asPDFName:()=>z8,asNumber:()=>t,arrayAsString:()=>u8,appendQuadraticCurve:()=>E8,appendBezierCurve:()=>p0,adjustDimsForRotation:()=>r2,addRandomSuffix:()=>uQ,ViewerPreferences:()=>W1,UnsupportedEncodingError:()=>Q7,UnrecognizedStreamTypeError:()=>J7,UnexpectedObjectTypeError:()=>A6,UnexpectedFieldTypeError:()=>z6,UnbalancedParenthesisError:()=>E7,TextRenderingMode:()=>C7,TextAlignment:()=>v0,StandardFonts:()=>N5,StandardFontValues:()=>o9,StandardFontEmbedder:()=>$6,StalledParserError:()=>j7,RotationTypes:()=>E5,RichTextFieldReadError:()=>e7,ReparseError:()=>Q5,RemovePageFromEmptyDocumentError:()=>o7,ReadingDirection:()=>U5,PrivateConstructorError:()=>K5,PrintScaling:()=>z5,PngEmbedder:()=>X8,ParseSpeeds:()=>A1,PageSizes:()=>HX,PageEmbeddingMismatchedContextError:()=>G7,PDFXRefStreamParser:()=>Lq,PDFWriter:()=>o5,PDFWidgetAnnotation:()=>M5,PDFTrailerDict:()=>Qq,PDFTrailer:()=>S6,PDFTextField:()=>A5,PDFString:()=>K0,PDFStreamWriter:()=>Jq,PDFStreamParsingError:()=>I7,PDFStream:()=>E0,PDFSignature:()=>O8,PDFRef:()=>a,PDFRawStream:()=>A2,PDFRadioGroup:()=>l6,PDFParsingError:()=>V6,PDFParser:()=>Bq,PDFPageTree:()=>H8,PDFPageLeaf:()=>_0,PDFPageEmbedder:()=>K8,PDFPage:()=>y0,PDFOptionList:()=>w5,PDFOperatorNames:()=>X0,PDFOperator:()=>e,PDFObjectStreamParser:()=>jq,PDFObjectStream:()=>a5,PDFObjectParsingError:()=>M7,PDFObjectParser:()=>U8,PDFObjectCopier:()=>Z1,PDFObject:()=>z0,PDFNumber:()=>x,PDFNull:()=>F0,PDFName:()=>I,PDFJavaScript:()=>xq,PDFInvalidObjectParsingError:()=>k7,PDFInvalidObject:()=>s5,PDFImage:()=>R5,PDFHexString:()=>g,PDFHeader:()=>_2,PDFForm:()=>gq,PDFFont:()=>w0,PDFFlateStream:()=>N6,PDFField:()=>d0,PDFEmbeddedPage:()=>R8,PDFDropdown:()=>O5,PDFDocument:()=>o0,PDFDict:()=>m,PDFCrossRefStream:()=>Yq,PDFCrossRefSection:()=>i5,PDFContext:()=>Z5,PDFContentStream:()=>p2,PDFCheckBox:()=>f6,PDFCatalog:()=>W8,PDFButton:()=>S5,PDFBool:()=>c2,PDFArrayIsNotRectangleError:()=>Z7,PDFArray:()=>i,PDFAnnotation:()=>Mq,PDFAcroText:()=>J6,PDFAcroTerminal:()=>K2,PDFAcroSignature:()=>F6,PDFAcroRadioButton:()=>Z6,PDFAcroPushButton:()=>G6,PDFAcroNonTerminal:()=>Y6,PDFAcroListBox:()=>W6,PDFAcroForm:()=>P6,PDFAcroField:()=>Y8,PDFAcroComboBox:()=>Q6,PDFAcroChoice:()=>G8,PDFAcroCheckBox:()=>K6,PDFAcroButton:()=>h6,NumberParsingError:()=>Vq,NonFullScreenPageMode:()=>H5,NoSuchFieldError:()=>s7,NextByteAssertionError:()=>z7,MultiSelectValueError:()=>W7,MissingTfOperatorError:()=>U7,MissingPageContentsEmbeddingError:()=>Y7,MissingPDFHeaderError:()=>L7,MissingOnValueCheckError:()=>X3,MissingKeywordError:()=>B7,MissingDAEntryError:()=>H7,MissingCatalogError:()=>qG,MethodNotImplementedError:()=>u0,LineJoinStyle:()=>$7,LineCapStyle:()=>u6,JpegEmbedder:()=>q8,InvalidTargetIndexError:()=>qq,InvalidPDFDateStringError:()=>G1,InvalidMaxLengthError:()=>VX,InvalidFieldNamePartError:()=>t7,InvalidAcroFieldValueError:()=>J5,IndexOutOfBoundsError:()=>Y5,ImageAlignment:()=>T2,ForeignPageError:()=>a7,FontkitNotRegisteredError:()=>i7,FileEmbedder:()=>Wq,FieldExistsAsNonTerminalError:()=>V3,FieldAlreadyExistsError:()=>Dq,ExceededMaxLengthError:()=>XX,EncryptedPDFError:()=>r7,Duplex:()=>Q8,CustomFontSubsetEmbedder:()=>Zq,CustomFontEmbedder:()=>C6,CorruptPageTreeError:()=>Xq,CombedTextLayoutError:()=>qX,ColorTypes:()=>U6,CharCodes:()=>E,Cache:()=>m0,BlendMode:()=>S2,AppearanceCharacteristics:()=>J8,AnnotationFlags:()=>I5,AcroTextFlags:()=>j0,AcroFieldFlags:()=>Y2,AcroChoiceFlags:()=>G0,AcroButtonFlags:()=>f0,AFRelationship:()=>t5});/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any @@ -14,22 +14,22 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var eq=function(q,X){return eq=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(V,K){V.__proto__=K}||function(V,K){for(var Q in K)if(K.hasOwnProperty(Q))V[Q]=K[Q]},eq(q,X)};function w(q,X){eq(q,X);function V(){this.constructor=q}q.prototype=X===null?Object.create(X):(V.prototype=X.prototype,new V)}var o=function(){return o=Object.assign||function(X){for(var V,K=1,Q=arguments.length;K0&&Y[Y.length-1]))&&(Z[0]===6||Z[0]===2)){V=0;continue}if(Z[0]===3&&(!Y||Z[1]>Y[0]&&Z[1]>2],X+=h5[(q[K]&3)<<4|q[K+1]>>4],X+=h5[(q[K+1]&15)<<2|q[K+2]>>6],X+=h5[q[K+2]&63];if(V%3===2)X=X.substring(0,X.length-1)+"=";else if(V%3===1)X=X.substring(0,X.length-2)+"==";return X},q4=function(q){var X=q.length*0.75,V=q.length,K,Q=0,Y,J,G,W;if(q[q.length-1]==="="){if(X--,q[q.length-2]==="=")X--}var Z=new Uint8Array(X);for(K=0;K>4,Z[Q++]=(J&15)<<4|G>>2,Z[Q++]=(G&3)<<6|W&63;return Z},DQ=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,V4=function(q){var X=q.trim(),V=X.substring(0,100),K=V.match(DQ);if(!K)return q4(X);var Q=K[0],Y=X.substring(Q.length);return q4(Y)};var s=function(q){return q.charCodeAt(0)},K4=function(q){return q.codePointAt(0)},D2=function(q,X){return e0(q.toString(16),X,"0").toUpperCase()},u2=function(q){return D2(q,2)},t0=function(q){return String.fromCharCode(q)},Q4=function(q){return t0(parseInt(q,16))},e0=function(q,X,V){var K="";for(var Q=0,Y=X-q.length;Q=55296&&V<=56319&&q.length>Q){if(K=q.charCodeAt(Q),K>=56320&&K<=57343)Y=2}return[q.slice(X,X+Y),Y]},J4=function(q){var X=[];for(var V=0,K=q.length;VV)Z();J+=z,G+=k}}return Z(),W},bQ=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,P8=function(q){var X=q.match(bQ);if(!X)return;var V=X[1],K=X[2],Q=K===void 0?"01":K,Y=X[3],J=Y===void 0?"01":Y,G=X[4],W=G===void 0?"00":G,Z=X[5],H=Z===void 0?"00":Z,U=X[6],z=U===void 0?"00":U,k=X[7],M=k===void 0?"Z":k,j=X[8],B=j===void 0?"00":j,L=X[9],O=L===void 0?"00":L,N=M==="Z"?"Z":""+M+B+":"+O,R=new Date(V+"-"+Q+"-"+J+"T"+W+":"+H+":"+z+N);return R},F5=function(q,X){var V,K=0,Q;while(K>6&31|192,G=Y&63|128;V.push(J,G),K+=1}else if(Y<65536){var J=Y>>12&15|224,G=Y>>6&63|128,W=Y&63|128;V.push(J,G,W),K+=1}else if(Y<1114112){var J=Y>>18&7|240,G=Y>>12&63|128,W=Y>>6&63|128,Z=Y>>0&63|128;V.push(J,G,W,Z),K+=2}else throw Error("Invalid code point: 0x"+u2(Y))}return new Uint8Array(V)},E4=function(q,X){if(X===void 0)X=!0;var V=[];if(X)V.push(65279);for(var K=0,Q=q.length;K=0&&q<=65535},L4=function(q){return q>=65536&&q<=1114111},D1=function(q){return Math.floor((q-65536)/1024)+55296},u1=function(q){return(q-65536)%1024+56320},E6;(function(q){q.BigEndian="BigEndian",q.LittleEndian="LittleEndian"})(E6||(E6={}));var g8="�".codePointAt(0),x8=function(q,X){if(X===void 0)X=!0;if(q.length<=1)return String.fromCodePoint(g8);var V=X?lQ(q):E6.BigEndian,K=X?2:0,Q=[];while(q.length-K>=2){var Y=lX(q[K++],q[K++],V);if(fQ(Y))if(q.length-K<2)Q.push(g8);else{var J=lX(q[K++],q[K++],V);if(fX(J))Q.push(Y,J);else Q.push(g8)}else if(fX(Y))K+=2,Q.push(g8);else Q.push(Y)}if(K=55296&&q<=56319},fX=function(q){return q>=56320&&q<=57343},lX=function(q,X,V){if(V===E6.LittleEndian)return X<<8|q;if(V===E6.BigEndian)return q<<8|X;throw Error("Invalid byteOrder: "+V)},lQ=function(q){return _X(q)?E6.BigEndian:cX(q)?E6.LittleEndian:E6.BigEndian},_X=function(q){return q[0]===254&&q[1]===255},cX=function(q){return q[0]===255&&q[1]===254},b8=function(q){return _X(q)||cX(q)};var B4=function(q){var X=String(q);if(Math.abs(q)<1){var V=parseInt(q.toString().split("e-")[1]);if(V){var K=q<0;if(K)q*=-1;if(q*=Math.pow(10,V-1),X="0."+Array(V).join("0")+q.toString().substring(2),K)X="-"+X}}else{var V=parseInt(q.toString().split("+")[1]);if(V>20)V-=20,q/=Math.pow(10,V),X=q.toString()+Array(V+1).join("0")}return X},P5=function(q){return Math.ceil(q.toString(2).length/8)},j6=function(q){var X=new Uint8Array(P5(q));for(var V=1;V<=X.length;V++)X[V-1]=q>>(X.length-V)*8;return X};var L6=function(q){throw Error(q)};var h9=$8(X1(),1),C9="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",V1=new Uint8Array(256);for(p5=0;p5>4,Z[Q++]=(J&15)<<4|G>>2,Z[Q++]=(G&3)<<6|W&63;return Z},uJ=function(q){var X="";for(var V=0;VK)throw Error($0(X)+" must be at least "+V+" and at most "+K+", but was actually "+q)},X2=function(q,X,V,K){if(T(q,X,["number","undefined"]),typeof q==="number")b0(q,X,V,K)},Y1=function(q,X,V){if(T(q,X,["number"]),q%V!==0)throw Error($0(X)+" must be a multiple of "+V+", but was actually "+q)},K7=function(q,X){if(!Number.isInteger(q))throw Error($0(X)+" must be an integer, but was actually "+q)},X6=function(q,X){if(![1,0].includes(Math.sign(q)))throw Error($0(X)+" must be a positive number or 0, but was actually "+q)};var V0=new Uint16Array(256);for(r5=0;r5<256;r5++)V0[r5]=r5;var r5;V0[22]=s("\x17");V0[24]=s("˘");V0[25]=s("ˇ");V0[26]=s("ˆ");V0[27]=s("˙");V0[28]=s("˝");V0[29]=s("˛");V0[30]=s("˚");V0[31]=s("˜");V0[127]=s("�");V0[128]=s("•");V0[129]=s("†");V0[130]=s("‡");V0[131]=s("…");V0[132]=s("—");V0[133]=s("–");V0[134]=s("ƒ");V0[135]=s("⁄");V0[136]=s("‹");V0[137]=s("›");V0[138]=s("−");V0[139]=s("‰");V0[140]=s("„");V0[141]=s("“");V0[142]=s("”");V0[143]=s("‘");V0[144]=s("’");V0[145]=s("‚");V0[146]=s("™");V0[147]=s("fi");V0[148]=s("fl");V0[149]=s("Ł");V0[150]=s("Œ");V0[151]=s("Š");V0[152]=s("Ÿ");V0[153]=s("Ž");V0[154]=s("ı");V0[155]=s("ł");V0[156]=s("œ");V0[157]=s("š");V0[158]=s("ž");V0[159]=s("�");V0[160]=s("€");V0[173]=s("�");var J1=function(q){var X=Array(q.length);for(var V=0,K=q.length;V=E.ExclamationPoint&&q<=E.Tilde&&!Kq[q]},KK={},QK=new Map,ZG=function(q){w(X,q);function X(V,K){var Q=this;if(V!==KK)throw new K5("PDFName");Q=q.call(this)||this;var Y="/";for(var J=0,G=K.length;J=E.Zero&&Z<=E.Nine||Z>=E.a&&Z<=E.f||Z>=E.A&&Z<=E.F){if(K+=W,K.length===2||!(H>="0"&&H<="9"||H>="a"&&H<="f"||H>="A"&&H<="F"))Y(parseInt(K,16)),K=""}else Y(Z)}return new Uint8Array(V)},X.prototype.decodeText=function(){var V=this.asBytes();return String.fromCharCode.apply(String,Array.from(V))},X.prototype.asString=function(){return this.encodedName},X.prototype.value=function(){return this.encodedName},X.prototype.clone=function(){return this},X.prototype.toString=function(){return this.encodedName},X.prototype.sizeInBytes=function(){return this.encodedName.length},X.prototype.copyBytesInto=function(V,K){return K+=k0(this.encodedName,V,K),this.encodedName.length},X.of=function(V){var K=JG(V),Q=QK.get(K);if(!Q)Q=new X(KK,K),QK.set(K,Q);return Q},X.Length=X.of("Length"),X.FlateDecode=X.of("FlateDecode"),X.Resources=X.of("Resources"),X.Font=X.of("Font"),X.XObject=X.of("XObject"),X.ExtGState=X.of("ExtGState"),X.Contents=X.of("Contents"),X.Type=X.of("Type"),X.Parent=X.of("Parent"),X.MediaBox=X.of("MediaBox"),X.Page=X.of("Page"),X.Annots=X.of("Annots"),X.TrimBox=X.of("TrimBox"),X.ArtBox=X.of("ArtBox"),X.BleedBox=X.of("BleedBox"),X.CropBox=X.of("CropBox"),X.Rotate=X.of("Rotate"),X.Title=X.of("Title"),X.Author=X.of("Author"),X.Subject=X.of("Subject"),X.Creator=X.of("Creator"),X.Keywords=X.of("Keywords"),X.Producer=X.of("Producer"),X.CreationDate=X.of("CreationDate"),X.ModDate=X.of("ModDate"),X}(z0),I=ZG;var WG=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.asNull=function(){return null},X.prototype.clone=function(){return this},X.prototype.toString=function(){return"null"},X.prototype.sizeInBytes=function(){return 4},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.n,V[K++]=E.u,V[K++]=E.l,V[K++]=E.l,4},X}(z0),F0=new WG;var HG=function(q){w(X,q);function X(V,K){var Q=q.call(this)||this;return Q.dict=V,Q.context=K,Q}return X.prototype.keys=function(){return Array.from(this.dict.keys())},X.prototype.values=function(){return Array.from(this.dict.values())},X.prototype.entries=function(){return Array.from(this.dict.entries())},X.prototype.set=function(V,K){this.dict.set(V,K)},X.prototype.get=function(V,K){if(K===void 0)K=!1;var Q=this.dict.get(V);if(Q===F0&&!K)return;return Q},X.prototype.has=function(V){var K=this.dict.get(V);return K!==void 0&&K!==F0},X.prototype.lookupMaybe=function(V){var K,Q=[];for(var Y=1;Y0&&Y[Y.length-1]))&&(Z[0]===6||Z[0]===2)){V=0;continue}if(Z[0]===3&&(!Y||Z[1]>Y[0]&&Z[1]>2],X+=h5[(q[K]&3)<<4|q[K+1]>>4],X+=h5[(q[K+1]&15)<<2|q[K+2]>>6],X+=h5[q[K+2]&63];if(V%3===2)X=X.substring(0,X.length-1)+"=";else if(V%3===1)X=X.substring(0,X.length-2)+"==";return X},q4=function(q){var X=q.length*0.75,V=q.length,K,Q=0,Y,J,G,W;if(q[q.length-1]==="="){if(X--,q[q.length-2]==="=")X--}var Z=new Uint8Array(X);for(K=0;K>4,Z[Q++]=(J&15)<<4|G>>2,Z[Q++]=(G&3)<<6|W&63;return Z},DQ=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,V4=function(q){var X=q.trim(),V=X.substring(0,100),K=V.match(DQ);if(!K)return q4(X);var Q=K[0],Y=X.substring(Q.length);return q4(Y)};var s=function(q){return q.charCodeAt(0)},K4=function(q){return q.codePointAt(0)},D2=function(q,X){return e0(q.toString(16),X,"0").toUpperCase()},u2=function(q){return D2(q,2)},t0=function(q){return String.fromCharCode(q)},Q4=function(q){return t0(parseInt(q,16))},e0=function(q,X,V){var K="";for(var Q=0,Y=X-q.length;Q=55296&&V<=56319&&q.length>Q){if(K=q.charCodeAt(Q),K>=56320&&K<=57343)Y=2}return[q.slice(X,X+Y),Y]},J4=function(q){var X=[];for(var V=0,K=q.length;VV)Z();J+=z,G+=k}}return Z(),W},bQ=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,P8=function(q){var X=q.match(bQ);if(!X)return;var V=X[1],K=X[2],Q=K===void 0?"01":K,Y=X[3],J=Y===void 0?"01":Y,G=X[4],W=G===void 0?"00":G,Z=X[5],H=Z===void 0?"00":Z,U=X[6],z=U===void 0?"00":U,k=X[7],M=k===void 0?"Z":k,j=X[8],B=j===void 0?"00":j,L=X[9],O=L===void 0?"00":L,N=M==="Z"?"Z":""+M+B+":"+O,R=new Date(V+"-"+Q+"-"+J+"T"+W+":"+H+":"+z+N);return R},F5=function(q,X){var V,K=0,Q;while(K>6&31|192,G=Y&63|128;V.push(J,G),K+=1}else if(Y<65536){var J=Y>>12&15|224,G=Y>>6&63|128,W=Y&63|128;V.push(J,G,W),K+=1}else if(Y<1114112){var J=Y>>18&7|240,G=Y>>12&63|128,W=Y>>6&63|128,Z=Y>>0&63|128;V.push(J,G,W,Z),K+=2}else throw Error("Invalid code point: 0x"+u2(Y))}return new Uint8Array(V)},E4=function(q,X){if(X===void 0)X=!0;var V=[];if(X)V.push(65279);for(var K=0,Q=q.length;K=0&&q<=65535},L4=function(q){return q>=65536&&q<=1114111},D1=function(q){return Math.floor((q-65536)/1024)+55296},u1=function(q){return(q-65536)%1024+56320},E6;(function(q){q.BigEndian="BigEndian",q.LittleEndian="LittleEndian"})(E6||(E6={}));var g8="�".codePointAt(0),x8=function(q,X){if(X===void 0)X=!0;if(q.length<=1)return String.fromCodePoint(g8);var V=X?lQ(q):E6.BigEndian,K=X?2:0,Q=[];while(q.length-K>=2){var Y=lX(q[K++],q[K++],V);if(fQ(Y))if(q.length-K<2)Q.push(g8);else{var J=lX(q[K++],q[K++],V);if(fX(J))Q.push(Y,J);else Q.push(g8)}else if(fX(Y))K+=2,Q.push(g8);else Q.push(Y)}if(K=55296&&q<=56319},fX=function(q){return q>=56320&&q<=57343},lX=function(q,X,V){if(V===E6.LittleEndian)return X<<8|q;if(V===E6.BigEndian)return q<<8|X;throw Error("Invalid byteOrder: "+V)},lQ=function(q){return _X(q)?E6.BigEndian:cX(q)?E6.LittleEndian:E6.BigEndian},_X=function(q){return q[0]===254&&q[1]===255},cX=function(q){return q[0]===255&&q[1]===254},b8=function(q){return _X(q)||cX(q)};var B4=function(q){var X=String(q);if(Math.abs(q)<1){var V=parseInt(q.toString().split("e-")[1]);if(V){var K=q<0;if(K)q*=-1;if(q*=Math.pow(10,V-1),X="0."+Array(V).join("0")+q.toString().substring(2),K)X="-"+X}}else{var V=parseInt(q.toString().split("+")[1]);if(V>20)V-=20,q/=Math.pow(10,V),X=q.toString()+Array(V+1).join("0")}return X},P5=function(q){return Math.ceil(q.toString(2).length/8)},j6=function(q){var X=new Uint8Array(P5(q));for(var V=1;V<=X.length;V++)X[V-1]=q>>(X.length-V)*8;return X};var L6=function(q){throw Error(q)};var h9=$8(X1(),1),C9="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",V1=new Uint8Array(256);for(p5=0;p5>4,Z[Q++]=(J&15)<<4|G>>2,Z[Q++]=(G&3)<<6|W&63;return Z},uJ=function(q){var X="";for(var V=0;VK)throw Error($0(X)+" must be at least "+V+" and at most "+K+", but was actually "+q)},X2=function(q,X,V,K){if(T(q,X,["number","undefined"]),typeof q==="number")b0(q,X,V,K)},Y1=function(q,X,V){if(T(q,X,["number"]),q%V!==0)throw Error($0(X)+" must be a multiple of "+V+", but was actually "+q)},K7=function(q,X){if(!Number.isInteger(q))throw Error($0(X)+" must be an integer, but was actually "+q)},X6=function(q,X){if(![1,0].includes(Math.sign(q)))throw Error($0(X)+" must be a positive number or 0, but was actually "+q)};var V0=new Uint16Array(256);for(r5=0;r5<256;r5++)V0[r5]=r5;var r5;V0[22]=s("\x17");V0[24]=s("˘");V0[25]=s("ˇ");V0[26]=s("ˆ");V0[27]=s("˙");V0[28]=s("˝");V0[29]=s("˛");V0[30]=s("˚");V0[31]=s("˜");V0[127]=s("�");V0[128]=s("•");V0[129]=s("†");V0[130]=s("‡");V0[131]=s("…");V0[132]=s("—");V0[133]=s("–");V0[134]=s("ƒ");V0[135]=s("⁄");V0[136]=s("‹");V0[137]=s("›");V0[138]=s("−");V0[139]=s("‰");V0[140]=s("„");V0[141]=s("“");V0[142]=s("”");V0[143]=s("‘");V0[144]=s("’");V0[145]=s("‚");V0[146]=s("™");V0[147]=s("fi");V0[148]=s("fl");V0[149]=s("Ł");V0[150]=s("Œ");V0[151]=s("Š");V0[152]=s("Ÿ");V0[153]=s("Ž");V0[154]=s("ı");V0[155]=s("ł");V0[156]=s("œ");V0[157]=s("š");V0[158]=s("ž");V0[159]=s("�");V0[160]=s("€");V0[173]=s("�");var J1=function(q){var X=Array(q.length);for(var V=0,K=q.length;V=E.ExclamationPoint&&q<=E.Tilde&&!Kq[q]},KK={},QK=new Map,ZG=function(q){A(X,q);function X(V,K){var Q=this;if(V!==KK)throw new K5("PDFName");Q=q.call(this)||this;var Y="/";for(var J=0,G=K.length;J=E.Zero&&Z<=E.Nine||Z>=E.a&&Z<=E.f||Z>=E.A&&Z<=E.F){if(K+=W,K.length===2||!(H>="0"&&H<="9"||H>="a"&&H<="f"||H>="A"&&H<="F"))Y(parseInt(K,16)),K=""}else Y(Z)}return new Uint8Array(V)},X.prototype.decodeText=function(){var V=this.asBytes();return String.fromCharCode.apply(String,Array.from(V))},X.prototype.asString=function(){return this.encodedName},X.prototype.value=function(){return this.encodedName},X.prototype.clone=function(){return this},X.prototype.toString=function(){return this.encodedName},X.prototype.sizeInBytes=function(){return this.encodedName.length},X.prototype.copyBytesInto=function(V,K){return K+=k0(this.encodedName,V,K),this.encodedName.length},X.of=function(V){var K=JG(V),Q=QK.get(K);if(!Q)Q=new X(KK,K),QK.set(K,Q);return Q},X.Length=X.of("Length"),X.FlateDecode=X.of("FlateDecode"),X.Resources=X.of("Resources"),X.Font=X.of("Font"),X.XObject=X.of("XObject"),X.ExtGState=X.of("ExtGState"),X.Contents=X.of("Contents"),X.Type=X.of("Type"),X.Parent=X.of("Parent"),X.MediaBox=X.of("MediaBox"),X.Page=X.of("Page"),X.Annots=X.of("Annots"),X.TrimBox=X.of("TrimBox"),X.ArtBox=X.of("ArtBox"),X.BleedBox=X.of("BleedBox"),X.CropBox=X.of("CropBox"),X.Rotate=X.of("Rotate"),X.Title=X.of("Title"),X.Author=X.of("Author"),X.Subject=X.of("Subject"),X.Creator=X.of("Creator"),X.Keywords=X.of("Keywords"),X.Producer=X.of("Producer"),X.CreationDate=X.of("CreationDate"),X.ModDate=X.of("ModDate"),X}(z0),I=ZG;var WG=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.asNull=function(){return null},X.prototype.clone=function(){return this},X.prototype.toString=function(){return"null"},X.prototype.sizeInBytes=function(){return 4},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.n,V[K++]=E.u,V[K++]=E.l,V[K++]=E.l,4},X}(z0),F0=new WG;var HG=function(q){A(X,q);function X(V,K){var Q=q.call(this)||this;return Q.dict=V,Q.context=K,Q}return X.prototype.keys=function(){return Array.from(this.dict.keys())},X.prototype.values=function(){return Array.from(this.dict.values())},X.prototype.entries=function(){return Array.from(this.dict.entries())},X.prototype.set=function(V,K){this.dict.set(V,K)},X.prototype.get=function(V,K){if(K===void 0)K=!1;var Q=this.dict.get(V);if(Q===F0&&!K)return;return Q},X.prototype.has=function(V){var K=this.dict.get(V);return K!==void 0&&K!==F0},X.prototype.lookupMaybe=function(V){var K,Q=[];for(var Y=1;Ythis.largestObjectNumber)this.largestObjectNumber=X.objectNumber},q.prototype.nextRef=function(){return this.largestObjectNumber+=1,a.of(this.largestObjectNumber)},q.prototype.register=function(X){var V=this.nextRef();return this.assign(V,X),V},q.prototype.delete=function(X){return this.indirectObjects.delete(X)},q.prototype.lookupMaybe=function(X){var V=[];for(var K=1;Kthis.largestObjectNumber)this.largestObjectNumber=X.objectNumber},q.prototype.nextRef=function(){return this.largestObjectNumber+=1,a.of(this.largestObjectNumber)},q.prototype.register=function(X){var V=this.nextRef();return this.assign(V,X),V},q.prototype.delete=function(X){return this.indirectObjects.delete(X)},q.prototype.lookupMaybe=function(X){var V=[];for(var K=1;K1)this.subsections.push([X]),this.chunkIdx+=1,this.chunkLength=1;else V.push(X),this.chunkLength+=1},q.create=function(){return new q({ref:a.of(0,65535),offset:0,deleted:!0})},q.createEmpty=function(){return new q},q}(),i5=vG;var RG=function(){function q(X){this.lastXRefOffset=String(X)}return q.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` %%EOF`},q.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},q.prototype.copyBytesInto=function(X,V){var K=V;return X[V++]=E.s,X[V++]=E.t,X[V++]=E.a,X[V++]=E.r,X[V++]=E.t,X[V++]=E.x,X[V++]=E.r,X[V++]=E.e,X[V++]=E.f,X[V++]=E.Newline,V+=k0(this.lastXRefOffset,X,V),X[V++]=E.Newline,X[V++]=E.Percent,X[V++]=E.Percent,X[V++]=E.E,X[V++]=E.O,X[V++]=E.F,V-K},q.forLastCrossRefSectionOffset=function(X){return new q(X)},q}(),S6=RG;var OG=function(){function q(X){this.dict=X}return q.prototype.toString=function(){return`trailer -`+this.dict.toString()},q.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},q.prototype.copyBytesInto=function(X,V){var K=V;return X[V++]=E.t,X[V++]=E.r,X[V++]=E.a,X[V++]=E.i,X[V++]=E.l,X[V++]=E.e,X[V++]=E.r,X[V++]=E.Newline,V+=this.dict.copyBytesInto(X,V),V-K},q.of=function(X){return new q(X)},q}(),Qq=OG;var AG=function(q){w(X,q);function X(V,K,Q){if(Q===void 0)Q=!0;var Y=q.call(this,V.obj({}),Q)||this;return Y.objects=K,Y.offsets=Y.computeObjectOffsets(),Y.offsetsString=Y.computeOffsetsString(),Y.dict.set(I.of("Type"),I.of("ObjStm")),Y.dict.set(I.of("N"),x.of(Y.objects.length)),Y.dict.set(I.of("First"),x.of(Y.offsetsString.length)),Y}return X.prototype.getObjectsCount=function(){return this.objects.length},X.prototype.clone=function(V){return X.withContextAndObjects(V||this.dict.context,this.objects.slice(),this.encode)},X.prototype.getContentsString=function(){var V=this.offsetsString;for(var K=0,Q=this.objects.length;K1)J.push(G),J.push(H.ref.objectNumber),G=0;G+=1}return J.push(G),J},Y.computeEntryTuples=function(){var J=Array(Y.entries.length);for(var G=0,W=Y.entries.length;GG[0])G[0]=M;if(j>G[1])G[1]=j;if(B>G[2])G[2]=B}return G},Y.entries=K||[],Y.entryTuplesCache=m0.populatedBy(Y.computeEntryTuples),Y.maxByteWidthsCache=m0.populatedBy(Y.computeMaxEntryByteWidths),Y.indexCache=m0.populatedBy(Y.computeIndex),V.set(I.of("Type"),I.of("XRef")),Y}return X.prototype.addDeletedEntry=function(V,K){var Q=y6.Deleted;this.entries.push({type:Q,ref:V,nextFreeObjectNumber:K}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.addUncompressedEntry=function(V,K){var Q=y6.Uncompressed;this.entries.push({type:Q,ref:V,offset:K}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.addCompressedEntry=function(V,K,Q){var Y=y6.Compressed;this.entries.push({type:Y,ref:V,objectStreamRef:K,index:Q}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.clone=function(V){var K=this,Q=K.dict,Y=K.entries,J=K.encode;return X.of(Q.clone(V),Y.slice(),J)},X.prototype.getContentsString=function(){var V=this.entryTuplesCache.access(),K=this.maxByteWidthsCache.access(),Q="";for(var Y=0,J=V.length;Y=0;M--)Q+=(U[M]||0).toString(2);for(var M=K[1]-1;M>=0;M--)Q+=(z[M]||0).toString(2);for(var M=K[2]-1;M>=0;M--)Q+=(k[M]||0).toString(2)}return Q},X.prototype.getUnencodedContents=function(){var V=this.entryTuplesCache.access(),K=this.maxByteWidthsCache.access(),Q=new Uint8Array(this.getUnencodedContentsSize()),Y=0;for(var J=0,G=V.length;J=0;j--)Q[Y++]=z[j]||0;for(var j=K[1]-1;j>=0;j--)Q[Y++]=k[j]||0;for(var j=K[2]-1;j>=0;j--)Q[Y++]=M[j]||0}return Q},X.prototype.getUnencodedContentsSize=function(){var V=this.maxByteWidthsCache.access(),K=z4(V);return K*this.entries.length},X.prototype.updateDict=function(){q.prototype.updateDict.call(this);var V=this.maxByteWidthsCache.access(),K=this.indexCache.access(),Q=this.dict.context;this.dict.set(I.of("W"),Q.obj(V)),this.dict.set(I.of("Index"),Q.obj(K))},X.create=function(V,K){if(K===void 0)K=!0;var Q=new X(V,[],K);return Q.addDeletedEntry(a.of(0,65535),0),Q},X.of=function(V,K,Q){if(Q===void 0)Q=!0;return new X(V,K,Q)},X}(N6),Yq=SG;var yG=function(q){w(X,q);function X(V,K,Q,Y){var J=q.call(this,V,K)||this;return J.encodeStreams=Q,J.objectsPerStream=Y,J}return X.prototype.computeBufferSize=function(){return _(this,void 0,void 0,function(){var V,K,Q,Y,J,G,W,Z,M,j,H,L,U,z,B,k,M,j,B,L,O,N,R,v;return c(this,function(A){switch(A.label){case 0:V=this.context.largestObjectNumber+1,K=_2.forVersion(1,7),Q=K.sizeInBytes()+2,Y=Yq.create(this.createTrailerDict(),this.encodeStreams),J=[],G=[],W=[],Z=this.context.enumerateIndirectObjects(),M=0,j=Z.length,A.label=1;case 1:if(!(M"},X.prototype.sizeInBytes=function(){return this.value.length+2},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.LessThan,K+=k0(this.value,V,K),V[K++]=E.GreaterThan,this.value.length+2},X.of=function(V){return new X(V)},X.fromText=function(V){var K=E4(V),Q="";for(var Y=0,J=K.length;Y1)J.push(G),J.push(H.ref.objectNumber),G=0;G+=1}return J.push(G),J},Y.computeEntryTuples=function(){var J=Array(Y.entries.length);for(var G=0,W=Y.entries.length;GG[0])G[0]=M;if(j>G[1])G[1]=j;if(B>G[2])G[2]=B}return G},Y.entries=K||[],Y.entryTuplesCache=m0.populatedBy(Y.computeEntryTuples),Y.maxByteWidthsCache=m0.populatedBy(Y.computeMaxEntryByteWidths),Y.indexCache=m0.populatedBy(Y.computeIndex),V.set(I.of("Type"),I.of("XRef")),Y}return X.prototype.addDeletedEntry=function(V,K){var Q=y6.Deleted;this.entries.push({type:Q,ref:V,nextFreeObjectNumber:K}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.addUncompressedEntry=function(V,K){var Q=y6.Uncompressed;this.entries.push({type:Q,ref:V,offset:K}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.addCompressedEntry=function(V,K,Q){var Y=y6.Compressed;this.entries.push({type:Y,ref:V,objectStreamRef:K,index:Q}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},X.prototype.clone=function(V){var K=this,Q=K.dict,Y=K.entries,J=K.encode;return X.of(Q.clone(V),Y.slice(),J)},X.prototype.getContentsString=function(){var V=this.entryTuplesCache.access(),K=this.maxByteWidthsCache.access(),Q="";for(var Y=0,J=V.length;Y=0;M--)Q+=(U[M]||0).toString(2);for(var M=K[1]-1;M>=0;M--)Q+=(z[M]||0).toString(2);for(var M=K[2]-1;M>=0;M--)Q+=(k[M]||0).toString(2)}return Q},X.prototype.getUnencodedContents=function(){var V=this.entryTuplesCache.access(),K=this.maxByteWidthsCache.access(),Q=new Uint8Array(this.getUnencodedContentsSize()),Y=0;for(var J=0,G=V.length;J=0;j--)Q[Y++]=z[j]||0;for(var j=K[1]-1;j>=0;j--)Q[Y++]=k[j]||0;for(var j=K[2]-1;j>=0;j--)Q[Y++]=M[j]||0}return Q},X.prototype.getUnencodedContentsSize=function(){var V=this.maxByteWidthsCache.access(),K=z4(V);return K*this.entries.length},X.prototype.updateDict=function(){q.prototype.updateDict.call(this);var V=this.maxByteWidthsCache.access(),K=this.indexCache.access(),Q=this.dict.context;this.dict.set(I.of("W"),Q.obj(V)),this.dict.set(I.of("Index"),Q.obj(K))},X.create=function(V,K){if(K===void 0)K=!0;var Q=new X(V,[],K);return Q.addDeletedEntry(a.of(0,65535),0),Q},X.of=function(V,K,Q){if(Q===void 0)Q=!0;return new X(V,K,Q)},X}(N6),Yq=SG;var yG=function(q){A(X,q);function X(V,K,Q,Y){var J=q.call(this,V,K)||this;return J.encodeStreams=Q,J.objectsPerStream=Y,J}return X.prototype.computeBufferSize=function(){return _(this,void 0,void 0,function(){var V,K,Q,Y,J,G,W,Z,M,j,H,L,U,z,B,k,M,j,B,L,O,N,R,v;return c(this,function(w){switch(w.label){case 0:V=this.context.largestObjectNumber+1,K=_2.forVersion(1,7),Q=K.sizeInBytes()+2,Y=Yq.create(this.createTrailerDict(),this.encodeStreams),J=[],G=[],W=[],Z=this.context.enumerateIndirectObjects(),M=0,j=Z.length,w.label=1;case 1:if(!(M"},X.prototype.sizeInBytes=function(){return this.value.length+2},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.LessThan,K+=k0(this.value,V,K),V[K++]=E.GreaterThan,this.value.length+2},X.of=function(V){return new X(V)},X.fromText=function(V){var K=E4(V),Q="";for(var Y=0,J=K.length;Y"},Gq=function(q){return D2(q,4)},FG=function(q){if(j4(q))return Gq(q);if(L4(q)){var X=D1(q),V=u1(q);return""+Gq(X)+Gq(V)}var K=u2(q),Q="0x"+K+" is not a valid UTF-8 or UTF-16 codepoint.";throw Error(Q)};var PG=function(q){var X=0,V=function(K){X|=1<=E.Zero&&Z<=E.Seven){if(K+=W,K.length===3||!(H>="0"&&H<="7"))Y(parseInt(K,8)),K=""}else Y(Z)}return new Uint8Array(V)},X.prototype.decodeText=function(){var V=this.asBytes();if(b8(V))return x8(V);return J1(V)},X.prototype.decodeDate=function(){var V=this.decodeText(),K=P8(V);if(!K)throw new G1(V);return K},X.prototype.asString=function(){return this.value},X.prototype.clone=function(){return X.of(this.value)},X.prototype.toString=function(){return"("+this.value+")"},X.prototype.sizeInBytes=function(){return this.value.length+2},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.LeftParen,K+=k0(this.value,V,K),V[K++]=E.RightParen,this.value.length+2},X.of=function(V){return new X(V)},X.fromDate=function(V){var K=e0(String(V.getUTCFullYear()),4,"0"),Q=e0(String(V.getUTCMonth()+1),2,"0"),Y=e0(String(V.getUTCDate()),2,"0"),J=e0(String(V.getUTCHours()),2,"0"),G=e0(String(V.getUTCMinutes()),2,"0"),W=e0(String(V.getUTCSeconds()),2,"0");return new X("D:"+K+Q+Y+J+G+W+"Z")},X}(z0),K0=DG;var uG=function(){function q(X,V,K,Q){var Y=this;this.allGlyphsInFontSortedById=function(){var J=Array(Y.font.characterSet.length);for(var G=0,W=J.length;G>3)]>>7-((M&7)<<0)&1,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?A[C]:255}}if(H==2)for(var S=0;S>2)]>>6-((M&3)<<1)&3,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?A[C]:255}}if(H==4)for(var S=0;S>1)]>>4-((M&1)<<2)&15,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?A[C]:255}}if(H==8)for(var M=0;M>>3)]>>>7-(r&7)&1),I0=u==L*255?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==2)for(var r=0;r>>2)]>>>6-((r&3)<<1)&3),I0=u==L*85?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==4)for(var r=0;r>>1)]>>>4-((r&1)<<2)&15),I0=u==L*17?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==8)for(var r=0;r>>2<<3);while(Q==0){if(Q=B(X,z,1),Y=B(X,z+1,2),z+=3,Y==0){if((z&7)!=0)z+=8-(z&7);var S=(z>>>3)+4,h=X[S-4]|X[S-3]<<8;if($)V=q.H.W(V,U+h);V.set(new K(X.buffer,X.byteOffset+S,h),U),z=S+h<<3,U+=h;continue}if($)V=q.H.W(V,U+131072);if(Y==1)k=A.J,M=A.h,Z=511,H=31;if(Y==2){J=L(X,z,5)+257,G=L(X,z+5,5)+1,W=L(X,z+10,4)+4,z+=14;var b=z,C=1;for(var D=0;D<38;D+=2)A.Q[D]=0,A.Q[D+1]=0;for(var D=0;DC)C=l}z+=3*W,N(A.Q,C),R(A.Q,C,A.u),k=A.w,M=A.d,z=O(A.u,(1<>>4;if(r>>>8==0)V[U++]=r;else if(r==256)break;else{var I0=U+r-254;if(r>264){var n0=A.q[r-257];I0=U+(n0>>>3)+L(X,z,n0&7),z+=n0&7}var N8=M[v(X,z)&H];z+=N8&15;var S8=N8>>>4,y2=A.c[S8],Z2=(y2>>>4)+B(X,z,y2&15);z+=y2&15;while(U>>4;if(U<=15)J[Z]=U,Z++;else{var z=0,k=0;if(U==16)k=3+G(Q,Y,2),Y+=2,z=J[Z-1];else if(U==17)k=3+G(Q,Y,3),Y+=3;else if(U==18)k=11+G(Q,Y,7),Y+=7;var M=Z+k;while(Z>>1;while(JY)Y=W;J++}while(J>1,Z=X[G+1],H=W<<4|Z,U=V-Z,z=X[G]<>>15-V;K[M]=H,z++}}},q.H.l=function(X,V){var K=q.H.m.r,Q=15-V;for(var Y=0;Y>>Q}},q.H.M=function(X,V,K){K=K<<(V&7);var Q=V>>>3;X[Q]|=K,X[Q+1]|=K>>>8},q.H.I=function(X,V,K){K=K<<(V&7);var Q=V>>>3;X[Q]|=K,X[Q+1]|=K>>>8,X[Q+2]|=K>>>16},q.H.e=function(X,V,K){return(X[V>>>3]|X[(V>>>3)+1]<<8)>>>(V&7)&(1<>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16)>>>(V&7)&(1<>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16)>>>(V&7)},q.H.i=function(X,V){return(X[V>>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16|X[(V>>>3)+3]<<24)>>>(V&7)},q.H.m=function(){var X=Uint16Array,V=Uint32Array;return{K:new X(16),j:new X(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new X(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new V(32),J:new X(512),_:[],h:new X(32),$:[],w:new X(32768),C:[],v:[],d:new X(32768),D:[],u:new X(512),Q:[],r:new X(32768),s:new V(286),Y:new V(30),a:new V(19),t:new V(15000),k:new X(65536),g:new X(32768)}}(),function(){var X=q.H.m,V=32768;for(var K=0;K>>1|(Q&1431655765)<<1,Q=(Q&3435973836)>>>2|(Q&858993459)<<2,Q=(Q&4042322160)>>>4|(Q&252645135)<<4,Q=(Q&4278255360)>>>8|(Q&16711935)<<8,X.r[K]=(Q>>>16|Q<<16)>>>17}function Y(J,G,W){while(G--!=0)J.push(0,W)}for(var K=0;K<32;K++)X.q[K]=X.S[K]<<3|X.T[K],X.c[K]=X.p[K]<<4|X.z[K];Y(X._,144,8),Y(X._,112,9),Y(X._,24,7),Y(X._,8,8),q.H.n(X._,9),q.H.A(X._,9,X.J),q.H.l(X._,9),Y(X.$,32,5),q.H.n(X.$,5),q.H.A(X.$,5,X.h),q.H.l(X.$,5),Y(X.Q,19,0),Y(X.C,286,0),Y(X.D,30,0),Y(X.v,320,0)}(),q.H.N}();P.decode._readInterlace=function(q,X){var{width:V,height:K}=X,Q=P.decode._getBPP(X),Y=Q>>3,J=Math.ceil(V*Q/8),G=new Uint8Array(K*J),W=0,Z=[0,0,4,0,2,0,1],H=[0,4,0,2,0,1,0],U=[8,8,8,4,4,2,2],z=[8,8,4,4,2,2,1],k=0;while(k<7){var M=U[k],j=z[k],B=0,L=0,O=Z[k];while(O>3];h=h>>7-(S&7)&1,G[A*J+($>>3)]|=h<<7-(($&7)<<0)}if(Q==2){var h=q[S>>3];h=h>>6-(S&7)&3,G[A*J+($>>2)]|=h<<6-(($&3)<<1)}if(Q==4){var h=q[S>>3];h=h>>4-(S&7)&15,G[A*J+($>>1)]|=h<<4-(($&1)<<2)}if(Q>=8){var b=A*J+$*Y;for(var C=0;C>3)+C]}S+=Q,$+=j}v++,A+=M}if(B*L!=0)W+=L*(1+R);k=k+1}return G};P.decode._getBPP=function(q){var X=[1,null,3,1,2,null,4][q.ctype];return X*q.depth};P.decode._filterZero=function(q,X,V,K,Q){var Y=P.decode._getBPP(X),J=Math.ceil(K*Y/8),G=P.decode._paeth;Y=Math.ceil(Y/8);var W=0,Z=1,H=q[V],U=0;if(H>1)q[V]=[0,0,1][H-2];if(H==3)for(U=Y;U>>1)&255;for(var z=0;z>>1);for(;U>>1)}else{for(;U>8&255,q[X+1]=V&255},readUint:function(q,X){return q[X]*16777216+(q[X+1]<<16|q[X+2]<<8|q[X+3])},writeUint:function(q,X,V){q[X]=V>>24&255,q[X+1]=V>>16&255,q[X+2]=V>>8&255,q[X+3]=V&255},readASCII:function(q,X,V){var K="";for(var Q=0;Q=0&&G>=0)U=k*X+M<<2,z=(G+k)*Q+J+M<<2;else U=(-G+k)*X-J+M<<2,z=k*Q+M<<2;if(W==0)K[z]=q[U],K[z+1]=q[U+1],K[z+2]=q[U+2],K[z+3]=q[U+3];else if(W==1){var j=q[U+3]*0.00392156862745098,B=q[U]*j,L=q[U+1]*j,O=q[U+2]*j,N=K[z+3]*0.00392156862745098,R=K[z]*N,v=K[z+1]*N,A=K[z+2]*N,$=1-j,S=j+N*$,h=S==0?0:1/S;K[z+3]=255*S,K[z+0]=(B+R*$)*h,K[z+1]=(L+v*$)*h,K[z+2]=(O+A*$)*h}else if(W==2){var j=q[U+3],B=q[U],L=q[U+1],O=q[U+2],N=K[z+3],R=K[z],v=K[z+1],A=K[z+2];if(j==N&&B==R&&L==v&&O==A)K[z]=0,K[z+1]=0,K[z+2]=0,K[z+3]=0;else K[z]=B,K[z+1]=L,K[z+2]=O,K[z+3]=j}else if(W==3){var j=q[U+3],B=q[U],L=q[U+1],O=q[U+2],N=K[z+3],R=K[z],v=K[z+1],A=K[z+2];if(j==N&&B==R&&L==v&&O==A)continue;if(j<220&&N>20)return!1}}return!0};P.encode=function(q,X,V,K,Q,Y,J){if(K==null)K=0;if(J==null)J=!1;var G=P.encode.compress(q,X,V,K,[!1,!1,!1,0,J]);return P.encode.compressPNG(G,-1),P.encode._main(G,X,V,Q,Y)};P.encodeLL=function(q,X,V,K,Q,Y,J,G){var W={ctype:0+(K==1?0:2)+(Q==0?0:4),depth:Y,frames:[]},Z=Date.now(),H=(K+Q)*Y,U=H*X;for(var z=0;z1,U=!1,z=33+(H?20:0);if(Q.sRGB!=null)z+=13;if(Q.pHYs!=null)z+=21;if(q.ctype==3){var k=q.plte.length;for(var M=0;M>>24!=255)U=!0;z+=8+k*3+4+(U?8+k*1+4:0)}for(var j=0;j>>8&255,$=R>>>16&255;L[Z+N+0]=v,L[Z+N+1]=A,L[Z+N+2]=$}if(Z+=k*3,J(L,Z,Y(L,Z-k*3-4,k*3+4)),Z+=4,U){J(L,Z,k),Z+=4,W(L,Z,"tRNS"),Z+=4;for(var M=0;M>>24&255;Z+=k,J(L,Z,Y(L,Z-k-4,k+4)),Z+=4}}var S=0;for(var j=0;j>2,D>>2));for(var k=0;kq0&&r==u[B-q0])J0[B]=J0[B-q0];else{var I0=N[r];if(I0==null){if(N[r]=I0=R.length,R.push(r),R.length>=300)break}J0[B]=I0}}}var n0=R.length;if(n0<=256&&Z==!1){if(n0<=2)U=1;else if(n0<=4)U=2;else if(n0<=16)U=4;else U=8;U=Math.max(U,W)}for(var k=0;k>1)]|=N1[y1+R0]<<4-(R0&1)*4;else if(U==2)for(var R0=0;R0>2)]|=N1[y1+R0]<<6-(R0&3)*2;else if(U==1)for(var R0=0;R0>3)]|=N1[y1+R0]<<7-(R0&7)*1}Z2=$2,H=3,bq=1}else if(L==!1&&O.length==1){var $2=new Uint8Array(q0*y2*3),pK=q0*y2;for(var B=0;B$)$=b;if(hS)S=h}}if($==-1)v=A=$=S=0;if(Q){if((v&1)==1)v--;if((A&1)==1)A--}var D=($-v+1)*(S-A+1);if(DB)B=R;if(vL)L=v}}if(B==-1)M=j=B=L=0;if(J){if((M&1)==1)M--;if((j&1)==1)j--}Y={x:M,y:j,width:B-M+1,height:L-j+1};var S=K[Q];if(S.rect=Y,S.blend=1,S.img=new Uint8Array(Y.width*Y.height*4),K[Q-1].dispose==0)P._copyTile(Z,X,V,S.img,Y.width,Y.height,-Y.x,-Y.y,0),P.encode._prepareDiff(z,X,V,S.img,Y);else P._copyTile(z,X,V,S.img,Y.width,Y.height,-Y.x,-Y.y,0)};P.encode._prepareDiff=function(q,X,V,K,Q){P._copyTile(q,X,V,K,Q.width,Q.height,-Q.x,-Q.y,2)};P.encode._filterZero=function(q,X,V,K,Q,Y,J){var G=[],W=[0,1,2,3,4];if(Y!=-1)W=[Y];else if(X*K>500000||V==1)W=[0];var Z;if(J)Z={level:0};var H=J&&UZIP!=null?UZIP:kK.default;for(var U=0;U>1)+256&255;if(Y==4)for(var Z=Q;Z>1)&255;for(var Z=Q;Z>1)&255}if(Y==4){for(var Z=0;Z>>1;else V=V>>>1;q[X]=V}return q}(),update:function(q,X,V,K){for(var Q=0;Q>>8;return q},crc:function(q,X,V){return P.crc.update(4294967295,q,X,V)^4294967295}};P.quantize=function(q,X){var V=new Uint8Array(q),K=V.slice(0),Q=new Uint32Array(K.buffer),Y=P.quantize.getKDtree(K,X),J=Y[0],G=Y[1],W=P.quantize.planeDst,Z=V,H=Q,U=Z.length,z=new Uint8Array(V.length>>2);for(var k=0;k>2]=O.ind,H[k>>2]=O.est.rgba}return{abuf:K.buffer,inds:z,plte:G}};P.quantize.getKDtree=function(q,X,V){if(V==null)V=0.0001;var K=new Uint32Array(q.buffer),Q={i0:0,i1:q.length,bst:null,est:null,tdst:0,left:null,right:null};Q.bst=P.quantize.stats(q,Q.i0,Q.i1),Q.est=P.quantize.estats(Q.bst);var Y=[Q];while(Y.lengthJ)J=Y[W].est.L,G=W;if(J=H||Z.i1<=H;if(U){Z.est.L=0;continue}var z={i0:Z.i0,i1:H,bst:null,est:null,tdst:0,left:null,right:null};z.bst=P.quantize.stats(q,z.i0,z.i1),z.est=P.quantize.estats(z.bst);var k={i0:H,i1:Z.i1,bst:null,est:null,tdst:0,left:null,right:null};k.bst={R:[],m:[],N:Z.bst.N-z.bst.N};for(var W=0;W<16;W++)k.bst.R[W]=Z.bst.R[W]-z.bst.R[W];for(var W=0;W<4;W++)k.bst.m[W]=Z.bst.m[W]-z.bst.m[W];k.est=P.quantize.estats(k.bst),Z.left=z,Z.right=k,Y[G]=z,Y.push(k)}Y.sort(function(M,j){return j.bst.N-M.bst.N});for(var W=0;W0)J=q.right,G=q.left;var W=P.quantize.getNearest(J,X,V,K,Q);if(W.tdst<=Y*Y)return W;var Z=P.quantize.getNearest(G,X,V,K,Q);return Z.tdstY)K-=4;if(V>=K)break;var W=X[V>>2];X[V>>2]=X[K>>2],X[K>>2]=W,V+=4,K-=4}while(J(q,V,Q)>Y)V-=4;return V+4};P.quantize.vecDot=function(q,X,V){return q[X]*V[0]+q[X+1]*V[1]+q[X+2]*V[2]+q[X+3]*V[3]};P.quantize.stats=function(q,X,V){var K=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],Q=[0,0,0,0],Y=V-X>>2;for(var J=X;J>>0}};P.M4={multVec:function(q,X){return[q[0]*X[0]+q[1]*X[1]+q[2]*X[2]+q[3]*X[3],q[4]*X[0]+q[5]*X[1]+q[6]*X[2]+q[7]*X[3],q[8]*X[0]+q[9]*X[1]+q[10]*X[2]+q[11]*X[3],q[12]*X[0]+q[13]*X[1]+q[14]*X[2]+q[15]*X[3]]},dot:function(q,X){return q[0]*X[0]+q[1]*X[1]+q[2]*X[2]+q[3]*X[3]},sml:function(q,X){return[q*X[0],q*X[1],q*X[2],q*X[3]]}};P.encode.concatRGBA=function(q){var X=0;for(var V=0;V1)throw Error("Animated PNGs are not supported");var Q=new Uint8Array(K[0]),Y=lG(Q),J=Y.rgbChannel,G=Y.alphaChannel;this.rgbChannel=J;var W=G.some(function(Z){return Z<255});if(W)this.alphaChannel=G;this.type=fG(V.ctype),this.width=V.width,this.height=V.height,this.bitsPerComponent=8}return q.load=function(X){return new q(X)},q}();var _G=function(){function q(X){this.image=X,this.bitsPerComponent=X.bitsPerComponent,this.width=X.width,this.height=X.height,this.colorSpace="DeviceRGB"}return q.for=function(X){return _(this,void 0,void 0,function(){var V;return c(this,function(K){return V=IK.load(X),[2,new q(V)]})})},q.prototype.embedIntoContext=function(X,V){return _(this,void 0,void 0,function(){var K,Q;return c(this,function(Y){if(K=this.embedAlphaChannel(X),Q=X.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:K}),V)return X.assign(V,Q),[2,V];else return[2,X.register(Q)];return[2]})})},q.prototype.embedAlphaChannel=function(X){if(!this.image.alphaChannel)return;var V=X.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return X.register(V)},q}(),X8=_G;var cG=function(){function q(X,V,K){this.bytes=X,this.start=V||0,this.pos=this.start,this.end=!!V&&!!K?V+K:this.bytes.length}return Object.defineProperty(q.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(q.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),q.prototype.getByte=function(){if(this.pos>=this.end)return-1;return this.bytes[this.pos++]},q.prototype.getUint16=function(){var X=this.getByte(),V=this.getByte();if(X===-1||V===-1)return-1;return(X<<8)+V},q.prototype.getInt32=function(){var X=this.getByte(),V=this.getByte(),K=this.getByte(),Q=this.getByte();return(X<<24)+(V<<16)+(K<<8)+Q},q.prototype.getBytes=function(X,V){if(V===void 0)V=!1;var K=this.bytes,Q=this.pos,Y=this.end;if(!X){var J=K.subarray(Q,Y);return V?new Uint8ClampedArray(J):J}else{var G=Q+X;if(G>Y)G=Y;this.pos=G;var J=K.subarray(Q,G);return V?new Uint8ClampedArray(J):J}},q.prototype.peekByte=function(){var X=this.getByte();return this.pos--,X},q.prototype.peekBytes=function(X,V){if(V===void 0)V=!1;var K=this.getBytes(X,V);return this.pos-=K.length,K},q.prototype.skip=function(X){if(!X)X=1;this.pos+=X},q.prototype.reset=function(){this.pos=this.start},q.prototype.moveStart=function(){this.start=this.pos},q.prototype.makeSubStream=function(X,V){return new q(this.bytes,X,V)},q.prototype.decode=function(){return this.bytes},q}(),Hq=cG;var pG=new Uint8Array(0),dG=function(){function q(X){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=pG,this.minBufferLength=512,X)while(this.minBufferLengthY)K=Y}else{while(!this.eof)this.readBlock();K=this.bufferLength}this.pos=K;var J=this.buffer.subarray(Q,K);return V&&!(J instanceof Uint8ClampedArray)?new Uint8ClampedArray(J):J},q.prototype.peekByte=function(){var X=this.getByte();return this.pos--,X},q.prototype.peekBytes=function(X,V){if(V===void 0)V=!1;var K=this.getBytes(X,V);return this.pos-=K.length,K},q.prototype.skip=function(X){if(!X)X=1;this.pos+=X},q.prototype.reset=function(){this.pos=0},q.prototype.makeSubStream=function(X,V){var K=X+V;while(this.bufferLength<=K&&!this.eof)this.readBlock();return new Hq(this.buffer,X,V)},q.prototype.decode=function(){while(!this.eof)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},q.prototype.readBlock=function(){throw new u0(this.constructor.name,"readBlock")},q.prototype.ensureBuffer=function(X){var V=this.buffer;if(X<=V.byteLength)return V;var K=this.minBufferLength;while(K=0;--Z)W[G+Z]=U&255,U>>=8}},X}(d2),jK=nG;var rG=function(q){w(X,q);function X(V,K){var Q=q.call(this,K)||this;if(Q.stream=V,Q.firstDigit=-1,K)K=0.5*K;return Q}return X.prototype.readBlock=function(){var V=8000,K=this.stream.getBytes(V);if(!K.length){this.eof=!0;return}var Q=K.length+1>>1,Y=this.ensureBuffer(this.bufferLength+Q),J=this.bufferLength,G=this.firstDigit;for(var W=0,Z=K.length;W=48&&H<=57)U=H&15;else if(H>=65&&H<=70||H>=97&&H<=102)U=(H&15)+9;else if(H===62){this.eof=!0;break}else continue;if(G<0)G=U;else Y[J++]=G<<4|U,G=-1}if(G>=0&&this.eof)Y[J++]=G<<4,G=-1;this.firstDigit=G,this.bufferLength=J},X}(d2),LK=rG;var BK=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),iG=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),aG=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),oG=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,590000,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],sG=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],tG=function(q){w(X,q);function X(V,K){var Q=q.call(this,K)||this;Q.stream=V;var Y=V.getByte(),J=V.getByte();if(Y===-1||J===-1)throw Error("Invalid header in flate stream: "+Y+", "+J);if((Y&15)!==8)throw Error("Unknown compression method in flate stream: "+Y+", "+J);if(((Y<<8)+J)%31!==0)throw Error("Bad FCHECK in flate stream: "+Y+", "+J);if(J&32)throw Error("FDICT bit set in flate stream: "+Y+", "+J);return Q.codeSize=0,Q.codeBuf=0,Q}return X.prototype.readBlock=function(){var V,K,Q=this.stream,Y=this.getBits(3);if(Y&1)this.eof=!0;if(Y>>=1,Y===0){var J=void 0;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");var G=J;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");if(G|=J<<8,(J=Q.getByte())===-1)throw Error("Bad block header in flate stream");var W=J;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");if(W|=J<<8,W!==(~G&65535)&&(G!==0||W!==0))throw Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var Z=this.bufferLength;V=this.ensureBuffer(Z+G);var H=Z+G;if(this.bufferLength=H,G===0){if(Q.peekByte()===-1)this.eof=!0}else for(var U=Z;U0)v[O++]=S}z=this.generateHuffmanTable(v.subarray(0,M)),k=this.generateHuffmanTable(v.subarray(M,R))}else throw Error("Unknown block type in flate stream");V=this.buffer;var C=V?V.length:0,D=this.bufferLength;while(!0){var l=this.getCode(z);if(l<256){if(D+1>=C)V=this.ensureBuffer(D+1),C=V.length;V[D++]=l;continue}if(l===256){this.bufferLength=D;return}l-=257,l=iG[l];var u=l>>16;if(u>0)u=this.getBits(u);if(K=(l&65535)+u,l=this.getCode(k),l=aG[l],u=l>>16,u>0)u=this.getBits(u);var q0=(l&65535)+u;if(D+K>=C)V=this.ensureBuffer(D+K),C=V.length;for(var J0=0;J0>V,this.codeSize=Q-=V,J},X.prototype.getCode=function(V){var K=this.stream,Q=V[0],Y=V[1],J=this.codeSize,G=this.codeBuf,W;while(J>16,U=Z&65535;if(H<1||J>H,this.codeSize=J-H,U},X.prototype.generateHuffmanTable=function(V){var K=V.length,Q=0,Y;for(Y=0;YQ)Q=V[Y];var J=1<>=1;for(Y=z;Y0;if(!v||v<256)B[0]=v,L=1;else if(v>=258)if(v=0;J--)B[J]=U[G],G=k[G]}else B[L++]=B[0];else if(v===256){M=9,H=258,L=0;continue}else{this.eof=!0,delete this.lzwState;break}if(A)k[H]=j,z[H]=z[j]+1,U[H]=B[0],H++,M=H+Z&H+Z-1?M:Math.min(Math.log(H+Z)/0.6931471805599453+1,12)|0;if(j=v,O+=L,K>>K&(1<0){var J=this.stream.getBytes(Y);K.set(J,Q),Q+=Y}}else{Y=257-Y;var G=V[1];K=this.ensureBuffer(Q+Y+1);for(var W=0;WK.size())throw new Y5(V,0,K.size());K.remove(V)}},X.prototype.normalizedEntries=function(){var V=this.Kids();if(!V)V=this.dict.context.obj([this.ref]),this.dict.set(I.of("Kids"),V);return{Kids:V}},X.fromDict=function(V,K){return new X(V,K)},X}(Y8),K2=UZ;var zZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.Opt=function(){return this.dict.lookupMaybe(I.of("Opt"),K0,g,i)},X.prototype.setOpt=function(V){this.dict.set(I.of("Opt"),this.dict.context.obj(V))},X.prototype.getExportValues=function(){var V=this.Opt();if(!V)return;if(V instanceof K0||V instanceof g)return[V];var K=[];for(var Q=0,Y=V.size();QK.size())throw new Y5(V,0,K.size());K.remove(V)}},X.prototype.normalizeExportValues=function(){var V,K,Q,Y,J=(V=this.getExportValues())!==null&&V!==void 0?V:[],G=[],W=this.getWidgets();for(var Z=0,H=W.length;Z1){if(!this.hasFlag(G0.MultiSelect))throw new W7;this.dict.set(I.of("V"),this.dict.context.obj(V))}this.updateSelectedIndices(V)},X.prototype.valuesAreValid=function(V){var K=this.getOptions(),Q=function(W,Z){var H=V[W].decodeText();if(!K.find(function(U){return H===(U.display||U.value).decodeText()}))return{value:!1}};for(var Y=0,J=V.length;Y1){var K=Array(V.length),Q=this.getOptions(),Y=function(W,Z){var H=V[W].decodeText();K[W]=Q.findIndex(function(U){return H===(U.display||U.value).decodeText()})};for(var J=0,G=V.length;J0){var G=J.lookup(0,K0,g),W=J.lookupMaybe(1,K0,g);K.push({value:G,display:W||G})}}}return K}return[]},X}(K2),G8=kZ;var IZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Ch",Ff:G0.Combo,Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(G8),Q6=IZ;var EZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.addField=function(V){var K=this.normalizedEntries().Kids;K===null||K===void 0||K.push(V)},X.prototype.normalizedEntries=function(){var V=this.Kids();if(!V)V=this.dict.context.obj([]),this.dict.set(I.of("Kids"),V);return{Kids:V}},X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({}),Q=V.register(K);return new X(K,Q)},X}(Y8),Y6=EZ;var jZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X}(K2),F6=jZ;var LZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.MaxLen=function(){var V=this.dict.lookup(I.of("MaxLen"));if(V instanceof x)return V;return},X.prototype.Q=function(){var V=this.dict.lookup(I.of("Q"));if(V instanceof x)return V;return},X.prototype.setMaxLength=function(V){this.dict.set(I.of("MaxLen"),x.of(V))},X.prototype.removeMaxLength=function(){this.dict.delete(I.of("MaxLen"))},X.prototype.getMaxLength=function(){var V;return(V=this.MaxLen())===null||V===void 0?void 0:V.asNumber()},X.prototype.setQuadding=function(V){this.dict.set(I.of("Q"),x.of(V))},X.prototype.getQuadding=function(){var V;return(V=this.Q())===null||V===void 0?void 0:V.asNumber()},X.prototype.setValue=function(V){this.dict.set(I.of("V"),V)},X.prototype.removeValue=function(){this.dict.delete(I.of("V"))},X.prototype.getValue=function(){var V=this.V();if(V instanceof K0||V instanceof g)return V;return},X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Tx",Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(K2),J6=LZ;var BZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Btn",Ff:f0.PushButton,Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(h6),G6=BZ;var TZ=function(q){w(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.setValue=function(V){var K=this.getOnValues();if(!K.includes(V)&&V!==I.of("Off"))throw new J5;this.dict.set(I.of("V"),V);var Q=this.getWidgets();for(var Y=0,J=Q.length;YY)throw new qq(K,Y);var J=K;for(var G=0,W=Q.size();GJ)return H.insertLeafNode(V,J)||Z;else J-=H.Count().asNumber();if(H instanceof _0)J-=1}if(J===0){this.insertLeafKid(Q.size(),V);return}throw new Xq(K,"insertLeafNode")},X.prototype.removeLeafNode=function(V,K){if(K===void 0)K=!0;var Q=this.Kids(),Y=this.Count().asNumber();if(V>=Y)throw new qq(V,Y);var J=V;for(var G=0,W=Q.size();GJ){if(H.removeLeafNode(J,K),K&&H.Kids().size()===0)Q.remove(G);return}else J-=H.Count().asNumber();if(H instanceof _0)if(J===0){this.removeKid(G);return}else J-=1}throw new Xq(V,"removeLeafNode")},X.prototype.ascend=function(V){V(this);var K=this.Parent();if(K)K.ascend(V)},X.prototype.traverse=function(V){var K=this.Kids();for(var Q=0,Y=K.size();QNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var Q="Parsed number that is too large for some PDF readers: "+X+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(Q),Number.MAX_SAFE_INTEGER}else{var Q="Parsed number that is too large for some PDF readers: "+X+", not capping.";console.warn(Q)}return K},q.prototype.skipWhitespace=function(){while(!this.bytes.done()&&k2[this.bytes.peek()])this.bytes.next()},q.prototype.skipLine=function(){while(!this.bytes.done()){var X=this.bytes.peek();if(X===wK||X===NK)return;this.bytes.next()}},q.prototype.skipComment=function(){if(this.bytes.peek()!==E.Percent)return!1;while(!this.bytes.done()){var X=this.bytes.peek();if(X===wK||X===NK)return!0;this.bytes.next()}return!0},q.prototype.skipWhitespaceAndComments=function(){this.skipWhitespace();while(this.skipComment())this.skipWhitespace()},q.prototype.matchKeyword=function(X){var V=this.bytes.offset();for(var K=0,Q=X.length;K=this.length},q.prototype.offset=function(){return this.idx},q.prototype.slice=function(X,V){return this.bytes.slice(X,V)},q.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},q.of=function(X){return new q(X)},q.fromPDFRawStream=function(X){return q.of(V8(X).decode())},q}(),D6=CZ;var hZ=E.Space,U1=E.CarriageReturn,z1=E.Newline,M1=[E.s,E.t,E.r,E.e,E.a,E.m],Eq=[E.e,E.n,E.d,E.s,E.t,E.r,E.e,E.a,E.m],M0={header:[E.Percent,E.P,E.D,E.F,E.Dash],eof:[E.Percent,E.Percent,E.E,E.O,E.F],obj:[E.o,E.b,E.j],endobj:[E.e,E.n,E.d,E.o,E.b,E.j],xref:[E.x,E.r,E.e,E.f],trailer:[E.t,E.r,E.a,E.i,E.l,E.e,E.r],startxref:[E.s,E.t,E.a,E.r,E.t,E.x,E.r,E.e,E.f],true:[E.t,E.r,E.u,E.e],false:[E.f,E.a,E.l,E.s,E.e],null:[E.n,E.u,E.l,E.l],stream:M1,streamEOF1:Q0(M1,[hZ,U1,z1]),streamEOF2:Q0(M1,[U1,z1]),streamEOF3:Q0(M1,[U1]),streamEOF4:Q0(M1,[z1]),endstream:Eq,EOF1endstream:Q0([U1,z1],Eq),EOF2endstream:Q0([U1],Eq),EOF3endstream:Q0([z1],Eq)};var FZ=function(q){w(X,q);function X(V,K,Q){if(Q===void 0)Q=!1;var Y=q.call(this,V,Q)||this;return Y.context=K,Y}return X.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(M0.true))return c2.True;if(this.matchKeyword(M0.false))return c2.False;if(this.matchKeyword(M0.null))return F0;var V=this.bytes.peek();if(V===E.LessThan&&this.bytes.peekAhead(1)===E.LessThan)return this.parseDictOrStream();if(V===E.LessThan)return this.parseHexString();if(V===E.LeftParen)return this.parseString();if(V===E.ForwardSlash)return this.parseName();if(V===E.LeftSquareBracket)return this.parseArray();if(H1[V])return this.parseNumberOrRef();throw new M7(this.bytes.position(),V)},X.prototype.parseNumberOrRef=function(){var V=this.parseRawNumber();this.skipWhitespaceAndComments();var K=this.bytes.offset();if(P0[this.bytes.peek()]){var Q=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===E.R)return this.bytes.assertNext(E.R),a.of(V,Q)}return this.bytes.moveTo(K),x.of(V)},X.prototype.parseHexString=function(){var V="";this.bytes.assertNext(E.LessThan);while(!this.bytes.done()&&this.bytes.peek()!==E.GreaterThan)V+=t0(this.bytes.next());return this.bytes.assertNext(E.GreaterThan),g.of(V)},X.prototype.parseString=function(){var V=0,K=!1,Q="";while(!this.bytes.done()){var Y=this.bytes.next();if(Q+=t0(Y),!K){if(Y===E.LeftParen)V+=1;if(Y===E.RightParen)V-=1}if(Y===E.BackSlash)K=!K;else if(K)K=!1;if(V===0)return K0.of(Q.substring(1,Q.length-1))}throw new E7(this.bytes.position())},X.prototype.parseName=function(){this.bytes.assertNext(E.ForwardSlash);var V="";while(!this.bytes.done()){var K=this.bytes.peek();if(k2[K]||V2[K])break;V+=t0(K),this.bytes.next()}return I.of(V)},X.prototype.parseArray=function(){this.bytes.assertNext(E.LeftSquareBracket),this.skipWhitespaceAndComments();var V=i.withContext(this.context);while(this.bytes.peek()!==E.RightSquareBracket){var K=this.parseObject();V.push(K),this.skipWhitespaceAndComments()}return this.bytes.assertNext(E.RightSquareBracket),V},X.prototype.parseDict=function(){this.bytes.assertNext(E.LessThan),this.bytes.assertNext(E.LessThan),this.skipWhitespaceAndComments();var V=new Map;while(!this.bytes.done()&&this.bytes.peek()!==E.GreaterThan&&this.bytes.peekAhead(1)!==E.GreaterThan){var K=this.parseName(),Q=this.parseObject();V.set(K,Q),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(E.GreaterThan),this.bytes.assertNext(E.GreaterThan);var Y=V.get(I.of("Type"));if(Y===I.of("Catalog"))return W8.fromMapWithContext(V,this.context);else if(Y===I.of("Pages"))return H8.fromMapWithContext(V,this.context);else if(Y===I.of("Page"))return _0.fromMapWithContext(V,this.context);else return m.fromMapWithContext(V,this.context)},X.prototype.parseDictOrStream=function(){var V=this.bytes.position(),K=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(M0.streamEOF1)&&!this.matchKeyword(M0.streamEOF2)&&!this.matchKeyword(M0.streamEOF3)&&!this.matchKeyword(M0.streamEOF4)&&!this.matchKeyword(M0.stream))return K;var Q=this.bytes.offset(),Y,J=K.get(I.of("Length"));if(J instanceof x){if(Y=Q+J.asNumber(),this.bytes.moveTo(Y),this.skipWhitespaceAndComments(),!this.matchKeyword(M0.endstream))this.bytes.moveTo(Q),Y=this.findEndOfStreamFallback(V)}else Y=this.findEndOfStreamFallback(V);var G=this.bytes.slice(Q,Y);return w2.of(K,G)},X.prototype.findEndOfStreamFallback=function(V){var K=1,Q=this.bytes.offset();while(!this.bytes.done()){if(Q=this.bytes.offset(),this.matchKeyword(M0.stream))K+=1;else if(this.matchKeyword(M0.EOF1endstream)||this.matchKeyword(M0.EOF2endstream)||this.matchKeyword(M0.EOF3endstream)||this.matchKeyword(M0.endstream))K-=1;else this.bytes.next();if(K===0)break}if(K!==0)throw new I7(V);return Q},X.forBytes=function(V,K,Q){return new X(D6.of(V),K,Q)},X.forByteStream=function(V,K,Q){if(Q===void 0)Q=!1;return new X(V,K,Q)},X}(SK),U8=FZ;var PZ=function(q){w(X,q);function X(V,K){var Q=q.call(this,D6.fromPDFRawStream(V),V.dict.context)||this,Y=V.dict;return Q.alreadyParsed=!1,Q.shouldWaitForTick=K||function(){return!1},Q.firstOffset=Y.lookup(I.of("First"),x).asNumber(),Q.objectCount=Y.lookup(I.of("N"),x).asNumber(),Q}return X.prototype.parseIntoContext=function(){return _(this,void 0,void 0,function(){var V,K,Q,Y,J,G,W,Z;return c(this,function(H){switch(H.label){case 0:if(this.alreadyParsed)throw new Q5("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,V=this.parseOffsetsAndObjectNumbers(),K=0,Q=V.length,H.label=1;case 1:if(!(K=E.Space&&K<=E.Tilde;if(Q){if(this.matchKeyword(M0.xref)||this.matchKeyword(M0.trailer)||this.matchKeyword(M0.startxref)||this.matchIndirectObjectHeader()){this.bytes.moveTo(V);break}}this.bytes.next()}},X.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var V=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(V)}catch(K){this.bytes.next(),this.skipWhitespaceAndComments()}},X.forBytesWithOptions=function(V,K,Q,Y){return new X(V,K,Q,Y)},X}(U8),Bq=uZ;var n2=function(q){return 1<0)K[K.length]=+Q;V[V.length]={cmd:X,args:K},K=[],Q="",Y=!1}X=Z}else if([" ",","].includes(Z)||Z==="-"&&Q.length>0&&Q[Q.length-1]!=="e"||Z==="."&&Y){if(Q.length===0)continue;if(K.length===J){if(V[V.length]={cmd:X,args:K},K=[+Q],X==="M")X="L";if(X==="m")X="l"}else K[K.length]=+Q;Y=Z===".",Q=["-","."].includes(Z)?Z:""}else if(Q+=Z,Z===".")Y=!0}if(Q.length>0)if(K.length===J){if(V[V.length]={cmd:X,args:K},K=[+Q],X==="M")X="L";if(X==="m")X="l"}else K[K.length]=+Q;return V[V.length]={cmd:X,args:K},V},oZ=function(q){d=n=Z0=W0=v1=R1=0;var X=[];for(var V=0;V1)z=Math.sqrt(z),V*=z,K*=z;var k=U/V,M=H/V,j=-H/K,B=U/K,L=k*G+M*W,O=j*G+B*W,N=k*q+M*X,R=j*q+B*X,v=(N-L)*(N-L)+(R-O)*(R-O),A=1/v-0.25;if(A<0)A=0;var $=Math.sqrt(A);if(Y===Q)$=-$;var S=0.5*(L+N)-$*(R-O),h=0.5*(O+R)+$*(N-L),b=Math.atan2(O-h,L-S),C=Math.atan2(R-h,N-S),D=C-b;if(D<0&&Y===1)D+=2*Math.PI;else if(D>0&&Y===0)D-=2*Math.PI;var l=Math.ceil(Math.abs(D/(Math.PI*0.5+0.001))),u=[];for(var q0=0;q0q.length)return Q-1;var B=X.heightAtSize(Q),L=B+B*0.2,O=L*Y;if(O>Math.abs(V.height))return Q-1;Q+=1}return Q},K3=function(q,X,V,K){var Q=V.width/K,Y=V.height,J=mK,G=J4(q);while(JQ*0.75;if(U)return J-1}var z=X.heightAtSize(J,{descender:!1});if(z>Y)return J-1;J+=1}return J},Q3=function(q){for(var X=q.length;X>0;X--)if(/\s/.test(q[X]))return X;return},Y3=function(q,X,V,K){var Q,Y=q.length;while(Y>0){var J=q.substring(0,Y),G=V.encodeText(J),W=V.widthOfTextAtSize(J,K);if(Wz)z=$+v;if(M+G>k)k=M+G;Z.push({text:N,encoded:R,width:v,height:G,x:$,y:M}),L=A===null||A===void 0?void 0:A.trim()}}return{fontSize:K,lineHeight:W,lines:Z,bounds:{x:H,y:U,width:z-H,height:k-U}}},KX=function(q,X){var{fontSize:V,font:K,bounds:Q,cellCount:Y}=X,J=F1(k6(q));if(J.length>Y)throw new qX(J.length,Y);if(V===void 0||V===0)V=K3(J,K,Q,Y);var G=Q.width/Y,W=K.heightAtSize(V,{descender:!1}),Z=Q.y+(Q.height/2-W/2),H=[],U=Q.x,z=Q.y,k=Q.x+Q.width,M=Q.y+Q.height,j=0,B=0;while(jk)k=$+v;if(Z+W>M)M=Z+W;H.push({text:J,encoded:R,width:v,height:W,x:$,y:Z}),j+=1,B+=N}return{fontSize:V,cells:H,bounds:{x:U,y:z,width:k-U,height:M-z}}},v8=function(q,X){var{alignment:V,fontSize:K,font:Q,bounds:Y}=X,J=F1(k6(q));if(K===void 0||K===0)K=lK([J],Q,Y);var G=Q.encodeText(J),W=Q.widthOfTextAtSize(J,K),Z=Q.heightAtSize(K,{descender:!1}),H=V===v0.Left?Y.x:V===v0.Center?Y.x+Y.width/2-W/2:V===v0.Right?Y.x+Y.width-W:Y.x,U=Y.y+(Y.height/2-Z/2);return{fontSize:K,line:{text:J,encoded:G,width:W,height:Z,x:H,y:U},bounds:{x:H,y:U,width:W,height:Z}}};var G2=function(q){if("normal"in q)return q;return{normal:q}},J3=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,m6=function(q){var X,V,K=(X=q.getDefaultAppearance())!==null&&X!==void 0?X:"",Q=(V=F5(K,J3).match)!==null&&V!==void 0?V:[],Y=Number(Q[2]);return isFinite(Y)?Y:void 0},G3=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,L2=function(q){var X,V=(X=q.getDefaultAppearance())!==null&&X!==void 0?X:"",K=F5(V,G3).match,Q=K!==null&&K!==void 0?K:[],Y=Q[1],J=Q[2],G=Q[3],W=Q[4],Z=Q[5];if(Z==="g"&&Y)return Sq(Number(Y));if(Z==="rg"&&Y&&J&&G)return Y0(Number(Y),Number(J),Number(G));if(Z==="k"&&Y&&J&&G&&W)return yq(Number(Y),Number(J),Number(G),Number(W));return},B2=function(q,X,V,K){var Q;if(K===void 0)K=0;var Y=[E2(X).toString(),T5((Q=V===null||V===void 0?void 0:V.name)!==null&&Q!==void 0?Q:"dummy__noop",K).toString()].join(` -`);q.setDefaultAppearance(Y)},QX=function(q,X){var V,K,Q,Y=L2(X),J=L2(q.acroField),G=X.getRectangle(),W=X.getAppearanceCharacteristics(),Z=X.getBorderStyle(),H=(V=Z===null||Z===void 0?void 0:Z.getWidth())!==null&&V!==void 0?V:0,U=I2(W===null||W===void 0?void 0:W.getRotation()),z=r2(G,U),k=z.width,M=z.height,j=j2(o(o({},G),{rotation:U})),B=Y0(0,0,0),L=(K=l0(W===null||W===void 0?void 0:W.getBorderColor()))!==null&&K!==void 0?K:B,O=l0(W===null||W===void 0?void 0:W.getBackgroundColor()),N=l0(W===null||W===void 0?void 0:W.getBackgroundColor(),0.8),R=(Q=Y!==null&&Y!==void 0?Y:J)!==null&&Q!==void 0?Q:B;if(Y)B2(X,R);else B2(q.acroField,R);var v={x:0+H/2,y:0+H/2,width:k-H,height:M-H,thickness:1.5,borderWidth:H,borderColor:L,markColor:R};return{normal:{on:Q0(j,B8(o(o({},v),{color:O,filled:!0}))),off:Q0(j,B8(o(o({},v),{color:O,filled:!1})))},down:{on:Q0(j,B8(o(o({},v),{color:N,filled:!0}))),off:Q0(j,B8(o(o({},v),{color:N,filled:!1})))}}},YX=function(q,X){var V,K,Q,Y=L2(X),J=L2(q.acroField),G=X.getRectangle(),W=X.getAppearanceCharacteristics(),Z=X.getBorderStyle(),H=(V=Z===null||Z===void 0?void 0:Z.getWidth())!==null&&V!==void 0?V:0,U=I2(W===null||W===void 0?void 0:W.getRotation()),z=r2(G,U),k=z.width,M=z.height,j=j2(o(o({},G),{rotation:U})),B=Y0(0,0,0),L=(K=l0(W===null||W===void 0?void 0:W.getBorderColor()))!==null&&K!==void 0?K:B,O=l0(W===null||W===void 0?void 0:W.getBackgroundColor()),N=l0(W===null||W===void 0?void 0:W.getBackgroundColor(),0.8),R=(Q=Y!==null&&Y!==void 0?Y:J)!==null&&Q!==void 0?Q:B;if(Y)B2(X,R);else B2(q.acroField,R);var v={x:k/2,y:M/2,width:k-H,height:M-H,borderWidth:H,borderColor:L,dotColor:R};return{normal:{on:Q0(j,T8(o(o({},v),{color:O,filled:!0}))),off:Q0(j,T8(o(o({},v),{color:O,filled:!1})))},down:{on:Q0(j,T8(o(o({},v),{color:N,filled:!0}))),off:Q0(j,T8(o(o({},v),{color:N,filled:!1})))}}},JX=function(q,X,V){var K,Q,Y,J,G,W=L2(X),Z=L2(q.acroField),H=m6(X),U=m6(q.acroField),z=X.getRectangle(),k=X.getAppearanceCharacteristics(),M=X.getBorderStyle(),j=k===null||k===void 0?void 0:k.getCaptions(),B=(K=j===null||j===void 0?void 0:j.normal)!==null&&K!==void 0?K:"",L=(Y=(Q=j===null||j===void 0?void 0:j.down)!==null&&Q!==void 0?Q:B)!==null&&Y!==void 0?Y:"",O=(J=M===null||M===void 0?void 0:M.getWidth())!==null&&J!==void 0?J:0,N=I2(k===null||k===void 0?void 0:k.getRotation()),R=r2(z,N),v=R.width,A=R.height,$=j2(o(o({},z),{rotation:N})),S=Y0(0,0,0),h=l0(k===null||k===void 0?void 0:k.getBorderColor()),b=l0(k===null||k===void 0?void 0:k.getBackgroundColor()),C=l0(k===null||k===void 0?void 0:k.getBackgroundColor(),0.8),D={x:O,y:O,width:v-O*2,height:A-O*2},l=v8(B,{alignment:v0.Center,fontSize:H!==null&&H!==void 0?H:U,font:V,bounds:D}),u=v8(L,{alignment:v0.Center,fontSize:H!==null&&H!==void 0?H:U,font:V,bounds:D}),q0=Math.min(l.fontSize,u.fontSize),J0=(G=W!==null&&W!==void 0?W:Z)!==null&&G!==void 0?G:S;if(W||H!==void 0)B2(X,J0,V,q0);else B2(q.acroField,J0,V,q0);var r={x:0+O/2,y:0+O/2,width:v-O,height:A-O,borderWidth:O,borderColor:h,textColor:J0,font:V.name,fontSize:q0};return{normal:Q0($,hq(o(o({},r),{color:b,textLines:[l.line]}))),down:Q0($,hq(o(o({},r),{color:C,textLines:[u.line]})))}},GX=function(q,X,V){var K,Q,Y,J,G=L2(X),W=L2(q.acroField),Z=m6(X),H=m6(q.acroField),U=X.getRectangle(),z=X.getAppearanceCharacteristics(),k=X.getBorderStyle(),M=(K=q.getText())!==null&&K!==void 0?K:"",j=(Q=k===null||k===void 0?void 0:k.getWidth())!==null&&Q!==void 0?Q:0,B=I2(z===null||z===void 0?void 0:z.getRotation()),L=r2(U,B),O=L.width,N=L.height,R=j2(o(o({},U),{rotation:B})),v=Y0(0,0,0),A=l0(z===null||z===void 0?void 0:z.getBorderColor()),$=l0(z===null||z===void 0?void 0:z.getBackgroundColor()),S,h,b=q.isCombed()?0:1,C={x:j+b,y:j+b,width:O-(j+b)*2,height:N-(j+b)*2};if(q.isMultiline()){var D=uq(M,{alignment:q.getAlignment(),fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C});S=D.lines,h=D.fontSize}else if(q.isCombed()){var D=KX(M,{fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C,cellCount:(Y=q.getMaxLength())!==null&&Y!==void 0?Y:0});S=D.cells,h=D.fontSize}else{var D=v8(M,{alignment:q.getAlignment(),fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C});S=[D.line],h=D.fontSize}var l=(J=G!==null&&G!==void 0?G:W)!==null&&J!==void 0?J:v;if(G||Z!==void 0)B2(X,l,V,h);else B2(q.acroField,l,V,h);var u={x:0+j/2,y:0+j/2,width:O-j,height:N-j,borderWidth:j!==null&&j!==void 0?j:0,borderColor:A,textColor:l,font:V.name,fontSize:h,color:$,textLines:S,padding:b};return Q0(R,Pq(u))},ZX=function(q,X,V){var K,Q,Y,J=L2(X),G=L2(q.acroField),W=m6(X),Z=m6(q.acroField),H=X.getRectangle(),U=X.getAppearanceCharacteristics(),z=X.getBorderStyle(),k=(K=q.getSelected()[0])!==null&&K!==void 0?K:"",M=(Q=z===null||z===void 0?void 0:z.getWidth())!==null&&Q!==void 0?Q:0,j=I2(U===null||U===void 0?void 0:U.getRotation()),B=r2(H,j),L=B.width,O=B.height,N=j2(o(o({},H),{rotation:j})),R=Y0(0,0,0),v=l0(U===null||U===void 0?void 0:U.getBorderColor()),A=l0(U===null||U===void 0?void 0:U.getBackgroundColor()),$=1,S={x:M+$,y:M+$,width:L-(M+$)*2,height:O-(M+$)*2},h=v8(k,{alignment:v0.Left,fontSize:W!==null&&W!==void 0?W:Z,font:V,bounds:S}),b=h.line,C=h.fontSize,D=(Y=J!==null&&J!==void 0?J:G)!==null&&Y!==void 0?Y:R;if(J||W!==void 0)B2(X,D,V,C);else B2(q.acroField,D,V,C);var l={x:0+M/2,y:0+M/2,width:L-M,height:O-M,borderWidth:M!==null&&M!==void 0?M:0,borderColor:v,textColor:D,font:V.name,fontSize:C,color:A,textLines:[b],padding:$};return Q0(N,Pq(l))},WX=function(q,X,V){var K,Q,Y=L2(X),J=L2(q.acroField),G=m6(X),W=m6(q.acroField),Z=X.getRectangle(),H=X.getAppearanceCharacteristics(),U=X.getBorderStyle(),z=(K=U===null||U===void 0?void 0:U.getWidth())!==null&&K!==void 0?K:0,k=I2(H===null||H===void 0?void 0:H.getRotation()),M=r2(Z,k),j=M.width,B=M.height,L=j2(o(o({},Z),{rotation:k})),O=Y0(0,0,0),N=l0(H===null||H===void 0?void 0:H.getBorderColor()),R=l0(H===null||H===void 0?void 0:H.getBackgroundColor()),v=q.getOptions(),A=q.getSelected();if(q.isSorted())v.sort();var $="";for(var S=0,h=v.length;S1||Q.length===1&&K)this.enableMultiselect();var G=Array(Q.length);for(var W=0,Z=Q.length;W1||Q.length===1&&K)this.enableMultiselect();var J=Array(Q.length);for(var G=0,W=Q.length;GK)throw new XX(V.length,K,this.getName());if(this.markAsDirty(),this.disableRichFormatting(),V)this.acroField.setValue(g.fromText(V));else this.acroField.removeValue()},X.prototype.getAlignment=function(){var V=this.acroField.getQuadding();return V===0?v0.Left:V===1?v0.Center:V===2?v0.Right:v0.Left},X.prototype.setAlignment=function(V){M2(V,"alignment",v0),this.markAsDirty(),this.acroField.setQuadding(V)},X.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},X.prototype.setMaxLength=function(V){if(X2(V,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),V===void 0)this.acroField.removeMaxLength();else{var K=this.getText();if(K&&K.length>V)throw new VX(K.length,V,this.getName());this.acroField.setMaxLength(V)}},X.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},X.prototype.setImage=function(V){var K=this.getAlignment(),Q=K===v0.Center?T2.Center:K===v0.Right?T2.Right:T2.Left,Y=this.acroField.getWidgets();for(var J=0,G=Y.length;J"u")globalThis.Buffer=y;if(typeof globalThis.process>"u")globalThis.process=N3;globalThis.__bundles=globalThis.__bundles||{};globalThis.__bundles["pdf-lib"]=UX;})(); +end`},HK=function(){var q=[];for(var X=0;X"},Gq=function(q){return D2(q,4)},FG=function(q){if(j4(q))return Gq(q);if(L4(q)){var X=D1(q),V=u1(q);return""+Gq(X)+Gq(V)}var K=u2(q),Q="0x"+K+" is not a valid UTF-8 or UTF-16 codepoint.";throw Error(Q)};var PG=function(q){var X=0,V=function(K){X|=1<=E.Zero&&Z<=E.Seven){if(K+=W,K.length===3||!(H>="0"&&H<="7"))Y(parseInt(K,8)),K=""}else Y(Z)}return new Uint8Array(V)},X.prototype.decodeText=function(){var V=this.asBytes();if(b8(V))return x8(V);return J1(V)},X.prototype.decodeDate=function(){var V=this.decodeText(),K=P8(V);if(!K)throw new G1(V);return K},X.prototype.asString=function(){return this.value},X.prototype.clone=function(){return X.of(this.value)},X.prototype.toString=function(){return"("+this.value+")"},X.prototype.sizeInBytes=function(){return this.value.length+2},X.prototype.copyBytesInto=function(V,K){return V[K++]=E.LeftParen,K+=k0(this.value,V,K),V[K++]=E.RightParen,this.value.length+2},X.of=function(V){return new X(V)},X.fromDate=function(V){var K=e0(String(V.getUTCFullYear()),4,"0"),Q=e0(String(V.getUTCMonth()+1),2,"0"),Y=e0(String(V.getUTCDate()),2,"0"),J=e0(String(V.getUTCHours()),2,"0"),G=e0(String(V.getUTCMinutes()),2,"0"),W=e0(String(V.getUTCSeconds()),2,"0");return new X("D:"+K+Q+Y+J+G+W+"Z")},X}(z0),K0=DG;var uG=function(){function q(X,V,K,Q){var Y=this;this.allGlyphsInFontSortedById=function(){var J=Array(Y.font.characterSet.length);for(var G=0,W=J.length;G>3)]>>7-((M&7)<<0)&1,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?w[C]:255}}if(H==2)for(var S=0;S>2)]>>6-((M&3)<<1)&3,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?w[C]:255}}if(H==4)for(var S=0;S>1)]>>4-((M&1)<<2)&15,D=3*C;G[R]=v[D],G[R+1]=v[D+1],G[R+2]=v[D+2],G[R+3]=C<$?w[C]:255}}if(H==8)for(var M=0;M>>3)]>>>7-(r&7)&1),I0=u==L*255?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==2)for(var r=0;r>>2)]>>>6-((r&3)<<1)&3),I0=u==L*85?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==4)for(var r=0;r>>1)]>>>4-((r&1)<<2)&15),I0=u==L*17?0:255;W[J0+r]=I0<<24|u<<16|u<<8|u}else if(H==8)for(var r=0;r>>2<<3);while(Q==0){if(Q=B(X,z,1),Y=B(X,z+1,2),z+=3,Y==0){if((z&7)!=0)z+=8-(z&7);var S=(z>>>3)+4,h=X[S-4]|X[S-3]<<8;if($)V=q.H.W(V,U+h);V.set(new K(X.buffer,X.byteOffset+S,h),U),z=S+h<<3,U+=h;continue}if($)V=q.H.W(V,U+131072);if(Y==1)k=w.J,M=w.h,Z=511,H=31;if(Y==2){J=L(X,z,5)+257,G=L(X,z+5,5)+1,W=L(X,z+10,4)+4,z+=14;var b=z,C=1;for(var D=0;D<38;D+=2)w.Q[D]=0,w.Q[D+1]=0;for(var D=0;DC)C=l}z+=3*W,N(w.Q,C),R(w.Q,C,w.u),k=w.w,M=w.d,z=O(w.u,(1<>>4;if(r>>>8==0)V[U++]=r;else if(r==256)break;else{var I0=U+r-254;if(r>264){var n0=w.q[r-257];I0=U+(n0>>>3)+L(X,z,n0&7),z+=n0&7}var N8=M[v(X,z)&H];z+=N8&15;var S8=N8>>>4,y2=w.c[S8],Z2=(y2>>>4)+B(X,z,y2&15);z+=y2&15;while(U>>4;if(U<=15)J[Z]=U,Z++;else{var z=0,k=0;if(U==16)k=3+G(Q,Y,2),Y+=2,z=J[Z-1];else if(U==17)k=3+G(Q,Y,3),Y+=3;else if(U==18)k=11+G(Q,Y,7),Y+=7;var M=Z+k;while(Z>>1;while(JY)Y=W;J++}while(J>1,Z=X[G+1],H=W<<4|Z,U=V-Z,z=X[G]<>>15-V;K[M]=H,z++}}},q.H.l=function(X,V){var K=q.H.m.r,Q=15-V;for(var Y=0;Y>>Q}},q.H.M=function(X,V,K){K=K<<(V&7);var Q=V>>>3;X[Q]|=K,X[Q+1]|=K>>>8},q.H.I=function(X,V,K){K=K<<(V&7);var Q=V>>>3;X[Q]|=K,X[Q+1]|=K>>>8,X[Q+2]|=K>>>16},q.H.e=function(X,V,K){return(X[V>>>3]|X[(V>>>3)+1]<<8)>>>(V&7)&(1<>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16)>>>(V&7)&(1<>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16)>>>(V&7)},q.H.i=function(X,V){return(X[V>>>3]|X[(V>>>3)+1]<<8|X[(V>>>3)+2]<<16|X[(V>>>3)+3]<<24)>>>(V&7)},q.H.m=function(){var X=Uint16Array,V=Uint32Array;return{K:new X(16),j:new X(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new X(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new V(32),J:new X(512),_:[],h:new X(32),$:[],w:new X(32768),C:[],v:[],d:new X(32768),D:[],u:new X(512),Q:[],r:new X(32768),s:new V(286),Y:new V(30),a:new V(19),t:new V(15000),k:new X(65536),g:new X(32768)}}(),function(){var X=q.H.m,V=32768;for(var K=0;K>>1|(Q&1431655765)<<1,Q=(Q&3435973836)>>>2|(Q&858993459)<<2,Q=(Q&4042322160)>>>4|(Q&252645135)<<4,Q=(Q&4278255360)>>>8|(Q&16711935)<<8,X.r[K]=(Q>>>16|Q<<16)>>>17}function Y(J,G,W){while(G--!=0)J.push(0,W)}for(var K=0;K<32;K++)X.q[K]=X.S[K]<<3|X.T[K],X.c[K]=X.p[K]<<4|X.z[K];Y(X._,144,8),Y(X._,112,9),Y(X._,24,7),Y(X._,8,8),q.H.n(X._,9),q.H.A(X._,9,X.J),q.H.l(X._,9),Y(X.$,32,5),q.H.n(X.$,5),q.H.A(X.$,5,X.h),q.H.l(X.$,5),Y(X.Q,19,0),Y(X.C,286,0),Y(X.D,30,0),Y(X.v,320,0)}(),q.H.N}();P.decode._readInterlace=function(q,X){var{width:V,height:K}=X,Q=P.decode._getBPP(X),Y=Q>>3,J=Math.ceil(V*Q/8),G=new Uint8Array(K*J),W=0,Z=[0,0,4,0,2,0,1],H=[0,4,0,2,0,1,0],U=[8,8,8,4,4,2,2],z=[8,8,4,4,2,2,1],k=0;while(k<7){var M=U[k],j=z[k],B=0,L=0,O=Z[k];while(O>3];h=h>>7-(S&7)&1,G[w*J+($>>3)]|=h<<7-(($&7)<<0)}if(Q==2){var h=q[S>>3];h=h>>6-(S&7)&3,G[w*J+($>>2)]|=h<<6-(($&3)<<1)}if(Q==4){var h=q[S>>3];h=h>>4-(S&7)&15,G[w*J+($>>1)]|=h<<4-(($&1)<<2)}if(Q>=8){var b=w*J+$*Y;for(var C=0;C>3)+C]}S+=Q,$+=j}v++,w+=M}if(B*L!=0)W+=L*(1+R);k=k+1}return G};P.decode._getBPP=function(q){var X=[1,null,3,1,2,null,4][q.ctype];return X*q.depth};P.decode._filterZero=function(q,X,V,K,Q){var Y=P.decode._getBPP(X),J=Math.ceil(K*Y/8),G=P.decode._paeth;Y=Math.ceil(Y/8);var W=0,Z=1,H=q[V],U=0;if(H>1)q[V]=[0,0,1][H-2];if(H==3)for(U=Y;U>>1)&255;for(var z=0;z>>1);for(;U>>1)}else{for(;U>8&255,q[X+1]=V&255},readUint:function(q,X){return q[X]*16777216+(q[X+1]<<16|q[X+2]<<8|q[X+3])},writeUint:function(q,X,V){q[X]=V>>24&255,q[X+1]=V>>16&255,q[X+2]=V>>8&255,q[X+3]=V&255},readASCII:function(q,X,V){var K="";for(var Q=0;Q=0&&G>=0)U=k*X+M<<2,z=(G+k)*Q+J+M<<2;else U=(-G+k)*X-J+M<<2,z=k*Q+M<<2;if(W==0)K[z]=q[U],K[z+1]=q[U+1],K[z+2]=q[U+2],K[z+3]=q[U+3];else if(W==1){var j=q[U+3]*0.00392156862745098,B=q[U]*j,L=q[U+1]*j,O=q[U+2]*j,N=K[z+3]*0.00392156862745098,R=K[z]*N,v=K[z+1]*N,w=K[z+2]*N,$=1-j,S=j+N*$,h=S==0?0:1/S;K[z+3]=255*S,K[z+0]=(B+R*$)*h,K[z+1]=(L+v*$)*h,K[z+2]=(O+w*$)*h}else if(W==2){var j=q[U+3],B=q[U],L=q[U+1],O=q[U+2],N=K[z+3],R=K[z],v=K[z+1],w=K[z+2];if(j==N&&B==R&&L==v&&O==w)K[z]=0,K[z+1]=0,K[z+2]=0,K[z+3]=0;else K[z]=B,K[z+1]=L,K[z+2]=O,K[z+3]=j}else if(W==3){var j=q[U+3],B=q[U],L=q[U+1],O=q[U+2],N=K[z+3],R=K[z],v=K[z+1],w=K[z+2];if(j==N&&B==R&&L==v&&O==w)continue;if(j<220&&N>20)return!1}}return!0};P.encode=function(q,X,V,K,Q,Y,J){if(K==null)K=0;if(J==null)J=!1;var G=P.encode.compress(q,X,V,K,[!1,!1,!1,0,J]);return P.encode.compressPNG(G,-1),P.encode._main(G,X,V,Q,Y)};P.encodeLL=function(q,X,V,K,Q,Y,J,G){var W={ctype:0+(K==1?0:2)+(Q==0?0:4),depth:Y,frames:[]},Z=Date.now(),H=(K+Q)*Y,U=H*X;for(var z=0;z1,U=!1,z=33+(H?20:0);if(Q.sRGB!=null)z+=13;if(Q.pHYs!=null)z+=21;if(q.ctype==3){var k=q.plte.length;for(var M=0;M>>24!=255)U=!0;z+=8+k*3+4+(U?8+k*1+4:0)}for(var j=0;j>>8&255,$=R>>>16&255;L[Z+N+0]=v,L[Z+N+1]=w,L[Z+N+2]=$}if(Z+=k*3,J(L,Z,Y(L,Z-k*3-4,k*3+4)),Z+=4,U){J(L,Z,k),Z+=4,W(L,Z,"tRNS"),Z+=4;for(var M=0;M>>24&255;Z+=k,J(L,Z,Y(L,Z-k-4,k+4)),Z+=4}}var S=0;for(var j=0;j>2,D>>2));for(var k=0;kq0&&r==u[B-q0])J0[B]=J0[B-q0];else{var I0=N[r];if(I0==null){if(N[r]=I0=R.length,R.push(r),R.length>=300)break}J0[B]=I0}}}var n0=R.length;if(n0<=256&&Z==!1){if(n0<=2)U=1;else if(n0<=4)U=2;else if(n0<=16)U=4;else U=8;U=Math.max(U,W)}for(var k=0;k>1)]|=N1[y1+R0]<<4-(R0&1)*4;else if(U==2)for(var R0=0;R0>2)]|=N1[y1+R0]<<6-(R0&3)*2;else if(U==1)for(var R0=0;R0>3)]|=N1[y1+R0]<<7-(R0&7)*1}Z2=$2,H=3,bq=1}else if(L==!1&&O.length==1){var $2=new Uint8Array(q0*y2*3),pK=q0*y2;for(var B=0;B$)$=b;if(hS)S=h}}if($==-1)v=w=$=S=0;if(Q){if((v&1)==1)v--;if((w&1)==1)w--}var D=($-v+1)*(S-w+1);if(DB)B=R;if(vL)L=v}}if(B==-1)M=j=B=L=0;if(J){if((M&1)==1)M--;if((j&1)==1)j--}Y={x:M,y:j,width:B-M+1,height:L-j+1};var S=K[Q];if(S.rect=Y,S.blend=1,S.img=new Uint8Array(Y.width*Y.height*4),K[Q-1].dispose==0)P._copyTile(Z,X,V,S.img,Y.width,Y.height,-Y.x,-Y.y,0),P.encode._prepareDiff(z,X,V,S.img,Y);else P._copyTile(z,X,V,S.img,Y.width,Y.height,-Y.x,-Y.y,0)};P.encode._prepareDiff=function(q,X,V,K,Q){P._copyTile(q,X,V,K,Q.width,Q.height,-Q.x,-Q.y,2)};P.encode._filterZero=function(q,X,V,K,Q,Y,J){var G=[],W=[0,1,2,3,4];if(Y!=-1)W=[Y];else if(X*K>500000||V==1)W=[0];var Z;if(J)Z={level:0};var H=J&&UZIP!=null?UZIP:kK.default;for(var U=0;U>1)+256&255;if(Y==4)for(var Z=Q;Z>1)&255;for(var Z=Q;Z>1)&255}if(Y==4){for(var Z=0;Z>>1;else V=V>>>1;q[X]=V}return q}(),update:function(q,X,V,K){for(var Q=0;Q>>8;return q},crc:function(q,X,V){return P.crc.update(4294967295,q,X,V)^4294967295}};P.quantize=function(q,X){var V=new Uint8Array(q),K=V.slice(0),Q=new Uint32Array(K.buffer),Y=P.quantize.getKDtree(K,X),J=Y[0],G=Y[1],W=P.quantize.planeDst,Z=V,H=Q,U=Z.length,z=new Uint8Array(V.length>>2);for(var k=0;k>2]=O.ind,H[k>>2]=O.est.rgba}return{abuf:K.buffer,inds:z,plte:G}};P.quantize.getKDtree=function(q,X,V){if(V==null)V=0.0001;var K=new Uint32Array(q.buffer),Q={i0:0,i1:q.length,bst:null,est:null,tdst:0,left:null,right:null};Q.bst=P.quantize.stats(q,Q.i0,Q.i1),Q.est=P.quantize.estats(Q.bst);var Y=[Q];while(Y.lengthJ)J=Y[W].est.L,G=W;if(J=H||Z.i1<=H;if(U){Z.est.L=0;continue}var z={i0:Z.i0,i1:H,bst:null,est:null,tdst:0,left:null,right:null};z.bst=P.quantize.stats(q,z.i0,z.i1),z.est=P.quantize.estats(z.bst);var k={i0:H,i1:Z.i1,bst:null,est:null,tdst:0,left:null,right:null};k.bst={R:[],m:[],N:Z.bst.N-z.bst.N};for(var W=0;W<16;W++)k.bst.R[W]=Z.bst.R[W]-z.bst.R[W];for(var W=0;W<4;W++)k.bst.m[W]=Z.bst.m[W]-z.bst.m[W];k.est=P.quantize.estats(k.bst),Z.left=z,Z.right=k,Y[G]=z,Y.push(k)}Y.sort(function(M,j){return j.bst.N-M.bst.N});for(var W=0;W0)J=q.right,G=q.left;var W=P.quantize.getNearest(J,X,V,K,Q);if(W.tdst<=Y*Y)return W;var Z=P.quantize.getNearest(G,X,V,K,Q);return Z.tdstY)K-=4;if(V>=K)break;var W=X[V>>2];X[V>>2]=X[K>>2],X[K>>2]=W,V+=4,K-=4}while(J(q,V,Q)>Y)V-=4;return V+4};P.quantize.vecDot=function(q,X,V){return q[X]*V[0]+q[X+1]*V[1]+q[X+2]*V[2]+q[X+3]*V[3]};P.quantize.stats=function(q,X,V){var K=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],Q=[0,0,0,0],Y=V-X>>2;for(var J=X;J>>0}};P.M4={multVec:function(q,X){return[q[0]*X[0]+q[1]*X[1]+q[2]*X[2]+q[3]*X[3],q[4]*X[0]+q[5]*X[1]+q[6]*X[2]+q[7]*X[3],q[8]*X[0]+q[9]*X[1]+q[10]*X[2]+q[11]*X[3],q[12]*X[0]+q[13]*X[1]+q[14]*X[2]+q[15]*X[3]]},dot:function(q,X){return q[0]*X[0]+q[1]*X[1]+q[2]*X[2]+q[3]*X[3]},sml:function(q,X){return[q*X[0],q*X[1],q*X[2],q*X[3]]}};P.encode.concatRGBA=function(q){var X=0;for(var V=0;V1)throw Error("Animated PNGs are not supported");var Q=new Uint8Array(K[0]),Y=lG(Q),J=Y.rgbChannel,G=Y.alphaChannel;this.rgbChannel=J;var W=G.some(function(Z){return Z<255});if(W)this.alphaChannel=G;this.type=fG(V.ctype),this.width=V.width,this.height=V.height,this.bitsPerComponent=8}return q.load=function(X){return new q(X)},q}();var _G=function(){function q(X){this.image=X,this.bitsPerComponent=X.bitsPerComponent,this.width=X.width,this.height=X.height,this.colorSpace="DeviceRGB"}return q.for=function(X){return _(this,void 0,void 0,function(){var V;return c(this,function(K){return V=IK.load(X),[2,new q(V)]})})},q.prototype.embedIntoContext=function(X,V){return _(this,void 0,void 0,function(){var K,Q;return c(this,function(Y){if(K=this.embedAlphaChannel(X),Q=X.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:K}),V)return X.assign(V,Q),[2,V];else return[2,X.register(Q)];return[2]})})},q.prototype.embedAlphaChannel=function(X){if(!this.image.alphaChannel)return;var V=X.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return X.register(V)},q}(),X8=_G;var cG=function(){function q(X,V,K){this.bytes=X,this.start=V||0,this.pos=this.start,this.end=!!V&&!!K?V+K:this.bytes.length}return Object.defineProperty(q.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(q.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),q.prototype.getByte=function(){if(this.pos>=this.end)return-1;return this.bytes[this.pos++]},q.prototype.getUint16=function(){var X=this.getByte(),V=this.getByte();if(X===-1||V===-1)return-1;return(X<<8)+V},q.prototype.getInt32=function(){var X=this.getByte(),V=this.getByte(),K=this.getByte(),Q=this.getByte();return(X<<24)+(V<<16)+(K<<8)+Q},q.prototype.getBytes=function(X,V){if(V===void 0)V=!1;var K=this.bytes,Q=this.pos,Y=this.end;if(!X){var J=K.subarray(Q,Y);return V?new Uint8ClampedArray(J):J}else{var G=Q+X;if(G>Y)G=Y;this.pos=G;var J=K.subarray(Q,G);return V?new Uint8ClampedArray(J):J}},q.prototype.peekByte=function(){var X=this.getByte();return this.pos--,X},q.prototype.peekBytes=function(X,V){if(V===void 0)V=!1;var K=this.getBytes(X,V);return this.pos-=K.length,K},q.prototype.skip=function(X){if(!X)X=1;this.pos+=X},q.prototype.reset=function(){this.pos=this.start},q.prototype.moveStart=function(){this.start=this.pos},q.prototype.makeSubStream=function(X,V){return new q(this.bytes,X,V)},q.prototype.decode=function(){return this.bytes},q}(),Hq=cG;var pG=new Uint8Array(0),dG=function(){function q(X){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=pG,this.minBufferLength=512,X)while(this.minBufferLengthY)K=Y}else{while(!this.eof)this.readBlock();K=this.bufferLength}this.pos=K;var J=this.buffer.subarray(Q,K);return V&&!(J instanceof Uint8ClampedArray)?new Uint8ClampedArray(J):J},q.prototype.peekByte=function(){var X=this.getByte();return this.pos--,X},q.prototype.peekBytes=function(X,V){if(V===void 0)V=!1;var K=this.getBytes(X,V);return this.pos-=K.length,K},q.prototype.skip=function(X){if(!X)X=1;this.pos+=X},q.prototype.reset=function(){this.pos=0},q.prototype.makeSubStream=function(X,V){var K=X+V;while(this.bufferLength<=K&&!this.eof)this.readBlock();return new Hq(this.buffer,X,V)},q.prototype.decode=function(){while(!this.eof)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},q.prototype.readBlock=function(){throw new u0(this.constructor.name,"readBlock")},q.prototype.ensureBuffer=function(X){var V=this.buffer;if(X<=V.byteLength)return V;var K=this.minBufferLength;while(K=0;--Z)W[G+Z]=U&255,U>>=8}},X}(d2),jK=nG;var rG=function(q){A(X,q);function X(V,K){var Q=q.call(this,K)||this;if(Q.stream=V,Q.firstDigit=-1,K)K=0.5*K;return Q}return X.prototype.readBlock=function(){var V=8000,K=this.stream.getBytes(V);if(!K.length){this.eof=!0;return}var Q=K.length+1>>1,Y=this.ensureBuffer(this.bufferLength+Q),J=this.bufferLength,G=this.firstDigit;for(var W=0,Z=K.length;W=48&&H<=57)U=H&15;else if(H>=65&&H<=70||H>=97&&H<=102)U=(H&15)+9;else if(H===62){this.eof=!0;break}else continue;if(G<0)G=U;else Y[J++]=G<<4|U,G=-1}if(G>=0&&this.eof)Y[J++]=G<<4,G=-1;this.firstDigit=G,this.bufferLength=J},X}(d2),LK=rG;var BK=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),iG=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),aG=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),oG=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,590000,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],sG=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],tG=function(q){A(X,q);function X(V,K){var Q=q.call(this,K)||this;Q.stream=V;var Y=V.getByte(),J=V.getByte();if(Y===-1||J===-1)throw Error("Invalid header in flate stream: "+Y+", "+J);if((Y&15)!==8)throw Error("Unknown compression method in flate stream: "+Y+", "+J);if(((Y<<8)+J)%31!==0)throw Error("Bad FCHECK in flate stream: "+Y+", "+J);if(J&32)throw Error("FDICT bit set in flate stream: "+Y+", "+J);return Q.codeSize=0,Q.codeBuf=0,Q}return X.prototype.readBlock=function(){var V,K,Q=this.stream,Y=this.getBits(3);if(Y&1)this.eof=!0;if(Y>>=1,Y===0){var J=void 0;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");var G=J;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");if(G|=J<<8,(J=Q.getByte())===-1)throw Error("Bad block header in flate stream");var W=J;if((J=Q.getByte())===-1)throw Error("Bad block header in flate stream");if(W|=J<<8,W!==(~G&65535)&&(G!==0||W!==0))throw Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var Z=this.bufferLength;V=this.ensureBuffer(Z+G);var H=Z+G;if(this.bufferLength=H,G===0){if(Q.peekByte()===-1)this.eof=!0}else for(var U=Z;U0)v[O++]=S}z=this.generateHuffmanTable(v.subarray(0,M)),k=this.generateHuffmanTable(v.subarray(M,R))}else throw Error("Unknown block type in flate stream");V=this.buffer;var C=V?V.length:0,D=this.bufferLength;while(!0){var l=this.getCode(z);if(l<256){if(D+1>=C)V=this.ensureBuffer(D+1),C=V.length;V[D++]=l;continue}if(l===256){this.bufferLength=D;return}l-=257,l=iG[l];var u=l>>16;if(u>0)u=this.getBits(u);if(K=(l&65535)+u,l=this.getCode(k),l=aG[l],u=l>>16,u>0)u=this.getBits(u);var q0=(l&65535)+u;if(D+K>=C)V=this.ensureBuffer(D+K),C=V.length;for(var J0=0;J0>V,this.codeSize=Q-=V,J},X.prototype.getCode=function(V){var K=this.stream,Q=V[0],Y=V[1],J=this.codeSize,G=this.codeBuf,W;while(J>16,U=Z&65535;if(H<1||J>H,this.codeSize=J-H,U},X.prototype.generateHuffmanTable=function(V){var K=V.length,Q=0,Y;for(Y=0;YQ)Q=V[Y];var J=1<>=1;for(Y=z;Y0;if(!v||v<256)B[0]=v,L=1;else if(v>=258)if(v=0;J--)B[J]=U[G],G=k[G]}else B[L++]=B[0];else if(v===256){M=9,H=258,L=0;continue}else{this.eof=!0,delete this.lzwState;break}if(w)k[H]=j,z[H]=z[j]+1,U[H]=B[0],H++,M=H+Z&H+Z-1?M:Math.min(Math.log(H+Z)/0.6931471805599453+1,12)|0;if(j=v,O+=L,K>>K&(1<0){var J=this.stream.getBytes(Y);K.set(J,Q),Q+=Y}}else{Y=257-Y;var G=V[1];K=this.ensureBuffer(Q+Y+1);for(var W=0;WK.size())throw new Y5(V,0,K.size());K.remove(V)}},X.prototype.normalizedEntries=function(){var V=this.Kids();if(!V)V=this.dict.context.obj([this.ref]),this.dict.set(I.of("Kids"),V);return{Kids:V}},X.fromDict=function(V,K){return new X(V,K)},X}(Y8),K2=UZ;var zZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.Opt=function(){return this.dict.lookupMaybe(I.of("Opt"),K0,g,i)},X.prototype.setOpt=function(V){this.dict.set(I.of("Opt"),this.dict.context.obj(V))},X.prototype.getExportValues=function(){var V=this.Opt();if(!V)return;if(V instanceof K0||V instanceof g)return[V];var K=[];for(var Q=0,Y=V.size();QK.size())throw new Y5(V,0,K.size());K.remove(V)}},X.prototype.normalizeExportValues=function(){var V,K,Q,Y,J=(V=this.getExportValues())!==null&&V!==void 0?V:[],G=[],W=this.getWidgets();for(var Z=0,H=W.length;Z1){if(!this.hasFlag(G0.MultiSelect))throw new W7;this.dict.set(I.of("V"),this.dict.context.obj(V))}this.updateSelectedIndices(V)},X.prototype.valuesAreValid=function(V){var K=this.getOptions(),Q=function(W,Z){var H=V[W].decodeText();if(!K.find(function(U){return H===(U.display||U.value).decodeText()}))return{value:!1}};for(var Y=0,J=V.length;Y1){var K=Array(V.length),Q=this.getOptions(),Y=function(W,Z){var H=V[W].decodeText();K[W]=Q.findIndex(function(U){return H===(U.display||U.value).decodeText()})};for(var J=0,G=V.length;J0){var G=J.lookup(0,K0,g),W=J.lookupMaybe(1,K0,g);K.push({value:G,display:W||G})}}}return K}return[]},X}(K2),G8=kZ;var IZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Ch",Ff:G0.Combo,Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(G8),Q6=IZ;var EZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.addField=function(V){var K=this.normalizedEntries().Kids;K===null||K===void 0||K.push(V)},X.prototype.normalizedEntries=function(){var V=this.Kids();if(!V)V=this.dict.context.obj([]),this.dict.set(I.of("Kids"),V);return{Kids:V}},X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({}),Q=V.register(K);return new X(K,Q)},X}(Y8),Y6=EZ;var jZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X}(K2),F6=jZ;var LZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.MaxLen=function(){var V=this.dict.lookup(I.of("MaxLen"));if(V instanceof x)return V;return},X.prototype.Q=function(){var V=this.dict.lookup(I.of("Q"));if(V instanceof x)return V;return},X.prototype.setMaxLength=function(V){this.dict.set(I.of("MaxLen"),x.of(V))},X.prototype.removeMaxLength=function(){this.dict.delete(I.of("MaxLen"))},X.prototype.getMaxLength=function(){var V;return(V=this.MaxLen())===null||V===void 0?void 0:V.asNumber()},X.prototype.setQuadding=function(V){this.dict.set(I.of("Q"),x.of(V))},X.prototype.getQuadding=function(){var V;return(V=this.Q())===null||V===void 0?void 0:V.asNumber()},X.prototype.setValue=function(V){this.dict.set(I.of("V"),V)},X.prototype.removeValue=function(){this.dict.delete(I.of("V"))},X.prototype.getValue=function(){var V=this.V();if(V instanceof K0||V instanceof g)return V;return},X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Tx",Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(K2),J6=LZ;var BZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.fromDict=function(V,K){return new X(V,K)},X.create=function(V){var K=V.obj({FT:"Btn",Ff:f0.PushButton,Kids:[]}),Q=V.register(K);return new X(K,Q)},X}(h6),G6=BZ;var TZ=function(q){A(X,q);function X(){return q!==null&&q.apply(this,arguments)||this}return X.prototype.setValue=function(V){var K=this.getOnValues();if(!K.includes(V)&&V!==I.of("Off"))throw new J5;this.dict.set(I.of("V"),V);var Q=this.getWidgets();for(var Y=0,J=Q.length;YY)throw new qq(K,Y);var J=K;for(var G=0,W=Q.size();GJ)return H.insertLeafNode(V,J)||Z;else J-=H.Count().asNumber();if(H instanceof _0)J-=1}if(J===0){this.insertLeafKid(Q.size(),V);return}throw new Xq(K,"insertLeafNode")},X.prototype.removeLeafNode=function(V,K){if(K===void 0)K=!0;var Q=this.Kids(),Y=this.Count().asNumber();if(V>=Y)throw new qq(V,Y);var J=V;for(var G=0,W=Q.size();GJ){if(H.removeLeafNode(J,K),K&&H.Kids().size()===0)Q.remove(G);return}else J-=H.Count().asNumber();if(H instanceof _0)if(J===0){this.removeKid(G);return}else J-=1}throw new Xq(V,"removeLeafNode")},X.prototype.ascend=function(V){V(this);var K=this.Parent();if(K)K.ascend(V)},X.prototype.traverse=function(V){var K=this.Kids();for(var Q=0,Y=K.size();QNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var Q="Parsed number that is too large for some PDF readers: "+X+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(Q),Number.MAX_SAFE_INTEGER}else{var Q="Parsed number that is too large for some PDF readers: "+X+", not capping.";console.warn(Q)}return K},q.prototype.skipWhitespace=function(){while(!this.bytes.done()&&k2[this.bytes.peek()])this.bytes.next()},q.prototype.skipLine=function(){while(!this.bytes.done()){var X=this.bytes.peek();if(X===AK||X===NK)return;this.bytes.next()}},q.prototype.skipComment=function(){if(this.bytes.peek()!==E.Percent)return!1;while(!this.bytes.done()){var X=this.bytes.peek();if(X===AK||X===NK)return!0;this.bytes.next()}return!0},q.prototype.skipWhitespaceAndComments=function(){this.skipWhitespace();while(this.skipComment())this.skipWhitespace()},q.prototype.matchKeyword=function(X){var V=this.bytes.offset();for(var K=0,Q=X.length;K=this.length},q.prototype.offset=function(){return this.idx},q.prototype.slice=function(X,V){return this.bytes.slice(X,V)},q.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},q.of=function(X){return new q(X)},q.fromPDFRawStream=function(X){return q.of(V8(X).decode())},q}(),D6=CZ;var hZ=E.Space,U1=E.CarriageReturn,z1=E.Newline,M1=[E.s,E.t,E.r,E.e,E.a,E.m],Eq=[E.e,E.n,E.d,E.s,E.t,E.r,E.e,E.a,E.m],M0={header:[E.Percent,E.P,E.D,E.F,E.Dash],eof:[E.Percent,E.Percent,E.E,E.O,E.F],obj:[E.o,E.b,E.j],endobj:[E.e,E.n,E.d,E.o,E.b,E.j],xref:[E.x,E.r,E.e,E.f],trailer:[E.t,E.r,E.a,E.i,E.l,E.e,E.r],startxref:[E.s,E.t,E.a,E.r,E.t,E.x,E.r,E.e,E.f],true:[E.t,E.r,E.u,E.e],false:[E.f,E.a,E.l,E.s,E.e],null:[E.n,E.u,E.l,E.l],stream:M1,streamEOF1:Q0(M1,[hZ,U1,z1]),streamEOF2:Q0(M1,[U1,z1]),streamEOF3:Q0(M1,[U1]),streamEOF4:Q0(M1,[z1]),endstream:Eq,EOF1endstream:Q0([U1,z1],Eq),EOF2endstream:Q0([U1],Eq),EOF3endstream:Q0([z1],Eq)};var FZ=function(q){A(X,q);function X(V,K,Q){if(Q===void 0)Q=!1;var Y=q.call(this,V,Q)||this;return Y.context=K,Y}return X.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(M0.true))return c2.True;if(this.matchKeyword(M0.false))return c2.False;if(this.matchKeyword(M0.null))return F0;var V=this.bytes.peek();if(V===E.LessThan&&this.bytes.peekAhead(1)===E.LessThan)return this.parseDictOrStream();if(V===E.LessThan)return this.parseHexString();if(V===E.LeftParen)return this.parseString();if(V===E.ForwardSlash)return this.parseName();if(V===E.LeftSquareBracket)return this.parseArray();if(H1[V])return this.parseNumberOrRef();throw new M7(this.bytes.position(),V)},X.prototype.parseNumberOrRef=function(){var V=this.parseRawNumber();this.skipWhitespaceAndComments();var K=this.bytes.offset();if(P0[this.bytes.peek()]){var Q=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===E.R)return this.bytes.assertNext(E.R),a.of(V,Q)}return this.bytes.moveTo(K),x.of(V)},X.prototype.parseHexString=function(){var V="";this.bytes.assertNext(E.LessThan);while(!this.bytes.done()&&this.bytes.peek()!==E.GreaterThan)V+=t0(this.bytes.next());return this.bytes.assertNext(E.GreaterThan),g.of(V)},X.prototype.parseString=function(){var V=0,K=!1,Q="";while(!this.bytes.done()){var Y=this.bytes.next();if(Q+=t0(Y),!K){if(Y===E.LeftParen)V+=1;if(Y===E.RightParen)V-=1}if(Y===E.BackSlash)K=!K;else if(K)K=!1;if(V===0)return K0.of(Q.substring(1,Q.length-1))}throw new E7(this.bytes.position())},X.prototype.parseName=function(){this.bytes.assertNext(E.ForwardSlash);var V="";while(!this.bytes.done()){var K=this.bytes.peek();if(k2[K]||V2[K])break;V+=t0(K),this.bytes.next()}return I.of(V)},X.prototype.parseArray=function(){this.bytes.assertNext(E.LeftSquareBracket),this.skipWhitespaceAndComments();var V=i.withContext(this.context);while(this.bytes.peek()!==E.RightSquareBracket){var K=this.parseObject();V.push(K),this.skipWhitespaceAndComments()}return this.bytes.assertNext(E.RightSquareBracket),V},X.prototype.parseDict=function(){this.bytes.assertNext(E.LessThan),this.bytes.assertNext(E.LessThan),this.skipWhitespaceAndComments();var V=new Map;while(!this.bytes.done()&&this.bytes.peek()!==E.GreaterThan&&this.bytes.peekAhead(1)!==E.GreaterThan){var K=this.parseName(),Q=this.parseObject();V.set(K,Q),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(E.GreaterThan),this.bytes.assertNext(E.GreaterThan);var Y=V.get(I.of("Type"));if(Y===I.of("Catalog"))return W8.fromMapWithContext(V,this.context);else if(Y===I.of("Pages"))return H8.fromMapWithContext(V,this.context);else if(Y===I.of("Page"))return _0.fromMapWithContext(V,this.context);else return m.fromMapWithContext(V,this.context)},X.prototype.parseDictOrStream=function(){var V=this.bytes.position(),K=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(M0.streamEOF1)&&!this.matchKeyword(M0.streamEOF2)&&!this.matchKeyword(M0.streamEOF3)&&!this.matchKeyword(M0.streamEOF4)&&!this.matchKeyword(M0.stream))return K;var Q=this.bytes.offset(),Y,J=K.get(I.of("Length"));if(J instanceof x){if(Y=Q+J.asNumber(),this.bytes.moveTo(Y),this.skipWhitespaceAndComments(),!this.matchKeyword(M0.endstream))this.bytes.moveTo(Q),Y=this.findEndOfStreamFallback(V)}else Y=this.findEndOfStreamFallback(V);var G=this.bytes.slice(Q,Y);return A2.of(K,G)},X.prototype.findEndOfStreamFallback=function(V){var K=1,Q=this.bytes.offset();while(!this.bytes.done()){if(Q=this.bytes.offset(),this.matchKeyword(M0.stream))K+=1;else if(this.matchKeyword(M0.EOF1endstream)||this.matchKeyword(M0.EOF2endstream)||this.matchKeyword(M0.EOF3endstream)||this.matchKeyword(M0.endstream))K-=1;else this.bytes.next();if(K===0)break}if(K!==0)throw new I7(V);return Q},X.forBytes=function(V,K,Q){return new X(D6.of(V),K,Q)},X.forByteStream=function(V,K,Q){if(Q===void 0)Q=!1;return new X(V,K,Q)},X}(SK),U8=FZ;var PZ=function(q){A(X,q);function X(V,K){var Q=q.call(this,D6.fromPDFRawStream(V),V.dict.context)||this,Y=V.dict;return Q.alreadyParsed=!1,Q.shouldWaitForTick=K||function(){return!1},Q.firstOffset=Y.lookup(I.of("First"),x).asNumber(),Q.objectCount=Y.lookup(I.of("N"),x).asNumber(),Q}return X.prototype.parseIntoContext=function(){return _(this,void 0,void 0,function(){var V,K,Q,Y,J,G,W,Z;return c(this,function(H){switch(H.label){case 0:if(this.alreadyParsed)throw new Q5("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,V=this.parseOffsetsAndObjectNumbers(),K=0,Q=V.length,H.label=1;case 1:if(!(K=E.Space&&K<=E.Tilde;if(Q){if(this.matchKeyword(M0.xref)||this.matchKeyword(M0.trailer)||this.matchKeyword(M0.startxref)||this.matchIndirectObjectHeader()){this.bytes.moveTo(V);break}}this.bytes.next()}},X.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var V=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(V)}catch(K){this.bytes.next(),this.skipWhitespaceAndComments()}},X.forBytesWithOptions=function(V,K,Q,Y){return new X(V,K,Q,Y)},X}(U8),Bq=uZ;var n2=function(q){return 1<0)K[K.length]=+Q;V[V.length]={cmd:X,args:K},K=[],Q="",Y=!1}X=Z}else if([" ",","].includes(Z)||Z==="-"&&Q.length>0&&Q[Q.length-1]!=="e"||Z==="."&&Y){if(Q.length===0)continue;if(K.length===J){if(V[V.length]={cmd:X,args:K},K=[+Q],X==="M")X="L";if(X==="m")X="l"}else K[K.length]=+Q;Y=Z===".",Q=["-","."].includes(Z)?Z:""}else if(Q+=Z,Z===".")Y=!0}if(Q.length>0)if(K.length===J){if(V[V.length]={cmd:X,args:K},K=[+Q],X==="M")X="L";if(X==="m")X="l"}else K[K.length]=+Q;return V[V.length]={cmd:X,args:K},V},oZ=function(q){d=n=Z0=W0=v1=R1=0;var X=[];for(var V=0;V1)z=Math.sqrt(z),V*=z,K*=z;var k=U/V,M=H/V,j=-H/K,B=U/K,L=k*G+M*W,O=j*G+B*W,N=k*q+M*X,R=j*q+B*X,v=(N-L)*(N-L)+(R-O)*(R-O),w=1/v-0.25;if(w<0)w=0;var $=Math.sqrt(w);if(Y===Q)$=-$;var S=0.5*(L+N)-$*(R-O),h=0.5*(O+R)+$*(N-L),b=Math.atan2(O-h,L-S),C=Math.atan2(R-h,N-S),D=C-b;if(D<0&&Y===1)D+=2*Math.PI;else if(D>0&&Y===0)D-=2*Math.PI;var l=Math.ceil(Math.abs(D/(Math.PI*0.5+0.001))),u=[];for(var q0=0;q0q.length)return Q-1;var B=X.heightAtSize(Q),L=B+B*0.2,O=L*Y;if(O>Math.abs(V.height))return Q-1;Q+=1}return Q},K3=function(q,X,V,K){var Q=V.width/K,Y=V.height,J=mK,G=J4(q);while(JQ*0.75;if(U)return J-1}var z=X.heightAtSize(J,{descender:!1});if(z>Y)return J-1;J+=1}return J},Q3=function(q){for(var X=q.length;X>0;X--)if(/\s/.test(q[X]))return X;return},Y3=function(q,X,V,K){var Q,Y=q.length;while(Y>0){var J=q.substring(0,Y),G=V.encodeText(J),W=V.widthOfTextAtSize(J,K);if(Wz)z=$+v;if(M+G>k)k=M+G;Z.push({text:N,encoded:R,width:v,height:G,x:$,y:M}),L=w===null||w===void 0?void 0:w.trim()}}return{fontSize:K,lineHeight:W,lines:Z,bounds:{x:H,y:U,width:z-H,height:k-U}}},KX=function(q,X){var{fontSize:V,font:K,bounds:Q,cellCount:Y}=X,J=F1(k6(q));if(J.length>Y)throw new qX(J.length,Y);if(V===void 0||V===0)V=K3(J,K,Q,Y);var G=Q.width/Y,W=K.heightAtSize(V,{descender:!1}),Z=Q.y+(Q.height/2-W/2),H=[],U=Q.x,z=Q.y,k=Q.x+Q.width,M=Q.y+Q.height,j=0,B=0;while(jk)k=$+v;if(Z+W>M)M=Z+W;H.push({text:J,encoded:R,width:v,height:W,x:$,y:Z}),j+=1,B+=N}return{fontSize:V,cells:H,bounds:{x:U,y:z,width:k-U,height:M-z}}},v8=function(q,X){var{alignment:V,fontSize:K,font:Q,bounds:Y}=X,J=F1(k6(q));if(K===void 0||K===0)K=lK([J],Q,Y);var G=Q.encodeText(J),W=Q.widthOfTextAtSize(J,K),Z=Q.heightAtSize(K,{descender:!1}),H=V===v0.Left?Y.x:V===v0.Center?Y.x+Y.width/2-W/2:V===v0.Right?Y.x+Y.width-W:Y.x,U=Y.y+(Y.height/2-Z/2);return{fontSize:K,line:{text:J,encoded:G,width:W,height:Z,x:H,y:U},bounds:{x:H,y:U,width:W,height:Z}}};var G2=function(q){if("normal"in q)return q;return{normal:q}},J3=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,m6=function(q){var X,V,K=(X=q.getDefaultAppearance())!==null&&X!==void 0?X:"",Q=(V=F5(K,J3).match)!==null&&V!==void 0?V:[],Y=Number(Q[2]);return isFinite(Y)?Y:void 0},G3=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,L2=function(q){var X,V=(X=q.getDefaultAppearance())!==null&&X!==void 0?X:"",K=F5(V,G3).match,Q=K!==null&&K!==void 0?K:[],Y=Q[1],J=Q[2],G=Q[3],W=Q[4],Z=Q[5];if(Z==="g"&&Y)return Sq(Number(Y));if(Z==="rg"&&Y&&J&&G)return Y0(Number(Y),Number(J),Number(G));if(Z==="k"&&Y&&J&&G&&W)return yq(Number(Y),Number(J),Number(G),Number(W));return},B2=function(q,X,V,K){var Q;if(K===void 0)K=0;var Y=[E2(X).toString(),T5((Q=V===null||V===void 0?void 0:V.name)!==null&&Q!==void 0?Q:"dummy__noop",K).toString()].join(` +`);q.setDefaultAppearance(Y)},QX=function(q,X){var V,K,Q,Y=L2(X),J=L2(q.acroField),G=X.getRectangle(),W=X.getAppearanceCharacteristics(),Z=X.getBorderStyle(),H=(V=Z===null||Z===void 0?void 0:Z.getWidth())!==null&&V!==void 0?V:0,U=I2(W===null||W===void 0?void 0:W.getRotation()),z=r2(G,U),k=z.width,M=z.height,j=j2(o(o({},G),{rotation:U})),B=Y0(0,0,0),L=(K=l0(W===null||W===void 0?void 0:W.getBorderColor()))!==null&&K!==void 0?K:B,O=l0(W===null||W===void 0?void 0:W.getBackgroundColor()),N=l0(W===null||W===void 0?void 0:W.getBackgroundColor(),0.8),R=(Q=Y!==null&&Y!==void 0?Y:J)!==null&&Q!==void 0?Q:B;if(Y)B2(X,R);else B2(q.acroField,R);var v={x:0+H/2,y:0+H/2,width:k-H,height:M-H,thickness:1.5,borderWidth:H,borderColor:L,markColor:R};return{normal:{on:Q0(j,B8(o(o({},v),{color:O,filled:!0}))),off:Q0(j,B8(o(o({},v),{color:O,filled:!1})))},down:{on:Q0(j,B8(o(o({},v),{color:N,filled:!0}))),off:Q0(j,B8(o(o({},v),{color:N,filled:!1})))}}},YX=function(q,X){var V,K,Q,Y=L2(X),J=L2(q.acroField),G=X.getRectangle(),W=X.getAppearanceCharacteristics(),Z=X.getBorderStyle(),H=(V=Z===null||Z===void 0?void 0:Z.getWidth())!==null&&V!==void 0?V:0,U=I2(W===null||W===void 0?void 0:W.getRotation()),z=r2(G,U),k=z.width,M=z.height,j=j2(o(o({},G),{rotation:U})),B=Y0(0,0,0),L=(K=l0(W===null||W===void 0?void 0:W.getBorderColor()))!==null&&K!==void 0?K:B,O=l0(W===null||W===void 0?void 0:W.getBackgroundColor()),N=l0(W===null||W===void 0?void 0:W.getBackgroundColor(),0.8),R=(Q=Y!==null&&Y!==void 0?Y:J)!==null&&Q!==void 0?Q:B;if(Y)B2(X,R);else B2(q.acroField,R);var v={x:k/2,y:M/2,width:k-H,height:M-H,borderWidth:H,borderColor:L,dotColor:R};return{normal:{on:Q0(j,T8(o(o({},v),{color:O,filled:!0}))),off:Q0(j,T8(o(o({},v),{color:O,filled:!1})))},down:{on:Q0(j,T8(o(o({},v),{color:N,filled:!0}))),off:Q0(j,T8(o(o({},v),{color:N,filled:!1})))}}},JX=function(q,X,V){var K,Q,Y,J,G,W=L2(X),Z=L2(q.acroField),H=m6(X),U=m6(q.acroField),z=X.getRectangle(),k=X.getAppearanceCharacteristics(),M=X.getBorderStyle(),j=k===null||k===void 0?void 0:k.getCaptions(),B=(K=j===null||j===void 0?void 0:j.normal)!==null&&K!==void 0?K:"",L=(Y=(Q=j===null||j===void 0?void 0:j.down)!==null&&Q!==void 0?Q:B)!==null&&Y!==void 0?Y:"",O=(J=M===null||M===void 0?void 0:M.getWidth())!==null&&J!==void 0?J:0,N=I2(k===null||k===void 0?void 0:k.getRotation()),R=r2(z,N),v=R.width,w=R.height,$=j2(o(o({},z),{rotation:N})),S=Y0(0,0,0),h=l0(k===null||k===void 0?void 0:k.getBorderColor()),b=l0(k===null||k===void 0?void 0:k.getBackgroundColor()),C=l0(k===null||k===void 0?void 0:k.getBackgroundColor(),0.8),D={x:O,y:O,width:v-O*2,height:w-O*2},l=v8(B,{alignment:v0.Center,fontSize:H!==null&&H!==void 0?H:U,font:V,bounds:D}),u=v8(L,{alignment:v0.Center,fontSize:H!==null&&H!==void 0?H:U,font:V,bounds:D}),q0=Math.min(l.fontSize,u.fontSize),J0=(G=W!==null&&W!==void 0?W:Z)!==null&&G!==void 0?G:S;if(W||H!==void 0)B2(X,J0,V,q0);else B2(q.acroField,J0,V,q0);var r={x:0+O/2,y:0+O/2,width:v-O,height:w-O,borderWidth:O,borderColor:h,textColor:J0,font:V.name,fontSize:q0};return{normal:Q0($,hq(o(o({},r),{color:b,textLines:[l.line]}))),down:Q0($,hq(o(o({},r),{color:C,textLines:[u.line]})))}},GX=function(q,X,V){var K,Q,Y,J,G=L2(X),W=L2(q.acroField),Z=m6(X),H=m6(q.acroField),U=X.getRectangle(),z=X.getAppearanceCharacteristics(),k=X.getBorderStyle(),M=(K=q.getText())!==null&&K!==void 0?K:"",j=(Q=k===null||k===void 0?void 0:k.getWidth())!==null&&Q!==void 0?Q:0,B=I2(z===null||z===void 0?void 0:z.getRotation()),L=r2(U,B),O=L.width,N=L.height,R=j2(o(o({},U),{rotation:B})),v=Y0(0,0,0),w=l0(z===null||z===void 0?void 0:z.getBorderColor()),$=l0(z===null||z===void 0?void 0:z.getBackgroundColor()),S,h,b=q.isCombed()?0:1,C={x:j+b,y:j+b,width:O-(j+b)*2,height:N-(j+b)*2};if(q.isMultiline()){var D=uq(M,{alignment:q.getAlignment(),fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C});S=D.lines,h=D.fontSize}else if(q.isCombed()){var D=KX(M,{fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C,cellCount:(Y=q.getMaxLength())!==null&&Y!==void 0?Y:0});S=D.cells,h=D.fontSize}else{var D=v8(M,{alignment:q.getAlignment(),fontSize:Z!==null&&Z!==void 0?Z:H,font:V,bounds:C});S=[D.line],h=D.fontSize}var l=(J=G!==null&&G!==void 0?G:W)!==null&&J!==void 0?J:v;if(G||Z!==void 0)B2(X,l,V,h);else B2(q.acroField,l,V,h);var u={x:0+j/2,y:0+j/2,width:O-j,height:N-j,borderWidth:j!==null&&j!==void 0?j:0,borderColor:w,textColor:l,font:V.name,fontSize:h,color:$,textLines:S,padding:b};return Q0(R,Pq(u))},ZX=function(q,X,V){var K,Q,Y,J=L2(X),G=L2(q.acroField),W=m6(X),Z=m6(q.acroField),H=X.getRectangle(),U=X.getAppearanceCharacteristics(),z=X.getBorderStyle(),k=(K=q.getSelected()[0])!==null&&K!==void 0?K:"",M=(Q=z===null||z===void 0?void 0:z.getWidth())!==null&&Q!==void 0?Q:0,j=I2(U===null||U===void 0?void 0:U.getRotation()),B=r2(H,j),L=B.width,O=B.height,N=j2(o(o({},H),{rotation:j})),R=Y0(0,0,0),v=l0(U===null||U===void 0?void 0:U.getBorderColor()),w=l0(U===null||U===void 0?void 0:U.getBackgroundColor()),$=1,S={x:M+$,y:M+$,width:L-(M+$)*2,height:O-(M+$)*2},h=v8(k,{alignment:v0.Left,fontSize:W!==null&&W!==void 0?W:Z,font:V,bounds:S}),b=h.line,C=h.fontSize,D=(Y=J!==null&&J!==void 0?J:G)!==null&&Y!==void 0?Y:R;if(J||W!==void 0)B2(X,D,V,C);else B2(q.acroField,D,V,C);var l={x:0+M/2,y:0+M/2,width:L-M,height:O-M,borderWidth:M!==null&&M!==void 0?M:0,borderColor:v,textColor:D,font:V.name,fontSize:C,color:w,textLines:[b],padding:$};return Q0(N,Pq(l))},WX=function(q,X,V){var K,Q,Y=L2(X),J=L2(q.acroField),G=m6(X),W=m6(q.acroField),Z=X.getRectangle(),H=X.getAppearanceCharacteristics(),U=X.getBorderStyle(),z=(K=U===null||U===void 0?void 0:U.getWidth())!==null&&K!==void 0?K:0,k=I2(H===null||H===void 0?void 0:H.getRotation()),M=r2(Z,k),j=M.width,B=M.height,L=j2(o(o({},Z),{rotation:k})),O=Y0(0,0,0),N=l0(H===null||H===void 0?void 0:H.getBorderColor()),R=l0(H===null||H===void 0?void 0:H.getBackgroundColor()),v=q.getOptions(),w=q.getSelected();if(q.isSorted())v.sort();var $="";for(var S=0,h=v.length;S1||Q.length===1&&K)this.enableMultiselect();var G=Array(Q.length);for(var W=0,Z=Q.length;W1||Q.length===1&&K)this.enableMultiselect();var J=Array(Q.length);for(var G=0,W=Q.length;GK)throw new XX(V.length,K,this.getName());if(this.markAsDirty(),this.disableRichFormatting(),V)this.acroField.setValue(g.fromText(V));else this.acroField.removeValue()},X.prototype.getAlignment=function(){var V=this.acroField.getQuadding();return V===0?v0.Left:V===1?v0.Center:V===2?v0.Right:v0.Left},X.prototype.setAlignment=function(V){M2(V,"alignment",v0),this.markAsDirty(),this.acroField.setQuadding(V)},X.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},X.prototype.setMaxLength=function(V){if(X2(V,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),V===void 0)this.acroField.removeMaxLength();else{var K=this.getText();if(K&&K.length>V)throw new VX(K.length,V,this.getName());this.acroField.setMaxLength(V)}},X.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},X.prototype.setImage=function(V){var K=this.getAlignment(),Q=K===v0.Center?T2.Center:K===v0.Right?T2.Right:T2.Left,Y=this.acroField.getWidgets();for(var J=0,G=Y.length;J"u")globalThis.Buffer=y;if(typeof globalThis.process>"u")globalThis.process=N3;globalThis.__bundles=globalThis.__bundles||{};globalThis.__bundles["pdf-lib"]=UX;})(); diff --git a/apps/sim/lib/integrations/icon-mapping.ts b/apps/sim/lib/integrations/icon-mapping.ts index 7aeb59d753a..04b349d7c43 100644 --- a/apps/sim/lib/integrations/icon-mapping.ts +++ b/apps/sim/lib/integrations/icon-mapping.ts @@ -38,6 +38,7 @@ import { CloudWatchIcon, CodePipelineIcon, ConfluenceIcon, + ContextDevIcon, ConvexIcon, CrowdStrikeIcon, CursorIcon, @@ -189,6 +190,7 @@ import { SlackIcon, SmtpIcon, SQSIcon, + SquareIcon, SshIcon, STSIcon, STTIcon, @@ -260,6 +262,7 @@ export const blockTypeToIconMap: Record = { cloudwatch: CloudWatchIcon, codepipeline: CodePipelineIcon, confluence_v2: ConfluenceIcon, + context_dev: ContextDevIcon, convex: ConvexIcon, crowdstrike: CrowdStrikeIcon, cursor_v2: CursorIcon, @@ -413,6 +416,7 @@ export const blockTypeToIconMap: Record = { slack: SlackIcon, smtp: SmtpIcon, sqs: SQSIcon, + square: SquareIcon, ssh: SshIcon, stagehand: StagehandIcon, stripe: StripeIcon, diff --git a/apps/sim/lib/integrations/integrations.json b/apps/sim/lib/integrations/integrations.json index c846bcdaf35..64e1d3ebc1c 100644 --- a/apps/sim/lib/integrations/integrations.json +++ b/apps/sim/lib/integrations/integrations.json @@ -1,5 +1,5 @@ { - "updatedAt": "2026-06-14", + "updatedAt": "2026-06-15", "integrations": [ { "type": "onepassword", @@ -3336,6 +3336,113 @@ "integrationType": "documents", "tags": ["knowledge-base", "content-management", "note-taking"] }, + { + "type": "context_dev", + "slug": "context-dev", + "name": "Context.dev", + "description": "Scrape, crawl, search, extract, and enrich web and brand data", + "longDescription": "Integrate Context.dev into the workflow. Scrape pages to markdown or HTML, capture screenshots, list images, crawl entire sites, map sitemaps, search the web, extract structured data and products, pull design systems, classify industries, and retrieve brand assets by domain, name, email, ticker, or transaction — all from one API.", + "bgColor": "#ffffff", + "iconName": "ContextDevIcon", + "docsUrl": "https://docs.sim.ai/integrations/context_dev", + "operations": [ + { + "name": "Scrape Markdown", + "description": "Scrape any URL and return clean, LLM-ready markdown content." + }, + { + "name": "Scrape HTML", + "description": "Scrape any URL and return the raw HTML content of the page." + }, + { + "name": "Scrape Images", + "description": "Discover every image asset on a page, with optional dimension and type enrichment." + }, + { + "name": "Screenshot", + "description": "Capture a screenshot of any web page and store it as a downloadable image file." + }, + { + "name": "Crawl Website", + "description": "Crawl an entire website and return each discovered page as clean markdown." + }, + { + "name": "Map Sitemap", + "description": "Build a sitemap of a domain and return every discovered page URL." + }, + { + "name": "Web Search", + "description": "Search the web with natural language and optionally scrape results to markdown." + }, + { + "name": "Extract Structured Data", + "description": "Crawl a website and extract structured data matching a provided JSON schema." + }, + { + "name": "Extract Product", + "description": "Detect and extract structured product details from a single product page URL." + }, + { + "name": "Extract Products", + "description": "Extract the product catalog from a brand" + }, + { + "name": "Scrape Fonts", + "description": "Extract the font families, usage stats, and font files used by a domain." + }, + { + "name": "Scrape Styleguide", + "description": "Extract a domain" + }, + { + "name": "Classify NAICS", + "description": "Classify a brand into NAICS industry codes from its domain or company name." + }, + { + "name": "Classify SIC", + "description": "Classify a brand into SIC industry codes from its domain or company name." + }, + { + "name": "Get Brand by Domain", + "description": "Retrieve brand data for a domain: logos, colors, backdrops, socials, address, and industry." + }, + { + "name": "Get Brand by Name", + "description": "Retrieve brand data by company name: logos, colors, socials, address, and industry." + }, + { + "name": "Get Brand by Email", + "description": "Retrieve brand data from a work email address. Free/disposable emails are rejected (422)." + }, + { + "name": "Get Brand by Ticker", + "description": "Retrieve brand data for a public company by its stock ticker symbol." + }, + { + "name": "Get Brand (Simplified)", + "description": "Retrieve essential brand data for a domain: title, colors, logos, and backdrops." + }, + { + "name": "Identify Transaction", + "description": "Identify the brand behind a raw bank/card transaction descriptor and return its brand data." + }, + { + "name": "Prefetch Domain", + "description": "Queue a domain for brand-data prefetching to reduce latency on later requests (subscribers; 0 credits)." + }, + { + "name": "Prefetch by Email", + "description": "Queue an email" + } + ], + "operationCount": 22, + "triggers": [], + "triggerCount": 0, + "authType": "api-key", + "category": "tools", + "integrationType": "search", + "tags": ["web-scraping", "enrichment", "automation"] + }, { "type": "convex", "slug": "convex", @@ -14553,6 +14660,161 @@ "category": "tools", "integrationType": "email" }, + { + "type": "square", + "slug": "square", + "name": "Square", + "description": "Process payments and manage Square commerce data", + "longDescription": "Integrate Square into the workflow. Take and refund payments, manage customers, build catalog items and images, create and search orders, and issue invoices. Authenticate with a Square access token (personal access token).", + "bgColor": "#000000", + "iconName": "SquareIcon", + "docsUrl": "https://docs.sim.ai/integrations/square", + "operations": [ + { + "name": "Create Payment", + "description": "Take a payment using a payment source such as a card nonce or a card on file" + }, + { + "name": "Get Payment", + "description": "Retrieve details for a single payment by its ID" + }, + { + "name": "List Payments", + "description": "List payments taken by the account, optionally filtered by location and time range" + }, + { + "name": "Cancel Payment", + "description": "Cancel (void) an authorized payment that has not been captured" + }, + { + "name": "Complete Payment", + "description": "Capture (complete) a payment that was authorized with delayed capture" + }, + { + "name": "Refund Payment", + "description": "Refund all or part of a completed payment" + }, + { + "name": "Get Refund", + "description": "Retrieve a single payment refund by its ID" + }, + { + "name": "List Refunds", + "description": "List payment refunds, optionally filtered by location, status, and time range" + }, + { + "name": "Create Customer", + "description": "Create a new customer profile in the Square customer directory" + }, + { + "name": "Get Customer", + "description": "Retrieve a single customer profile by its ID" + }, + { + "name": "List Customers", + "description": "List customer profiles in the Square customer directory" + }, + { + "name": "Search Customers", + "description": "Search customer profiles using filters such as email, phone, or creation date" + }, + { + "name": "Update Customer", + "description": "Update fields on an existing customer profile" + }, + { + "name": "Delete Customer", + "description": "Delete a customer profile from the Square customer directory" + }, + { + "name": "List Locations", + "description": "List all locations associated with the Square account" + }, + { + "name": "Get Location", + "description": "Retrieve a single location by its ID" + }, + { + "name": "Create Order", + "description": "Create an order with line items, taxes, discounts, and fulfillments" + }, + { + "name": "Get Order", + "description": "Retrieve a single order by its ID" + }, + { + "name": "Search Orders", + "description": "Search orders across one or more locations using filters and sorting" + }, + { + "name": "Pay Order", + "description": "Pay for an order using one or more already-approved payments" + }, + { + "name": "Create Invoice", + "description": "Create a draft invoice for an existing order and customer" + }, + { + "name": "Get Invoice", + "description": "Retrieve a single invoice by its ID" + }, + { + "name": "List Invoices", + "description": "List invoices for a specific location" + }, + { + "name": "Search Invoices", + "description": "Search invoices across one or more locations" + }, + { + "name": "Publish Invoice", + "description": "Publish a draft invoice so it is sent to the customer and becomes payable" + }, + { + "name": "Cancel Invoice", + "description": "Cancel a published invoice that is unpaid or partially paid" + }, + { + "name": "Delete Invoice", + "description": "Delete a draft invoice" + }, + { + "name": "Upsert Catalog Object", + "description": "Create or update a catalog object such as an item, variation, or category" + }, + { + "name": "Get Catalog Object", + "description": "Retrieve a single catalog object by its ID" + }, + { + "name": "List Catalog", + "description": "List catalog objects, optionally filtered by type" + }, + { + "name": "Search Catalog Objects", + "description": "Search catalog objects by type and query filters" + }, + { + "name": "Create Catalog Image", + "description": "Upload an image and attach it to the catalog, optionally to a specific item" + }, + { + "name": "Delete Catalog Object", + "description": "Delete a catalog object and its children (e.g. an item and its variations)" + }, + { + "name": "Batch Retrieve Inventory Counts", + "description": "Retrieve current inventory counts for catalog items across locations" + } + ], + "operationCount": 34, + "triggers": [], + "triggerCount": 0, + "authType": "api-key", + "category": "tools", + "integrationType": "commerce", + "tags": ["payments", "subscriptions", "automation"] + }, { "type": "ssh", "slug": "ssh", diff --git a/apps/sim/lib/invitations/core.ts b/apps/sim/lib/invitations/core.ts index 96740dd4d6f..122cf5d6b5b 100644 --- a/apps/sim/lib/invitations/core.ts +++ b/apps/sim/lib/invitations/core.ts @@ -15,6 +15,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' +import { normalizeEmail } from '@sim/utils/string' import { and, eq, inArray, lte } from 'drizzle-orm' import { setActiveOrganizationForCurrentSession } from '@/lib/auth/active-organization' import { syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' @@ -204,10 +205,6 @@ export async function expireStalePendingInvitationsForWorkspaces( } } -export function normalizeEmail(email: string): string { - return email.trim().toLowerCase() -} - export type AcceptInvitationFailure = | { kind: 'not-found' } | { kind: 'already-processed' } diff --git a/apps/sim/lib/invitations/send.ts b/apps/sim/lib/invitations/send.ts index 6a355e45466..23b7f8566c6 100644 --- a/apps/sim/lib/invitations/send.ts +++ b/apps/sim/lib/invitations/send.ts @@ -9,6 +9,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' +import { normalizeEmail } from '@sim/utils/string' import { and, eq, inArray, ne, sql } from 'drizzle-orm' import { getEmailSubject, @@ -17,7 +18,7 @@ import { renderWorkspaceInvitationEmail, } from '@/components/emails' import { getBaseUrl } from '@/lib/core/utils/urls' -import { computeInvitationExpiry, normalizeEmail } from '@/lib/invitations/core' +import { computeInvitationExpiry } from '@/lib/invitations/core' import { sendEmail } from '@/lib/messaging/email/mailer' import { getFromEmailAddress } from '@/lib/messaging/email/utils' diff --git a/apps/sim/lib/invitations/workspace-invitations.ts b/apps/sim/lib/invitations/workspace-invitations.ts index dad09c88f7b..c29cbc12731 100644 --- a/apps/sim/lib/invitations/workspace-invitations.ts +++ b/apps/sim/lib/invitations/workspace-invitations.ts @@ -1,12 +1,12 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' import { db } from '@sim/db' import { type InvitationMembershipIntent, permissions, user } from '@sim/db/schema' +import { normalizeEmail } from '@sim/utils/string' import { and, eq, sql } from 'drizzle-orm' import type { NextRequest } from 'next/server' import { getUserOrganization } from '@/lib/billing/organizations/membership' import { validateSeatAvailability } from '@/lib/billing/validation/seat-management' import { PlatformEvents } from '@/lib/core/telemetry' -import { normalizeEmail } from '@/lib/invitations/core' import { cancelPendingInvitation, createPendingInvitation, diff --git a/apps/sim/lib/media/falai-video.ts b/apps/sim/lib/media/falai-video.ts index 1339d2520c4..4b6a9413783 100644 --- a/apps/sim/lib/media/falai-video.ts +++ b/apps/sim/lib/media/falai-video.ts @@ -1,9 +1,9 @@ +import { isRecordLike } from '@sim/utils/object' import { downloadFalMedia, extractFalMediaUrl, getFalApiKey, getNumberProp, - isRecord, runFalQueue, } from '@/lib/media/falai' import { type FalAICostMetadata, getFalAICostMetadata } from '@/lib/tools/falai-pricing' @@ -176,7 +176,7 @@ export async function generateFalVideo(params: GenerateFalVideoParams): Promise< const url = extractFalMediaUrl(data, ['video', 'output']) if (!url) throw new Error('No video URL in Fal.ai response') - const videoNode = isRecord(data.video) ? data.video : undefined + const videoNode = isRecordLike(data.video) ? data.video : undefined const { buffer, contentType } = await downloadFalMedia(url) const cost = await getFalAICostMetadata({ apiKey, endpointId: endpoint, requestId }) diff --git a/apps/sim/lib/media/falai.ts b/apps/sim/lib/media/falai.ts index a2d09614f0b..21a36dfbad9 100644 --- a/apps/sim/lib/media/falai.ts +++ b/apps/sim/lib/media/falai.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { sleep } from '@sim/utils/helpers' +import { isRecordLike } from '@sim/utils/object' import { getMaxExecutionTimeout } from '@/lib/core/execution-limits' import { secureFetchWithPinnedIP, @@ -44,10 +45,6 @@ export function getFalApiKey(): string { return keys[index] } -export function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export function getStringProp( record: Record | undefined, key: string @@ -70,7 +67,7 @@ function falQueueUrl(endpoint: string, requestId: string, path: 'status' | 'resp function falErrorMessage(error: unknown): string { if (typeof error === 'string') return error - if (isRecord(error)) return getStringProp(error, 'message') || JSON.stringify(error) + if (isRecordLike(error)) return getStringProp(error, 'message') || JSON.stringify(error) return 'Unknown Fal.ai error' } @@ -105,7 +102,7 @@ export async function runFalQueue( maxBytes: MAX_MEDIA_JSON_BYTES, label: 'Fal.ai create response', }) - if (!isRecord(createData)) throw new Error('Invalid Fal.ai queue response') + if (!isRecordLike(createData)) throw new Error('Invalid Fal.ai queue response') const requestId = getStringProp(createData, 'request_id') if (!requestId) throw new Error('Fal.ai queue response missing request_id') @@ -134,7 +131,7 @@ export async function runFalQueue( maxBytes: MAX_MEDIA_JSON_BYTES, label: 'Fal.ai status response', }) - if (!isRecord(statusData)) throw new Error('Invalid Fal.ai status response') + if (!isRecordLike(statusData)) throw new Error('Invalid Fal.ai status response') const status = getStringProp(statusData, 'status') if (status === 'COMPLETED') { @@ -157,7 +154,7 @@ export async function runFalQueue( maxBytes: MAX_MEDIA_JSON_BYTES, label: 'Fal.ai result response', }) - if (!isRecord(resultData)) throw new Error('Invalid Fal.ai result response') + if (!isRecordLike(resultData)) throw new Error('Invalid Fal.ai result response') return { requestId, data: resultData } } @@ -180,12 +177,12 @@ export function extractFalMediaUrl( for (const key of keys) { const value = data[key] if (typeof value === 'string') return value - if (isRecord(value)) { + if (isRecordLike(value)) { const url = getStringProp(value, 'url') if (url) return url } if (Array.isArray(value)) { - const first = value.find(isRecord) as Record | undefined + const first = value.find(isRecordLike) as Record | undefined const url = getStringProp(first, 'url') if (url) return url } diff --git a/apps/sim/lib/permission-groups/block-access.ts b/apps/sim/lib/permission-groups/block-access.ts new file mode 100644 index 00000000000..884f952665a --- /dev/null +++ b/apps/sim/lib/permission-groups/block-access.ts @@ -0,0 +1,22 @@ +import { getBlock } from '@/blocks/registry' + +/** + * Block types that bypass permission-group access control entirely. + * + * Two kinds of blocks are exempt: + * - `start_trigger`: the universal workflow entry point. A workflow must always + * be startable regardless of the configured integration allowlist. + * - Legacy blocks (`hideFromToolbar: true`): superseded integration versions and + * deprecated blocks. They never appear in the toolbar or the Access Control + * admin list, so admins cannot allowlist them — yet they may still live inside + * older workflows. Exempting them keeps those workflows runnable instead of + * silently blocking blocks the admin had no way to permit. + * + * This is the single source of truth shared by both the runtime enforcement + * paths and the Access Control admin UI so the "hidden from the list" set and + * the "skipped by enforcement" set never drift apart. + */ +export function isBlockTypeAccessControlExempt(blockType: string): boolean { + if (blockType === 'start_trigger') return true + return getBlock(blockType)?.hideFromToolbar === true +} diff --git a/apps/sim/lib/table/query-builder/converters.ts b/apps/sim/lib/table/query-builder/converters.ts index d5423034bda..f0b96ce82b6 100644 --- a/apps/sim/lib/table/query-builder/converters.ts +++ b/apps/sim/lib/table/query-builder/converters.ts @@ -3,6 +3,7 @@ */ import { generateShortId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import type { Filter, FilterRule, JsonValue, Sort, SortDirection, SortRule } from '../types' /** Converts UI filter rules to a Filter object for API queries. */ @@ -162,7 +163,7 @@ function parseFilterGroup(group: Filter): FilterRule[] { for (const [column, value] of Object.entries(group)) { if (column === '$or' || column === '$and') continue - if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + if (isRecordLike(value)) { for (const [op, opValue] of Object.entries(value)) { if (!op.startsWith('$')) continue // `$empty` is a valueless boolean operator — map it back to the two diff --git a/apps/sim/lib/tools/falai-pricing.ts b/apps/sim/lib/tools/falai-pricing.ts index 5714e0c9784..764a9e741a2 100644 --- a/apps/sim/lib/tools/falai-pricing.ts +++ b/apps/sim/lib/tools/falai-pricing.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' +import { isRecordLike } from '@sim/utils/object' export const FALAI_HOSTED_KEY_MARKUP_MULTIPLIER = 1.5 export const FALAI_IMAGE_FALLBACK_PROVIDER_COST_DOLLARS = 0.05 @@ -31,10 +32,6 @@ interface FalAIBillingEvent { cost_estimate_nano_usd: number } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function getNumber(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? value : undefined } @@ -65,7 +62,7 @@ function getFalAIFallbackProviderCostDollars(endpointId: string): number { } function parseBillingEvent(value: unknown): FalAIBillingEvent | undefined { - if (!isRecord(value)) return undefined + if (!isRecordLike(value)) return undefined const requestId = value.request_id const endpointId = value.endpoint_id @@ -116,7 +113,7 @@ async function fetchFalAIBillingEvent( }) return undefined }) - if (!isRecord(data) || !Array.isArray(data.billing_events)) return undefined + if (!isRecordLike(data) || !Array.isArray(data.billing_events)) return undefined return data.billing_events.map(parseBillingEvent).find(Boolean) } @@ -152,7 +149,7 @@ async function estimateFalAICallCost( } const data = (await response.json()) as unknown - const totalCost = isRecord(data) ? getNumber(data.total_cost) : undefined + const totalCost = isRecordLike(data) ? getNumber(data.total_cost) : undefined if (totalCost === undefined) { return { error: 'Fal.ai pricing estimate missing total_cost' } } diff --git a/apps/sim/lib/uploads/utils/user-file-base64.server.ts b/apps/sim/lib/uploads/utils/user-file-base64.server.ts index 213eb3a9a95..2aa3abda185 100644 --- a/apps/sim/lib/uploads/utils/user-file-base64.server.ts +++ b/apps/sim/lib/uploads/utils/user-file-base64.server.ts @@ -1,5 +1,6 @@ import type { Logger } from '@sim/logger' import { createLogger } from '@sim/logger' +import { isPlainRecord } from '@sim/utils/object' import { getRedisClient } from '@/lib/core/config/redis' import { isUserFileWithMetadata } from '@/lib/core/utils/user-file' import { recordMaterializedAccessKeys } from '@/lib/execution/payloads/access-keys' @@ -573,14 +574,6 @@ export async function hydrateUserFileWithBase64( return hydrateUserFile(file, options, state, logger) } -function isPlainObject(value: unknown): value is Record { - if (!value || typeof value !== 'object') { - return false - } - const proto = Object.getPrototypeOf(value) - return proto === Object.prototype || proto === null -} - /** * Checks if a value contains any UserFile objects with metadata. */ @@ -597,7 +590,7 @@ export function containsUserFileWithMetadata(value: unknown): boolean { return value.some((item) => containsUserFileWithMetadata(item)) } - if (!isPlainObject(value)) { + if (!isPlainRecord(value)) { return false } diff --git a/apps/sim/lib/webhooks/polling/types.ts b/apps/sim/lib/webhooks/polling/types.ts index 49aeab414c8..2647b22c1aa 100644 --- a/apps/sim/lib/webhooks/polling/types.ts +++ b/apps/sim/lib/webhooks/polling/types.ts @@ -1,5 +1,6 @@ import type { webhook, workflow } from '@sim/db/schema' import type { Logger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' /** Summary returned after polling all webhooks for a provider. */ export interface PollSummary { @@ -19,14 +20,10 @@ export interface PollWebhookContext { export type WebhookRecord = typeof webhook.$inferSelect export type WorkflowRecord = typeof workflow.$inferSelect -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export function getProviderConfigRecord( providerConfig: WebhookRecord['providerConfig'] ): Record { - return isRecord(providerConfig) ? providerConfig : {} + return isRecordLike(providerConfig) ? providerConfig : {} } export function getProviderConfig( diff --git a/apps/sim/lib/webhooks/providers/emailbison.ts b/apps/sim/lib/webhooks/providers/emailbison.ts index 1601cb30eb5..d477b11560a 100644 --- a/apps/sim/lib/webhooks/providers/emailbison.ts +++ b/apps/sim/lib/webhooks/providers/emailbison.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import { getNotificationUrl, getProviderConfig } from '@/lib/webhooks/provider-subscription-utils' import type { DeleteSubscriptionContext, @@ -19,7 +20,7 @@ export const emailBisonHandler: WebhookProviderHandler = { const triggerId = providerConfig.triggerId as string | undefined if (!triggerId) return true - if (!isRecord(body)) { + if (!isRecordLike(body)) { logger.warn(`[${requestId}] Email Bison webhook payload was not an object`) return false } @@ -36,9 +37,9 @@ export const emailBisonHandler: WebhookProviderHandler = { }, async formatInput({ body, webhook }: FormatInputContext): Promise { - const payload = isRecord(body) ? unwrapEmailBisonPayload(body) : {} - const event = isRecord(payload.event) ? payload.event : null - const data = isRecord(payload.data) ? payload.data : null + const payload = isRecordLike(body) ? unwrapEmailBisonPayload(body) : {} + const event = isRecordLike(payload.event) ? payload.event : null + const data = isRecordLike(payload.data) ? payload.data : null const providerConfig = getProviderConfig(webhook) const triggerId = providerConfig.triggerId as string | undefined const input: Record = { @@ -176,7 +177,7 @@ export const emailBisonHandler: WebhookProviderHandler = { ) } - const data = isRecord(responseBody?.data) ? responseBody.data : null + const data = isRecordLike(responseBody?.data) ? responseBody.data : null const externalId = data?.id if (externalId === undefined || externalId === null || externalId === '') { throw new Error('Email Bison webhook was created but the API response did not include an ID.') @@ -245,7 +246,7 @@ export const emailBisonHandler: WebhookProviderHandler = { async function parseJsonResponse(response: Response): Promise | null> { try { const body: unknown = await response.json() - return isRecord(body) ? body : null + return isRecordLike(body) ? body : null } catch { return null } @@ -257,19 +258,19 @@ function extractEmailBisonError(body: Record | null): string | if (typeof body.error === 'string') return body.error const data = body.data - if (isRecord(data) && typeof data.message === 'string') return data.message + if (isRecordLike(data) && typeof data.message === 'string') return data.message return null } function unwrapEmailBisonPayload(body: Record): Record { - if (isRecord(body.event)) return body + if (isRecordLike(body.event)) return body const data = body.data - if (isRecord(data) && isRecord(data.event)) return data + if (isRecordLike(data) && isRecordLike(data.event)) return data - const payload = isRecord(data) ? data.payload : body.payload - if (isRecord(payload) && isRecord(payload.event)) return payload + const payload = isRecordLike(data) ? data.payload : body.payload + if (isRecordLike(payload) && isRecordLike(payload.event)) return payload return body } @@ -288,16 +289,12 @@ function toNumberOrNull(value: unknown): number | null { } function toRecordOrNull(value: unknown): Record | null { - return isRecord(value) ? value : null + return isRecordLike(value) ? value : null } function renameTypeField(value: unknown, targetKey: string): Record | null { - if (!isRecord(value)) return null + if (!isRecordLike(value)) return null const { type, ...rest } = value return { ...rest, [targetKey]: type ?? null } } - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} diff --git a/apps/sim/lib/webhooks/providers/instantly.ts b/apps/sim/lib/webhooks/providers/instantly.ts index 17bd554e734..fcfc81d48b0 100644 --- a/apps/sim/lib/webhooks/providers/instantly.ts +++ b/apps/sim/lib/webhooks/providers/instantly.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' import { generateShortId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { NextResponse } from 'next/server' import { getNotificationUrl, getProviderConfig } from '@/lib/webhooks/provider-subscription-utils' import type { @@ -39,7 +40,7 @@ export const instantlyHandler: WebhookProviderHandler = { const triggerId = providerConfig.triggerId as string | undefined if (!triggerId) return true - if (!isRecord(body)) { + if (!isRecordLike(body)) { logger.warn(`[${requestId}] Instantly webhook payload was not an object`) return false } @@ -57,7 +58,7 @@ export const instantlyHandler: WebhookProviderHandler = { }, async formatInput({ body }: FormatInputContext): Promise { - const payload = isRecord(body) ? body : {} + const payload = isRecordLike(body) ? body : {} return { input: { @@ -232,7 +233,7 @@ export const instantlyHandler: WebhookProviderHandler = { async function parseJsonResponse(response: Response): Promise | null> { try { const body: unknown = await response.json() - return isRecord(body) ? body : null + return isRecordLike(body) ? body : null } catch { return null } @@ -263,7 +264,3 @@ function optionalId(value: unknown): string | undefined { if (trimmed === '' || trimmed === '-') return undefined return trimmed } - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} diff --git a/apps/sim/lib/webhooks/providers/sendblue.ts b/apps/sim/lib/webhooks/providers/sendblue.ts index 109ed9a8fc3..0384f27fcd3 100644 --- a/apps/sim/lib/webhooks/providers/sendblue.ts +++ b/apps/sim/lib/webhooks/providers/sendblue.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' import { getProviderConfig } from '@/lib/webhooks/provider-subscription-utils' import type { EventMatchContext, @@ -27,7 +28,7 @@ export const sendblueHandler: WebhookProviderHandler = { const triggerId = providerConfig.triggerId as string | undefined if (!triggerId || !(triggerId in SENDBLUE_TRIGGER_IS_OUTBOUND)) return true - if (!isRecord(body)) { + if (!isRecordLike(body)) { logger.warn(`[${requestId}] Sendblue webhook payload was not an object`) return false } @@ -43,7 +44,7 @@ export const sendblueHandler: WebhookProviderHandler = { }, extractIdempotencyId(body: unknown): string | null { - if (!isRecord(body)) return null + if (!isRecordLike(body)) return null const handle = body.message_handle if (typeof handle !== 'string' || handle.length === 0) return null // A single outbound message emits multiple status callbacks (e.g. SENT then @@ -54,7 +55,7 @@ export const sendblueHandler: WebhookProviderHandler = { }, async formatInput({ body }: FormatInputContext): Promise { - const b = isRecord(body) ? body : {} + const b = isRecordLike(body) ? body : {} return { input: { account_email: b.accountEmail ?? b.account_email ?? null, @@ -89,7 +90,3 @@ export const sendblueHandler: WebhookProviderHandler = { } }, } - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} diff --git a/apps/sim/lib/workflows/executor/execution-core.ts b/apps/sim/lib/workflows/executor/execution-core.ts index 7fb35a49103..3763203aaae 100644 --- a/apps/sim/lib/workflows/executor/execution-core.ts +++ b/apps/sim/lib/workflows/executor/execution-core.ts @@ -5,11 +5,10 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { filterUndefined } from '@sim/utils/object' +import { filterUndefined, isPlainRecord, isRecordLike } from '@sim/utils/object' import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' import type { Edge } from 'reactflow' import { z } from 'zod' -import { isPlainRecord } from '@/lib/core/utils/records' import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils' import { clearExecutionCancellation } from '@/lib/execution/cancellation' import { warmLargeValueRefs } from '@/lib/execution/payloads/hydration' @@ -151,7 +150,7 @@ function parseVariableValueByType(value: unknown, type: string): unknown { } if (type === 'object') { - if (typeof value === 'object' && value !== null && !Array.isArray(value)) return value + if (isRecordLike(value)) return value if (typeof value === 'string' && value.trim()) { try { return JSON.parse(value) diff --git a/apps/sim/lib/workflows/migrations/subblock-migrations.ts b/apps/sim/lib/workflows/migrations/subblock-migrations.ts index c24e04845b4..3deedca5212 100644 --- a/apps/sim/lib/workflows/migrations/subblock-migrations.ts +++ b/apps/sim/lib/workflows/migrations/subblock-migrations.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' +import { isPlainRecord } from '@sim/utils/object' import { DEFAULT_SUBBLOCK_TYPE } from '@sim/workflow-persistence/subblocks' -import { isPlainRecord } from '@/lib/core/utils/records' import { sanitizeMalformedSubBlocks } from '@/lib/workflows/sanitization/subblocks' import { buildCanonicalIndex, diff --git a/apps/sim/lib/workflows/operations/import-export.ts b/apps/sim/lib/workflows/operations/import-export.ts index 9a718d225a0..fcf94979aff 100644 --- a/apps/sim/lib/workflows/operations/import-export.ts +++ b/apps/sim/lib/workflows/operations/import-export.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { isRecordLike } from '@sim/utils/object' import { ApiClientError } from '@/lib/api/client/errors' import { requestJson } from '@/lib/api/client/request' import { @@ -21,18 +22,14 @@ import type { Variable, WorkflowState } from '@/stores/workflows/workflow/types' const logger = createLogger('WorkflowImportExport') -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function unwrapWorkflowExportEnvelope(data: unknown): unknown { - if (!isRecord(data)) { + if (!isRecordLike(data)) { return data } const envelopeData = data.data if ( - isRecord(envelopeData) && + isRecordLike(envelopeData) && (envelopeData.state || envelopeData.version || envelopeData.workflow) ) { return envelopeData @@ -523,7 +520,7 @@ export function parseWorkflowJson( // Handle new export format (version/exportedAt/state) or old format (blocks/edges at root) let workflowData: any - if (isRecord(data.state)) { + if (isRecordLike(data.state)) { // Export/API envelope format with workflow state nested under `state` logger.info('Parsing workflow JSON with version', { version: data.version, diff --git a/apps/sim/lib/workflows/sanitization/json-sanitizer.ts b/apps/sim/lib/workflows/sanitization/json-sanitizer.ts index 0c56c15f661..04802b76e49 100644 --- a/apps/sim/lib/workflows/sanitization/json-sanitizer.ts +++ b/apps/sim/lib/workflows/sanitization/json-sanitizer.ts @@ -1,3 +1,4 @@ +import { isRecordLike, sortObjectKeysDeep } from '@sim/utils/object' import type { Edge } from 'reactflow' import { sanitizeWorkflowForSharing } from '@/lib/workflows/credentials/credential-extractor' import type { BlockState, Loop, Parallel, WorkflowState } from '@/stores/workflows/workflow/types' @@ -75,12 +76,8 @@ interface SanitizedCondition { value: string } -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} - function toSanitizedCondition(condition: unknown): SanitizedCondition { - const record = isRecord(condition) ? condition : {} + const record = isRecordLike(condition) ? condition : {} return { id: String(record.id ?? ''), title: String(record.title ?? ''), @@ -113,7 +110,7 @@ function parseConditions(value: unknown): Array<{ id: string; title: string }> | const conditions: Array<{ id: string; title: string }> = [] for (const item of items) { - if (!isRecord(item) || typeof item.id !== 'string') { + if (!isRecordLike(item) || typeof item.id !== 'string') { return null } conditions.push({ @@ -133,7 +130,7 @@ function parseRoutes(value: unknown): Array<{ id: string; title?: string }> | nu const routes: Array<{ id: string; title?: string }> = [] for (const item of items) { - if (!isRecord(item) || typeof item.id !== 'string') { + if (!isRecordLike(item) || typeof item.id !== 'string') { return null } routes.push({ @@ -251,26 +248,7 @@ function sanitizeTools(tools: ToolInput[]): SanitizedTool[] { } function isToolInput(value: unknown): value is ToolInput { - return isRecord(value) && typeof value.type === 'string' -} - -/** - * Sort object keys recursively for consistent comparison - */ -function sortKeysRecursively(item: unknown): unknown { - if (Array.isArray(item)) { - return item.map(sortKeysRecursively) - } - if (item !== null && typeof item === 'object') { - const obj = item as Record - return Object.keys(obj) - .sort() - .reduce((result: Record, key: string) => { - result[key] = sortKeysRecursively(obj[key]) - return result - }, {}) - } - return item + return isRecordLike(value) && typeof value.type === 'string' } /** @@ -304,7 +282,7 @@ function sanitizeSubBlocks( // Sort keys for consistent comparison if (obj && typeof obj === 'object') { - sanitized[key] = sortKeysRecursively(obj) as Record + sanitized[key] = sortObjectKeysDeep(obj) as Record return } } catch { diff --git a/apps/sim/lib/workflows/sanitization/subblocks.ts b/apps/sim/lib/workflows/sanitization/subblocks.ts index 80b3e472f14..a97bb7b479b 100644 --- a/apps/sim/lib/workflows/sanitization/subblocks.ts +++ b/apps/sim/lib/workflows/sanitization/subblocks.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' +import { isPlainRecord } from '@sim/utils/object' import { DEFAULT_SUBBLOCK_TYPE } from '@sim/workflow-persistence/subblocks' -import { isPlainRecord } from '@/lib/core/utils/records' import { getBlock } from '@/blocks' import type { BlockState } from '@/stores/workflows/workflow/types' diff --git a/apps/sim/lib/workflows/sanitization/validation.ts b/apps/sim/lib/workflows/sanitization/validation.ts index 01ee3ff9d7c..c3152491a8d 100644 --- a/apps/sim/lib/workflows/sanitization/validation.ts +++ b/apps/sim/lib/workflows/sanitization/validation.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import { getBlock } from '@/blocks/registry' import { isCustomTool, isMcpTool } from '@/executor/constants' import type { BlockState, WorkflowState } from '@/stores/workflows/workflow/types' @@ -7,28 +8,24 @@ import { getTool } from '@/tools/utils' const logger = createLogger('WorkflowValidation') -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} - /** * Checks if a custom tool has a valid inline schema */ function isValidCustomToolSchema(tool: unknown): boolean { try { - if (!isRecord(tool)) return false + if (!isRecordLike(tool)) return false if (tool.type !== 'custom-tool') return true // non-custom tools are validated elsewhere const schema = tool.schema - if (!isRecord(schema)) return false + if (!isRecordLike(schema)) return false const fn = schema.function - if (!isRecord(fn)) return false + if (!isRecordLike(fn)) return false if (!fn.name || typeof fn.name !== 'string') return false const params = fn.parameters - if (!isRecord(params)) return false + if (!isRecordLike(params)) return false if (params.type !== 'object') return false - if (!isRecord(params.properties)) return false + if (!isRecordLike(params.properties)) return false return true } catch (_err) { @@ -41,7 +38,7 @@ function isValidCustomToolSchema(tool: unknown): boolean { */ function isValidCustomToolReference(tool: unknown): boolean { try { - if (!isRecord(tool)) return false + if (!isRecordLike(tool)) return false if (tool.type !== 'custom-tool') return false // Reference format: has customToolId but no inline schema/code @@ -97,7 +94,7 @@ export function sanitizeAgentToolsInBlocks(blocks: Record): const cleaned = value .filter((tool: unknown) => { // Allow non-custom tools to pass through as-is - if (!isRecord(tool)) return false + if (!isRecordLike(tool)) return false if (tool.type !== 'custom-tool') return true // Check if it's a valid reference-only format (new format) @@ -118,7 +115,7 @@ export function sanitizeAgentToolsInBlocks(blocks: Record): return ok }) .map((tool: unknown) => { - if (isRecord(tool) && tool.type === 'custom-tool') { + if (isRecordLike(tool) && tool.type === 'custom-tool') { // For reference-only tools, ensure usageControl default if (!tool.usageControl) { tool.usageControl = 'auto' diff --git a/apps/sim/lib/workflows/subblocks/display.ts b/apps/sim/lib/workflows/subblocks/display.ts index 8ddb49f63ae..4b6bf462018 100644 --- a/apps/sim/lib/workflows/subblocks/display.ts +++ b/apps/sim/lib/workflows/subblocks/display.ts @@ -6,6 +6,7 @@ * Every resolver takes plain data instead of hooks so both surfaces run the * exact same logic and cannot drift. */ +import { isRecordLike } from '@sim/utils/object' import { truncate } from '@sim/utils/string' import type { FilterRule, SortRule } from '@/lib/table/types' import { DELETED_WORKFLOW_LABEL } from '@/app/workspace/[workspaceId]/logs/utils' @@ -75,11 +76,6 @@ const isFieldFormatArray = (value: unknown): value is FieldFormat[] => { ) } -/** Checks if a value is a plain object (not array, not null). */ -const isPlainObject = (value: unknown): value is Record => { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - /** Type guard for variable assignments arrays (variables-input subblocks). */ const isVariableAssignmentsArray = ( value: unknown @@ -269,7 +265,7 @@ export const getDisplayValue = (value: unknown): string => { return summarizeNames(names) ?? '-' } - if (isPlainObject(parsedValue)) { + if (isRecordLike(parsedValue)) { const entries = Object.entries(parsedValue).filter( ([, val]) => val !== null && val !== undefined && val !== '' ) @@ -339,7 +335,7 @@ export function resolveFilterFieldLabel( if (!isFilterField || !rawValue) return null const parsedValue = tryParseJson(rawValue) - if (!isPlainObject(parsedValue) && !Array.isArray(parsedValue)) return null + if (!isRecordLike(parsedValue) && !Array.isArray(parsedValue)) return null try { const jsonStr = JSON.stringify(parsedValue, null, 0) diff --git a/apps/sim/lib/workflows/triggers/run-options.ts b/apps/sim/lib/workflows/triggers/run-options.ts index a35adf99dc5..853459ee2f6 100644 --- a/apps/sim/lib/workflows/triggers/run-options.ts +++ b/apps/sim/lib/workflows/triggers/run-options.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import { z } from 'zod' import { generateToolInputSchema, generateToolZodSchema } from '@/lib/mcp/workflow-tool-schema' import { normalizeInputFormatValue } from '@/lib/workflows/input-format' @@ -55,10 +56,6 @@ export interface TriggerInputValidationResult { error?: string } -function isPlainObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function readSubBlockValue(block: TriggerBlockLike, key: string): unknown { const raw = (block.subBlocks as Record | undefined)?.[key] if (raw && typeof raw === 'object' && !Array.isArray(raw)) { @@ -328,7 +325,7 @@ export function validateTriggerInput( return { ok: true } case 'chat': { - if (!isPlainObject(input) || typeof input.input !== 'string' || input.input.trim() === '') { + if (!isRecordLike(input) || typeof input.input !== 'string' || input.input.trim() === '') { return { ok: false, error: `Chat trigger "${option.blockName}" requires workflow_input shaped like { "input": "" }.`, @@ -338,7 +335,7 @@ export function validateTriggerInput( } case 'event_payload': { - if (!isPlainObject(input) || Object.keys(input).length === 0) { + if (!isRecordLike(input) || Object.keys(input).length === 0) { return { ok: false, error: @@ -354,7 +351,7 @@ export function validateTriggerInput( if (!baseShape) { // Trigger declares no input fields — accept an object (including {}). if (input === undefined || input === null) return { ok: true } - if (!isPlainObject(input)) { + if (!isRecordLike(input)) { return { ok: false, error: `Trigger "${option.blockName}" expects a JSON object for workflow_input.`, diff --git a/apps/sim/lib/workflows/variables/variable-manager.ts b/apps/sim/lib/workflows/variables/variable-manager.ts index 61e5dfaee39..eabb4feed8d 100644 --- a/apps/sim/lib/workflows/variables/variable-manager.ts +++ b/apps/sim/lib/workflows/variables/variable-manager.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import type { VariableType } from '@/stores/variables/types' /** @@ -66,7 +67,7 @@ export class VariableManager { case 'object': // Already an object (not array) - if (typeof unquoted === 'object' && unquoted !== null && !Array.isArray(unquoted)) { + if (isRecordLike(unquoted)) { return unquoted } // Special case for test diff --git a/apps/sim/providers/anthropic/core.ts b/apps/sim/providers/anthropic/core.ts index c265d1e903c..57056e6acca 100644 --- a/apps/sim/providers/anthropic/core.ts +++ b/apps/sim/providers/anthropic/core.ts @@ -16,6 +16,8 @@ import { supportsNativeStructuredOutputs, supportsTemperature, } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptAnthropicToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegment } from '@/providers/trace-enrichment' import type { ProviderRequest, ProviderResponse, TimeSegment } from '@/providers/types' import { ProviderError } from '@/providers/types' @@ -251,15 +253,7 @@ export async function executeAnthropicProviderRequest( } let anthropicTools: Anthropic.Messages.Tool[] | undefined = request.tools?.length - ? request.tools.map((tool) => ({ - name: tool.id, - description: tool.description, - input_schema: { - type: 'object' as const, - properties: tool.parameters.properties, - required: tool.parameters.required, - }, - })) + ? request.tools.map((tool) => adaptAnthropicToolSchema(tool)) : undefined let toolChoice: 'none' | 'auto' | { type: 'tool'; name: string } = 'auto' @@ -403,79 +397,38 @@ export async function executeAnthropicProviderRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromAnthropicStream( - streamResponse as AsyncIterable, - (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.input_tokens, - output: usage.output_tokens, - total: usage.input_tokens + usage.output_tokens, - } - - const costResult = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { total: 0.0, input: 0.0, output: 0.0 }, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (content, usage) => { + output.content = content + output.tokens = { + input: usage.input_tokens, + output: usage.output_tokens, + total: usage.input_tokens + usage.output_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost(request.model, usage.input_tokens, usage.output_tokens) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } + + finalizeTiming() } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { - total: 0.0, - input: 0.0, - output: 0.0, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + ), + }) - return streamingResult as StreamingExecution + return streamingResult } if (request.stream && !shouldStreamToolCalls) { @@ -811,81 +764,57 @@ export async function executeAnthropicProviderRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromAnthropicStream( - streamResponse as AsyncIterable, - (streamContent, usage) => { - streamingResult.execution.output.content = streamContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.input_tokens, - output: tokens.output + usage.output_tokens, - total: tokens.total + usage.input_tokens + usage.output_tokens, - } - - const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + toolCost: undefined as number | undefined, + total: accumulatedCost.total, + }, + toolCalls: toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (streamContent, usage) => { + output.content = streamContent + output.tokens = { + input: tokens.input + usage.input_tokens, + output: tokens.output + usage.output_tokens, + total: tokens.total + usage.input_tokens + usage.output_tokens, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamCost = calculateCost( + request.model, + usage.input_tokens, + usage.output_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + finalizeTiming() } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - toolCost: undefined as number | undefined, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + ), + }) - return streamingResult as StreamingExecution + return streamingResult } catch (error) { const providerEndTime = Date.now() const providerEndTimeISO = new Date(providerEndTime).toISOString() @@ -1258,81 +1187,57 @@ export async function executeAnthropicProviderRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromAnthropicStream( - streamResponse as AsyncIterable, - (streamContent, usage) => { - streamingResult.execution.output.content = streamContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.input_tokens, - output: tokens.output + usage.output_tokens, - total: tokens.total + usage.input_tokens + usage.output_tokens, - } - - const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - const tc2 = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: cost.input + streamCost.input, - output: cost.output + streamCost.output, - toolCost: tc2 || undefined, - total: cost.total + streamCost.total + tc2, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: cost.input, + output: cost.output, + toolCost: undefined as number | undefined, + total: cost.total, + }, + toolCalls: toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (streamContent, usage) => { + output.content = streamContent + output.tokens = { + input: tokens.input + usage.input_tokens, + output: tokens.output + usage.output_tokens, + total: tokens.total + usage.input_tokens + usage.output_tokens, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamCost = calculateCost( + request.model, + usage.input_tokens, + usage.output_tokens + ) + const tc2 = sumToolCosts(toolResults) + output.cost = { + input: cost.input + streamCost.input, + output: cost.output + streamCost.output, + toolCost: tc2 || undefined, + total: cost.total + streamCost.total + tc2, + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + finalizeTiming() } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: cost.input, - output: cost.output, - toolCost: undefined as number | undefined, - total: cost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + ), + }) - return streamingResult as StreamingExecution + return streamingResult } return { diff --git a/apps/sim/providers/azure-openai/index.ts b/apps/sim/providers/azure-openai/index.ts index a7b879891d8..ddae32b7fb4 100644 --- a/apps/sim/providers/azure-openai/index.ts +++ b/apps/sim/providers/azure-openai/index.ts @@ -27,6 +27,8 @@ import { } from '@/providers/azure-openai/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' import { executeResponsesProviderRequest } from '@/providers/openai/core' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -117,14 +119,7 @@ async function executeChatCompletionsRequest( } const tools: ChatCompletionTool[] | undefined = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function' as const, - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: ChatCompletionCreateParamsBase & { verbosity?: string } = { @@ -197,75 +192,38 @@ async function executeChatCompletionsRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -528,80 +486,62 @@ async function executeChatCompletionsRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromAzureOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution + finalizeTiming() + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() diff --git a/apps/sim/providers/baseten/index.ts b/apps/sim/providers/baseten/index.ts index a1dd2cfb7c2..a25fb29cb9c 100644 --- a/apps/sim/providers/baseten/index.ts +++ b/apps/sim/providers/baseten/index.ts @@ -11,6 +11,8 @@ import { supportsNativeStructuredOutputs, } from '@/providers/baseten/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -111,14 +113,7 @@ export const basetenProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'baseten') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -165,71 +160,38 @@ export const basetenProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const end = Date.now() - const endISO = new Date(end).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = endISO - streamingResult.execution.output.providerTiming.duration = end - providerStartTime - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = end - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - end - providerStartTime + const costResult = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -487,67 +449,51 @@ export const basetenProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: tokens.input, output: tokens.output, total: tokens.total }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, }, - } as StreamingExecution + toolCalls: + toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + createStream: ({ output }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } if (request.responseFormat && hasActiveTools) { diff --git a/apps/sim/providers/bedrock/index.ts b/apps/sim/providers/bedrock/index.ts index e6ab3d572a9..32be4078675 100644 --- a/apps/sim/providers/bedrock/index.ts +++ b/apps/sim/providers/bedrock/index.ts @@ -25,6 +25,7 @@ import { getBedrockInferenceProfileId, } from '@/providers/bedrock/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' import { enrichLastModelSegment } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -360,76 +361,36 @@ export const bedrockProvider: ProviderConfig = { throw new Error('No stream returned from Bedrock') } - const streamingResult = { - stream: createReadableStreamFromBedrockStream(streamResponse.stream, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.inputTokens, - output: usage.outputTokens, - total: usage.inputTokens + usage.outputTokens, - } - - const costResult = calculateCost(request.model, usage.inputTokens, usage.outputTokens) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + const bedrockStream = streamResponse.stream + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { total: 0.0, input: 0.0, output: 0.0 }, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromBedrockStream(bedrockStream, (content, usage) => { + output.content = content + output.tokens = { + input: usage.inputTokens, + output: usage.outputTokens, + total: usage.inputTokens + usage.outputTokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost(request.model, usage.inputTokens, usage.outputTokens) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { - total: 0.0, - input: 0.0, - output: 0.0, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const providerStartTime = Date.now() @@ -884,12 +845,33 @@ export const bedrockProvider: ProviderConfig = { throw new Error('No stream returned from Bedrock') } - const streamingResult = { - stream: createReadableStreamFromBedrockStream( - streamResponse.stream, - (streamContent, usage) => { - streamingResult.execution.output.content = streamContent - streamingResult.execution.output.tokens = { + const bedrockStream = streamResponse.stream + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: cost.input, + output: cost.output, + toolCost: undefined as number | undefined, + total: cost.total, + }, + toolCalls: + toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromBedrockStream(bedrockStream, (streamContent, usage) => { + output.content = streamContent + output.tokens = { input: tokens.input + usage.inputTokens, output: tokens.output + usage.outputTokens, total: tokens.total + usage.inputTokens + usage.outputTokens, @@ -897,68 +879,18 @@ export const bedrockProvider: ProviderConfig = { const streamCost = calculateCost(request.model, usage.inputTokens, usage.outputTokens) const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { + output.cost = { input: cost.input + streamCost.input, output: cost.output + streamCost.output, toolCost: tc || undefined, total: cost.total + streamCost.total + tc, } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime - } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime, - toolsTime, - firstResponseTime, - iterations: iterationCount + 1, - timeSegments, - }, - cost: { - input: cost.input, - output: cost.output, - toolCost: undefined as number | undefined, - total: cost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + finalizeTiming() + }), + }) - return streamingResult as StreamingExecution + return streamingResult } return { diff --git a/apps/sim/providers/cerebras/index.ts b/apps/sim/providers/cerebras/index.ts index f5991be9c3c..c351ffc4268 100644 --- a/apps/sim/providers/cerebras/index.ts +++ b/apps/sim/providers/cerebras/index.ts @@ -7,6 +7,8 @@ import { formatMessagesForProvider } from '@/providers/attachments' import type { CerebrasResponse } from '@/providers/cerebras/types' import { createReadableStreamFromCerebrasStream } from '@/providers/cerebras/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { ProviderConfig, @@ -68,14 +70,7 @@ export const cerebrasProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'cerebras') const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -130,60 +125,37 @@ export const cerebrasProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromCerebrasStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromCerebrasStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const initialCallTime = Date.now() @@ -489,73 +461,62 @@ export const cerebrasProvider: ProviderConfig = { const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output) - const streamingResult = { - stream: createReadableStreamFromCerebrasStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - toolCost: undefined as number | undefined, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, }, - } + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + toolCost: undefined as number | undefined, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromCerebrasStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } return { diff --git a/apps/sim/providers/deepseek/index.ts b/apps/sim/providers/deepseek/index.ts index e42592ebc4f..37f09254be3 100644 --- a/apps/sim/providers/deepseek/index.ts +++ b/apps/sim/providers/deepseek/index.ts @@ -6,6 +6,8 @@ import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { createReadableStreamFromDeepseekStream } from '@/providers/deepseek/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { ProviderConfig, @@ -71,14 +73,7 @@ export const deepseekProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'deepseek') const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -127,12 +122,18 @@ export const deepseekProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromDeepseekStream( - streamResponse as any, - (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromDeepseekStream(streamResponse as any, (content, usage) => { + output.content = content + output.tokens = { input: usage.prompt_tokens, output: usage.completion_tokens, total: usage.total_tokens, @@ -143,47 +144,15 @@ export const deepseekProvider: ProviderConfig = { usage.prompt_tokens, usage.completion_tokens ) - streamingResult.execution.output.cost = { + output.cost = { input: costResult.input, output: costResult.output, total: costResult.total, } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const initialCallTime = Date.now() @@ -480,12 +449,41 @@ export const deepseekProvider: ProviderConfig = { const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output) - const streamingResult = { - stream: createReadableStreamFromDeepseekStream( - streamResponse as any, - (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + toolCost: undefined as number | undefined, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromDeepseekStream(streamResponse as any, (content, usage) => { + output.content = content + output.tokens = { input: tokens.input + usage.prompt_tokens, output: tokens.output + usage.completion_tokens, total: tokens.total + usage.total_tokens, @@ -497,59 +495,16 @@ export const deepseekProvider: ProviderConfig = { usage.completion_tokens ) const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { + output.cost = { input: accumulatedCost.input + streamCost.input, output: accumulatedCost.output + streamCost.output, toolCost: tc || undefined, total: accumulatedCost.total + streamCost.total + tc, } - } - ), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - toolCost: undefined as number | undefined, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } return { diff --git a/apps/sim/providers/fireworks/index.ts b/apps/sim/providers/fireworks/index.ts index cdf355d3451..c6981d4abf0 100644 --- a/apps/sim/providers/fireworks/index.ts +++ b/apps/sim/providers/fireworks/index.ts @@ -11,6 +11,8 @@ import { supportsNativeStructuredOutputs, } from '@/providers/fireworks/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -111,14 +113,7 @@ export const fireworksProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'fireworks') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -165,71 +160,38 @@ export const fireworksProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const end = Date.now() - const endISO = new Date(end).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = endISO - streamingResult.execution.output.providerTiming.duration = end - providerStartTime - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = end - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - end - providerStartTime + const costResult = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -487,67 +449,51 @@ export const fireworksProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: tokens.input, output: tokens.output, total: tokens.total }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, }, - } as StreamingExecution + toolCalls: + toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + createStream: ({ output }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } if (request.responseFormat && hasActiveTools) { diff --git a/apps/sim/providers/google/utils.ts b/apps/sim/providers/google/utils.ts index 089f7dac552..bd98db115c1 100644 --- a/apps/sim/providers/google/utils.ts +++ b/apps/sim/providers/google/utils.ts @@ -14,6 +14,7 @@ import { } from '@google/genai' import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import { buildGeminiMessageParts } from '@/providers/attachments' import type { ProviderRequest } from '@/providers/types' import { trackForcedToolUsage } from '@/providers/utils' @@ -30,8 +31,8 @@ const logger = createLogger('GoogleUtils') * @returns A Record suitable for functionResponse.response */ export function ensureStructResponse(value: unknown): Record { - if (typeof value === 'object' && value !== null && !Array.isArray(value)) { - return value as Record + if (isRecordLike(value)) { + return value } return { value } } diff --git a/apps/sim/providers/groq/index.ts b/apps/sim/providers/groq/index.ts index 750c55d04ce..15d854e145c 100644 --- a/apps/sim/providers/groq/index.ts +++ b/apps/sim/providers/groq/index.ts @@ -6,6 +6,8 @@ import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { createReadableStreamFromGroqStream } from '@/providers/groq/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { ProviderConfig, @@ -64,14 +66,7 @@ export const groqProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'groq') const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -131,60 +126,37 @@ export const groqProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromGroqStream(streamResponse as any, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromGroqStream(streamResponse as any, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerStartTime = Date.now() @@ -437,73 +409,62 @@ export const groqProvider: ProviderConfig = { const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output) - const streamingResult = { - stream: createReadableStreamFromGroqStream(streamResponse as any, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - toolCost: undefined as number | undefined, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, }, - } + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + toolCost: undefined as number | undefined, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromGroqStream(streamResponse as any, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() diff --git a/apps/sim/providers/litellm/index.ts b/apps/sim/providers/litellm/index.ts index 53a5360d2c9..0f5fc2d3d2c 100644 --- a/apps/sim/providers/litellm/index.ts +++ b/apps/sim/providers/litellm/index.ts @@ -8,6 +8,8 @@ import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { createReadableStreamFromLiteLLMStream } from '@/providers/litellm/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { Message, @@ -129,14 +131,7 @@ export const litellmProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'litellm') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -216,81 +211,44 @@ export const litellmProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromLiteLLMStream(streamResponse, (content, usage) => { - let cleanContent = content - if (cleanContent && request.responseFormat) { - cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() - } - - streamingResult.execution.output.content = cleanContent - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromLiteLLMStream(streamResponse, (content, usage) => { + let cleanContent = content + if (cleanContent && request.responseFormat) { + cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + output.content = cleanContent + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -600,77 +558,66 @@ export const litellmProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromLiteLLMStream(streamResponse, (content, usage) => { - let cleanContent = content - if (cleanContent && request.responseFormat) { - cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromLiteLLMStream(streamResponse, (content, usage) => { + let cleanContent = content + if (cleanContent && request.responseFormat) { + cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() + } - streamingResult.execution.output.content = cleanContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } + output.content = cleanContent + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } as StreamingExecution + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } if (deferResponseFormat && responseFormatPayload) { diff --git a/apps/sim/providers/mistral/index.ts b/apps/sim/providers/mistral/index.ts index 33fb3a5b524..95c66422a72 100644 --- a/apps/sim/providers/mistral/index.ts +++ b/apps/sim/providers/mistral/index.ts @@ -7,6 +7,8 @@ import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { createReadableStreamFromMistralStream } from '@/providers/mistral/utils' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { ProviderConfig, @@ -81,14 +83,7 @@ export const mistralProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'mistral') const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -153,75 +148,38 @@ export const mistralProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromMistralStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromMistralStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -493,71 +451,60 @@ export const mistralProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromMistralStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, }, - } as StreamingExecution + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + createStream: ({ output }) => + createReadableStreamFromMistralStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() diff --git a/apps/sim/providers/ollama/core.ts b/apps/sim/providers/ollama/core.ts index 3021d410919..9e10b7c436a 100644 --- a/apps/sim/providers/ollama/core.ts +++ b/apps/sim/providers/ollama/core.ts @@ -9,6 +9,8 @@ import type { CompletionUsage } from 'openai/resources/completions' import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { Message, ProviderRequest, ProviderResponse, TimeSegment } from '@/providers/types' import { ProviderError } from '@/providers/types' @@ -103,14 +105,7 @@ export async function executeOllamaProviderRequest( const formattedMessages = formatMessagesForProvider(allMessages, providerId) as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -179,82 +174,43 @@ export async function executeOllamaProviderRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: config.createStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - - if (content && request.responseFormat) { - streamingResult.execution.output.content = content - .replace(/```json\n?|\n?```/g, '') - .trim() - } - - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + config.createStream(streamResponse, (content, usage) => { + output.content = content + + if (content && request.responseFormat) { + output.content = content.replace(/```json\n?|\n?```/g, '').trim() + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -504,78 +460,65 @@ export async function executeOllamaProviderRequest( request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: config.createStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - - if (content && request.responseFormat) { - streamingResult.execution.output.content = content - .replace(/```json\n?|\n?```/g, '') - .trim() - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + createStream: ({ output }) => + config.createStream(streamResponse, (content, usage) => { + output.content = content + + if (content && request.responseFormat) { + output.content = content.replace(/```json\n?|\n?```/g, '').trim() + } - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } // Deferred structured output: one final JSON-mode call now that tools have run. diff --git a/apps/sim/providers/openai/core.ts b/apps/sim/providers/openai/core.ts index 6f19cef1562..c0fa50def86 100644 --- a/apps/sim/providers/openai/core.ts +++ b/apps/sim/providers/openai/core.ts @@ -3,6 +3,8 @@ import { getErrorMessage, toError } from '@sim/utils/errors' import type OpenAI from 'openai' import type { IterationToolCall, StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegment, parseToolCallArguments } from '@/providers/trace-enrichment' import type { Message, ProviderRequest, ProviderResponse, TimeSegment } from '@/providers/types' import { ProviderError } from '@/providers/types' @@ -138,14 +140,7 @@ export async function executeResponsesProviderRequest( } const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined let preparedTools: PreparedTools | null = null @@ -246,75 +241,38 @@ export async function executeResponsesProviderRequest( throw new Error(`${config.providerLabel} API error (${streamResponse.status}): ${message}`) } - const streamingResult = { - stream: createReadableStreamFromResponses(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage?.promptTokens || 0, - output: usage?.completionTokens || 0, - total: usage?.totalTokens || 0, - } - - const costResult = calculateCost( - request.model, - usage?.promptTokens || 0, - usage?.completionTokens || 0 - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() - - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromResponses(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage?.promptTokens || 0, + output: usage?.completionTokens || 0, + total: usage?.totalTokens || 0, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage?.promptTokens || 0, + usage?.completionTokens || 0 + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -697,71 +655,50 @@ export async function executeResponsesProviderRequest( throw new Error(`${config.providerLabel} API error (${streamResponse.status}): ${message}`) } - const streamingResult = { - stream: createReadableStreamFromResponses(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + (usage?.promptTokens || 0), - output: tokens.output + (usage?.completionTokens || 0), - total: tokens.total + (usage?.totalTokens || 0), - } - - const streamCost = calculateCost( - request.model, - usage?.promptTokens || 0, - usage?.completionTokens || 0 - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, }, - } as StreamingExecution + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + createStream: ({ output }) => + createReadableStreamFromResponses(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + (usage?.promptTokens || 0), + output: tokens.output + (usage?.completionTokens || 0), + total: tokens.total + (usage?.totalTokens || 0), + } + + const streamCost = calculateCost( + request.model, + usage?.promptTokens || 0, + usage?.completionTokens || 0 + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() diff --git a/apps/sim/providers/openrouter/index.ts b/apps/sim/providers/openrouter/index.ts index 9bc180bdd11..8821483fa4e 100644 --- a/apps/sim/providers/openrouter/index.ts +++ b/apps/sim/providers/openrouter/index.ts @@ -11,6 +11,8 @@ import { createReadableStreamFromOpenAIStream, supportsNativeStructuredOutputs, } from '@/providers/openrouter/utils' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -113,14 +115,7 @@ export const openRouterProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'openrouter') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -167,71 +162,38 @@ export const openRouterProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const end = Date.now() - const endISO = new Date(end).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = endISO - streamingResult.execution.output.providerTiming.duration = end - providerStartTime - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = end - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - end - providerStartTime + const costResult = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -489,67 +451,51 @@ export const openRouterProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: tokens.input, output: tokens.output, total: tokens.total }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, }, - } as StreamingExecution + toolCalls: + toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + createStream: ({ output }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } if (request.responseFormat && hasActiveTools) { diff --git a/apps/sim/providers/streaming-execution.test.ts b/apps/sim/providers/streaming-execution.test.ts new file mode 100644 index 00000000000..25e7708b1f0 --- /dev/null +++ b/apps/sim/providers/streaming-execution.test.ts @@ -0,0 +1,210 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it, vi } from 'vitest' +import type { NormalizedBlockOutput } from '@/executor/types' +import { createStreamingExecution } from '@/providers/streaming-execution' + +/** + * Builds a fake stream factory mirroring the providers' `createReadableStreamFrom*` + * helpers: it returns a sentinel stream and synchronously invokes the drain + * callback so the test can assert the populated output without a real stream. + */ +function fakeStreamFactory( + drain: (handles: { output: NormalizedBlockOutput; finalizeTiming: () => void }) => void +) { + const stream = new ReadableStream() + return { + stream, + createStream: (handles: { output: NormalizedBlockOutput; finalizeTiming: () => void }) => { + drain(handles) + return stream + }, + } +} + +describe('createStreamingExecution', () => { + const providerStartTime = 1_000 + const providerStartTimeISO = new Date(providerStartTime).toISOString() + + it('assembles the simple (no-tools) shape and finalizes timing on drain', () => { + const drainTime = 5_000 + vi.spyOn(Date, 'now').mockReturnValue(drainTime) + + const { stream, createStream } = fakeStreamFactory(({ output, finalizeTiming }) => { + output.content = 'hello' + output.tokens = { input: 10, output: 20, total: 30 } + output.cost = { input: 0.1, output: 0.2, total: 0.3 } + finalizeTiming() + }) + + const result = createStreamingExecution({ + model: 'test-model', + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: 'test-model' }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream, + }) + + expect(result.stream).toBe(stream) + + const output = result.execution.output + expect(output.content).toBe('hello') + expect(output.model).toBe('test-model') + expect(output.tokens).toEqual({ input: 10, output: 20, total: 30 }) + expect(output.cost).toEqual({ input: 0.1, output: 0.2, total: 0.3 }) + expect(output.toolCalls).toBeUndefined() + + const timing = output.providerTiming + expect(timing?.startTime).toBe(providerStartTimeISO) + expect(timing?.endTime).toBe(new Date(drainTime).toISOString()) + expect(timing?.duration).toBe(drainTime - providerStartTime) + expect(timing?.modelTime).toBeUndefined() + + const segment = timing?.timeSegments?.[0] + expect(segment).toMatchObject({ + type: 'model', + name: 'test-model', + startTime: providerStartTime, + }) + expect(segment?.endTime).toBe(drainTime) + expect(segment?.duration).toBe(drainTime - providerStartTime) + + expect(result.execution.success).toBe(true) + expect(result.execution.logs).toEqual([]) + expect(result.execution.isStreaming).toBe(true) + expect(result.execution.metadata?.startTime).toBe(providerStartTimeISO) + + vi.restoreAllMocks() + }) + + it('assembles the accumulated (post-tools) shape with pre-built segments', () => { + const drainTime = 7_000 + vi.spyOn(Date, 'now').mockReturnValue(drainTime) + + const timeSegments = [ + { type: 'model' as const, name: 'iter 1', startTime: 1_000, endTime: 2_000, duration: 1_000 }, + { type: 'tool' as const, name: 'lookup', startTime: 2_000, endTime: 2_500, duration: 500 }, + ] + + const { createStream } = fakeStreamFactory(({ output }) => { + output.content = 'final' + output.tokens = { input: 110, output: 220, total: 330 } + output.cost = { input: 1.1, output: 2.2, toolCost: 0.5, total: 3.8 } + }) + + const result = createStreamingExecution({ + model: 'tool-model', + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime: 1_500, + toolsTime: 500, + firstResponseTime: 800, + iterations: 2, + timeSegments, + }, + initialTokens: { input: 100, output: 200, total: 300 }, + initialCost: { input: 1, output: 2, toolCost: undefined, total: 3 }, + toolCalls: { list: [{ name: 'lookup' }], count: 1 }, + isStreaming: true, + createStream, + }) + + const output = result.execution.output + expect(output.content).toBe('final') + expect(output.tokens).toEqual({ input: 110, output: 220, total: 330 }) + expect(output.cost).toEqual({ input: 1.1, output: 2.2, toolCost: 0.5, total: 3.8 }) + expect(output.toolCalls).toEqual({ list: [{ name: 'lookup' }], count: 1 }) + + const timing = output.providerTiming + expect(timing?.modelTime).toBe(1_500) + expect(timing?.toolsTime).toBe(500) + expect(timing?.firstResponseTime).toBe(800) + expect(timing?.iterations).toBe(2) + expect(timing?.timeSegments).toBe(timeSegments) + expect(timing?.startTime).toBe(providerStartTimeISO) + expect(timing?.endTime).toBe(new Date(drainTime).toISOString()) + expect(timing?.duration).toBe(drainTime - providerStartTime) + + vi.restoreAllMocks() + }) + + it('only finalizes timing when the provider calls finalizeTiming', () => { + const constructTime = 1_200 + vi.spyOn(Date, 'now').mockReturnValue(constructTime) + + const result = createStreamingExecution({ + model: 'no-finalize', + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime: 0, + toolsTime: 0, + firstResponseTime: 0, + iterations: 1, + timeSegments: [], + }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output }) => { + output.content = 'no-timing-mutation' + return new ReadableStream() + }, + }) + + const timing = result.execution.output.providerTiming + expect(timing?.endTime).toBe(new Date(constructTime).toISOString()) + expect(timing?.duration).toBe(constructTime - providerStartTime) + expect(result.execution.isStreaming).toBeUndefined() + + vi.restoreAllMocks() + }) + + it('finalizeTiming touches only top-level aggregate for accumulated timing', () => { + const constructTime = 1_000 + const drainTime = 9_000 + const nowMock = vi.spyOn(Date, 'now').mockReturnValue(constructTime) + + const segment = { type: 'model' as const, name: 's', startTime: 1, endTime: 2, duration: 1 } + + const result = createStreamingExecution({ + model: 'm', + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime: 0, + toolsTime: 0, + firstResponseTime: 0, + iterations: 1, + timeSegments: [segment], + }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ finalizeTiming }) => { + nowMock.mockReturnValue(drainTime) + finalizeTiming() + return new ReadableStream() + }, + }) + + const timing = result.execution.output.providerTiming + expect(timing?.endTime).toBe(new Date(drainTime).toISOString()) + expect(timing?.duration).toBe(drainTime - providerStartTime) + expect(timing?.timeSegments?.[0]).toEqual({ + type: 'model', + name: 's', + startTime: 1, + endTime: 2, + duration: 1, + }) + + vi.restoreAllMocks() + }) +}) diff --git a/apps/sim/providers/streaming-execution.ts b/apps/sim/providers/streaming-execution.ts new file mode 100644 index 00000000000..7a217af283d --- /dev/null +++ b/apps/sim/providers/streaming-execution.ts @@ -0,0 +1,196 @@ +import type { NormalizedBlockOutput, StreamingExecution } from '@/executor/types' +import type { TimeSegment } from '@/providers/types' + +/** + * Provider-agnostic assembly of the {@link StreamingExecution} object that every + * LLM provider returns from its streaming path. Centralizes the start/end timing, + * duration tracking, time-segment wiring, the `success`/`logs`/`metadata` envelope, + * and the timing-finalization contract that was previously copy-pasted across + * providers. Callers inject only the provider-specific stream iterable (which + * writes final content/tokens/cost) via {@link CreateStreamingExecutionOptions.createStream}. + */ + +/** Initial cost slice; shape is opaque so providers may include `toolCost`/`pricing`. */ +type CostSlice = NonNullable + +/** Initial token slice written into `execution.output.tokens`. */ +type TokenSlice = NonNullable + +/** + * Tool-call container written into `execution.output.toolCalls`. Providers build + * structurally-compatible list items whose `result` field is `unknown`; the + * container is widened here (mirroring the providers' former `as StreamingExecution` + * cast) and narrowed on assignment. + */ +type ToolCallSlice = { list: unknown[]; count: number } + +/** + * Timing for the no-tools streaming path. The factory builds a single inline + * `model` time segment and, when {@link StreamFinalizer.finalizeTiming} runs, + * overwrites the top-level `endTime`/`duration` and that segment's + * `endTime`/`duration` from the drain timestamp. + */ +interface SimpleTiming { + kind: 'simple' + /** Segment label — providers use the model id. */ + segmentName: string +} + +/** + * Timing for the post-tool streaming path. The factory emits the pre-built + * segments and aggregate counters from the tool-execution loop and, when + * {@link StreamFinalizer.finalizeTiming} runs, overwrites only the top-level + * `endTime`/`duration` (segments are already finalized by the loop). + */ +interface AccumulatedTiming { + kind: 'accumulated' + modelTime: number + toolsTime: number + firstResponseTime: number + iterations: number + timeSegments: TimeSegment[] +} + +type StreamingTiming = SimpleTiming | AccumulatedTiming + +/** Handles passed to {@link CreateStreamingExecutionOptions.createStream}. */ +interface StreamFinalizer { + /** Live output object — write final `content`/`tokens`/`cost` here on drain. */ + output: NormalizedBlockOutput + /** Overwrites placeholder timing from the drain timestamp. Call once on drain. */ + finalizeTiming: () => void +} + +interface CreateStreamingExecutionOptions { + /** Model id echoed into `execution.output.model`. */ + model: string + /** Wall-clock ms when the provider started the request (`Date.now()`). */ + providerStartTime: number + /** ISO form of {@link providerStartTime}. */ + providerStartTimeISO: string + /** Timing shape — `simple` (no tools) or `accumulated` (post-tools). */ + timing: StreamingTiming + /** Initial token counts (zeroed for the simple path, accumulated otherwise). */ + initialTokens: TokenSlice + /** Initial cost (zeroed for the simple path, accumulated otherwise). */ + initialCost: CostSlice + /** Tool-call container, or `undefined` when none were used. */ + toolCalls?: ToolCallSlice + /** Marks `execution.isStreaming = true` when set. */ + isStreaming?: boolean + /** + * Builds the provider stream. Receives the live `output` object and a + * `finalizeTiming` hook. The provider wires its native stream factory and, in + * the drain callback, writes final content/tokens/cost onto `output` then + * calls `finalizeTiming()`. + */ + createStream: (handles: StreamFinalizer) => ReadableStream +} + +/** + * Assembles a fully-wired {@link StreamingExecution}. The provider's stream + * (from {@link CreateStreamingExecutionOptions.createStream}) populates the + * output and finalizes timing on drain. + */ +export function createStreamingExecution( + options: CreateStreamingExecutionOptions +): StreamingExecution { + const { + model, + providerStartTime, + providerStartTimeISO, + timing, + initialTokens, + initialCost, + toolCalls, + isStreaming, + createStream, + } = options + + const now = Date.now() + const nowISO = new Date(now).toISOString() + const duration = now - providerStartTime + + const providerTiming: NonNullable = + timing.kind === 'simple' + ? { + startTime: providerStartTimeISO, + endTime: nowISO, + duration, + timeSegments: [ + { + type: 'model', + name: timing.segmentName, + startTime: providerStartTime, + endTime: now, + duration, + }, + ], + } + : { + startTime: providerStartTimeISO, + endTime: nowISO, + duration, + modelTime: timing.modelTime, + toolsTime: timing.toolsTime, + firstResponseTime: timing.firstResponseTime, + iterations: timing.iterations, + timeSegments: timing.timeSegments, + } + + const output: NormalizedBlockOutput = { + content: '', + model, + tokens: initialTokens, + toolCalls: toolCalls as NormalizedBlockOutput['toolCalls'], + providerTiming, + cost: initialCost, + } + + const timingKind = timing.kind + const stream = createStream({ + output, + finalizeTiming: () => finalizeTiming(output, providerStartTime, timingKind), + }) + + return { + stream, + execution: { + success: true, + output, + logs: [], + metadata: { + startTime: providerStartTimeISO, + endTime: nowISO, + duration, + }, + ...(isStreaming ? { isStreaming: true } : {}), + }, + } +} + +/** + * Overwrites the placeholder timing with the drain timestamp. For the simple + * path the first time segment is also finalized; for the accumulated path only + * the top-level aggregate is touched (segments are pre-finalized by the loop). + */ +function finalizeTiming( + output: NormalizedBlockOutput, + providerStartTime: number, + kind: StreamingTiming['kind'] +): void { + const streamEndTime = Date.now() + const providerTiming = output.providerTiming + if (!providerTiming) return + + providerTiming.endTime = new Date(streamEndTime).toISOString() + providerTiming.duration = streamEndTime - providerStartTime + + if (kind === 'simple') { + const segment = providerTiming.timeSegments?.[0] + if (segment) { + segment.endTime = streamEndTime + segment.duration = streamEndTime - providerStartTime + } + } +} diff --git a/apps/sim/providers/together/index.ts b/apps/sim/providers/together/index.ts index aff98633f51..34c22f5c18c 100644 --- a/apps/sim/providers/together/index.ts +++ b/apps/sim/providers/together/index.ts @@ -6,11 +6,13 @@ import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' import { checkForForcedToolUsage, createReadableStreamFromOpenAIStream, supportsNativeStructuredOutputs, } from '@/providers/together/utils' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { FunctionCallResponse, @@ -111,14 +113,7 @@ export const togetherProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'together') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -165,71 +160,38 @@ export const togetherProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const end = Date.now() - const endISO = new Date(end).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = endISO - streamingResult.execution.output.providerTiming.duration = end - providerStartTime - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = end - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - end - providerStartTime + const costResult = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -487,67 +449,51 @@ export const togetherProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - requestedModel, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: requestedModel, - tokens: { input: tokens.input, output: tokens.output, total: tokens.total }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, + const streamingResult = createStreamingExecution({ + model: requestedModel, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { input: tokens.input, output: tokens.output, total: tokens.total }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, }, - } as StreamingExecution + toolCalls: + toolCalls.length > 0 ? { list: toolCalls, count: toolCalls.length } : undefined, + createStream: ({ output }) => + createReadableStreamFromOpenAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + requestedModel, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } if (request.responseFormat && hasActiveTools) { diff --git a/apps/sim/providers/tool-schema-adapter.test.ts b/apps/sim/providers/tool-schema-adapter.test.ts new file mode 100644 index 00000000000..745d376e526 --- /dev/null +++ b/apps/sim/providers/tool-schema-adapter.test.ts @@ -0,0 +1,114 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { + adaptAnthropicToolSchema, + adaptOpenAIChatToolSchema, +} from '@/providers/tool-schema-adapter' +import type { ProviderToolConfig } from '@/providers/types' + +const sampleTool: ProviderToolConfig = { + id: 'search_web', + name: 'Search Web', + description: 'Search the web for a query', + params: {}, + parameters: { + type: 'object', + properties: { query: { type: 'string', description: 'The query' } }, + required: ['query'], + }, +} + +const noDescriptionTool: ProviderToolConfig = { + id: 'noop', + name: 'Noop', + description: '', + params: {}, + parameters: { + type: 'object', + properties: {}, + required: [], + }, +} + +const emptyParametersTool: ProviderToolConfig = { + id: 'ping', + name: 'Ping', + description: 'Ping the server', + params: {}, + parameters: {} as ProviderToolConfig['parameters'], +} + +describe('adaptOpenAIChatToolSchema', () => { + it('wraps the tool in the chat function shape', () => { + expect(adaptOpenAIChatToolSchema(sampleTool)).toEqual({ + type: 'function', + function: { + name: 'search_web', + description: 'Search the web for a query', + parameters: sampleTool.parameters, + }, + }) + }) + + it('preserves an empty description', () => { + expect(adaptOpenAIChatToolSchema(noDescriptionTool)).toEqual({ + type: 'function', + function: { + name: 'noop', + description: '', + parameters: noDescriptionTool.parameters, + }, + }) + }) + + it('passes through empty parameters unchanged', () => { + expect(adaptOpenAIChatToolSchema(emptyParametersTool)).toEqual({ + type: 'function', + function: { + name: 'ping', + description: 'Ping the server', + parameters: emptyParametersTool.parameters, + }, + }) + }) +}) + +describe('adaptAnthropicToolSchema', () => { + it('produces the Anthropic input_schema shape', () => { + expect(adaptAnthropicToolSchema(sampleTool)).toEqual({ + name: 'search_web', + description: 'Search the web for a query', + input_schema: { + type: 'object', + properties: sampleTool.parameters.properties, + required: sampleTool.parameters.required, + }, + }) + }) + + it('preserves an empty description', () => { + expect(adaptAnthropicToolSchema(noDescriptionTool)).toEqual({ + name: 'noop', + description: '', + input_schema: { + type: 'object', + properties: noDescriptionTool.parameters.properties, + required: noDescriptionTool.parameters.required, + }, + }) + }) + + it('passes through empty parameters as undefined properties/required', () => { + expect(adaptAnthropicToolSchema(emptyParametersTool)).toEqual({ + name: 'ping', + description: 'Ping the server', + input_schema: { + type: 'object', + properties: undefined, + required: undefined, + }, + }) + }) +}) diff --git a/apps/sim/providers/tool-schema-adapter.ts b/apps/sim/providers/tool-schema-adapter.ts new file mode 100644 index 00000000000..8c35651fa35 --- /dev/null +++ b/apps/sim/providers/tool-schema-adapter.ts @@ -0,0 +1,56 @@ +import type { ProviderToolConfig } from '@/providers/types' + +/** + * OpenAI Chat Completions-style tool definition, shared by every + * OpenAI-compatible provider (groq, mistral, together, etc.). + */ +export interface OpenAIChatToolSchema { + type: 'function' + function: { + name: string + description: string + parameters: ProviderToolConfig['parameters'] + } +} + +/** + * Anthropic Messages API tool definition. + */ +export interface AnthropicToolSchema { + name: string + description: string + input_schema: { + type: 'object' + properties: ProviderToolConfig['parameters']['properties'] + required: ProviderToolConfig['parameters']['required'] + } +} + +/** + * Adapts a tool config to the OpenAI Chat Completions function-wrapped shape. + */ +export function adaptOpenAIChatToolSchema(tool: ProviderToolConfig): OpenAIChatToolSchema { + return { + type: 'function', + function: { + name: tool.id, + description: tool.description, + parameters: tool.parameters, + }, + } +} + +/** + * Adapts a tool config to the Anthropic Messages `input_schema` shape. + */ +export function adaptAnthropicToolSchema(tool: ProviderToolConfig): AnthropicToolSchema { + return { + name: tool.id, + description: tool.description, + input_schema: { + type: 'object', + properties: tool.parameters.properties, + required: tool.parameters.required, + }, + } +} diff --git a/apps/sim/providers/vllm/index.ts b/apps/sim/providers/vllm/index.ts index 87610d9c43e..7251ec1c31a 100644 --- a/apps/sim/providers/vllm/index.ts +++ b/apps/sim/providers/vllm/index.ts @@ -7,6 +7,8 @@ import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { Message, @@ -126,14 +128,7 @@ export const vllmProvider: ProviderConfig = { const formattedMessages = formatMessagesForProvider(allMessages, 'vllm') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined const payload: any = { @@ -199,80 +194,43 @@ export const vllmProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromVLLMStream(streamResponse, (content, usage) => { - let cleanContent = content - if (cleanContent && request.responseFormat) { - cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() - } - - streamingResult.execution.output.content = cleanContent - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } - - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + createStream: ({ output, finalizeTiming }) => + createReadableStreamFromVLLMStream(streamResponse, (content, usage) => { + let cleanContent = content + if (cleanContent && request.responseFormat) { + cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() + } - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + output.content = cleanContent + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = - streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = - streamEndTime - providerStartTime + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, } - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution - return streamingResult as StreamingExecution + finalizeTiming() + }), + }) + + return streamingResult } const initialCallTime = Date.now() @@ -556,76 +514,65 @@ export const vllmProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromVLLMStream(streamResponse, (content, usage) => { - let cleanContent = content - if (cleanContent && request.responseFormat) { - cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, + }, + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + createStream: ({ output }) => + createReadableStreamFromVLLMStream(streamResponse, (content, usage) => { + let cleanContent = content + if (cleanContent && request.responseFormat) { + cleanContent = cleanContent.replace(/```json\n?|\n?```/g, '').trim() + } - streamingResult.execution.output.content = cleanContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } + output.content = cleanContent + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - }, - } as StreamingExecution + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() diff --git a/apps/sim/providers/xai/index.ts b/apps/sim/providers/xai/index.ts index 0d2dcb7b27c..42ebeb1254c 100644 --- a/apps/sim/providers/xai/index.ts +++ b/apps/sim/providers/xai/index.ts @@ -6,6 +6,8 @@ import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' import { formatMessagesForProvider } from '@/providers/attachments' import { getProviderDefaultModel, getProviderModels } from '@/providers/models' +import { createStreamingExecution } from '@/providers/streaming-execution' +import { adaptOpenAIChatToolSchema } from '@/providers/tool-schema-adapter' import { enrichLastModelSegmentFromChatCompletions } from '@/providers/trace-enrichment' import type { Message, @@ -79,14 +81,7 @@ export const xAIProvider: ProviderConfig = { } const formattedMessages = formatMessagesForProvider(allMessages, 'xai') as Message[] const tools = request.tools?.length - ? request.tools.map((tool) => ({ - type: 'function', - function: { - name: tool.id, - description: tool.description, - parameters: tool.parameters, - }, - })) + ? request.tools.map((tool) => adaptOpenAIChatToolSchema(tool)) : undefined if (tools?.length && request.responseFormat) { logger.warn( @@ -125,60 +120,37 @@ export const xAIProvider: ProviderConfig = { request.abortSignal ? { signal: request.abortSignal } : undefined ) - const streamingResult = { - stream: createReadableStreamFromXAIStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.prompt_tokens, - output: usage.completion_tokens, - total: usage.total_tokens, - } + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { kind: 'simple', segmentName: request.model }, + initialTokens: { input: 0, output: 0, total: 0 }, + initialCost: { input: 0, output: 0, total: 0 }, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromXAIStream(streamResponse, (content, usage) => { + output.content = content + output.tokens = { + input: usage.prompt_tokens, + output: usage.completion_tokens, + total: usage.total_tokens, + } - const costResult = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { input: 0, output: 0, total: 0 }, - toolCalls: undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - timeSegments: [ - { - type: 'model', - name: request.model, - startTime: providerStartTime, - endTime: Date.now(), - duration: Date.now() - providerStartTime, - }, - ], - }, - cost: { input: 0, output: 0, total: 0 }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, - }, - } + const costResult = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerStartTime = Date.now() const providerStartTimeISO = new Date(providerStartTime).toISOString() @@ -520,73 +492,62 @@ export const xAIProvider: ProviderConfig = { const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output) - const streamingResult = { - stream: createReadableStreamFromXAIStream(streamResponse as any, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: tokens.input + usage.prompt_tokens, - output: tokens.output + usage.completion_tokens, - total: tokens.total + usage.total_tokens, - } - - const streamCost = calculateCost( - request.model, - usage.prompt_tokens, - usage.completion_tokens - ) - const tc = sumToolCosts(toolResults) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - toolCost: tc || undefined, - total: accumulatedCost.total + streamCost.total + tc, - } - }), - execution: { - success: true, - output: { - content: '', - model: request.model, - tokens: { - input: tokens.input, - output: tokens.output, - total: tokens.total, - }, - toolCalls: - toolCalls.length > 0 - ? { - list: toolCalls, - count: toolCalls.length, - } - : undefined, - providerTiming: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - modelTime: modelTime, - toolsTime: toolsTime, - firstResponseTime: firstResponseTime, - iterations: iterationCount + 1, - timeSegments: timeSegments, - }, - cost: { - input: accumulatedCost.input, - output: accumulatedCost.output, - toolCost: undefined as number | undefined, - total: accumulatedCost.total, - }, - }, - logs: [], - metadata: { - startTime: providerStartTimeISO, - endTime: new Date().toISOString(), - duration: Date.now() - providerStartTime, - }, - isStreaming: true, + const streamingResult = createStreamingExecution({ + model: request.model, + providerStartTime, + providerStartTimeISO, + timing: { + kind: 'accumulated', + modelTime, + toolsTime, + firstResponseTime, + iterations: iterationCount + 1, + timeSegments, }, - } + initialTokens: { + input: tokens.input, + output: tokens.output, + total: tokens.total, + }, + initialCost: { + input: accumulatedCost.input, + output: accumulatedCost.output, + toolCost: undefined as number | undefined, + total: accumulatedCost.total, + }, + toolCalls: + toolCalls.length > 0 + ? { + list: toolCalls, + count: toolCalls.length, + } + : undefined, + isStreaming: true, + createStream: ({ output }) => + createReadableStreamFromXAIStream(streamResponse as any, (content, usage) => { + output.content = content + output.tokens = { + input: tokens.input + usage.prompt_tokens, + output: tokens.output + usage.completion_tokens, + total: tokens.total + usage.total_tokens, + } + + const streamCost = calculateCost( + request.model, + usage.prompt_tokens, + usage.completion_tokens + ) + const tc = sumToolCosts(toolResults) + output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + toolCost: tc || undefined, + total: accumulatedCost.total + streamCost.total + tc, + } + }), + }) - return streamingResult as StreamingExecution + return streamingResult } const providerEndTime = Date.now() const providerEndTimeISO = new Date(providerEndTime).toISOString() diff --git a/apps/sim/tools/context_dev/classify_naics.ts b/apps/sim/tools/context_dev/classify_naics.ts new file mode 100644 index 00000000000..1386b672487 --- /dev/null +++ b/apps/sim/tools/context_dev/classify_naics.ts @@ -0,0 +1,96 @@ +import type { + ContextDevClassifyNaicsParams, + ContextDevClassifyNaicsResponse, +} from '@/tools/context_dev/types' +import { CLASSIFICATION_CODE_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevClassifyNaicsTool: ToolConfig< + ContextDevClassifyNaicsParams, + ContextDevClassifyNaicsResponse +> = { + id: 'context_dev_classify_naics', + name: 'Context.dev Classify NAICS', + description: 'Classify a brand into NAICS industry codes from its domain or company name.', + version: '1.0.0', + + params: { + input: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Brand domain or company name to classify (e.g., "stripe.com" or "Stripe")', + }, + minResults: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Minimum number of codes to return (1-10, default: 1)', + }, + maxResults: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of codes to return (1-10, default: 5)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/naics`) + appendParam(url.searchParams, 'input', params.input) + appendParam(url.searchParams, 'minResults', params.minResults) + appendParam(url.searchParams, 'maxResults', params.maxResults) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + domain: data.domain ?? null, + type: data.type ?? null, + codes: data.codes ?? [], + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Classification status' }, + domain: { type: 'string', description: 'Resolved domain', optional: true }, + type: { type: 'string', description: 'Input type that was resolved', optional: true }, + codes: { + type: 'array', + description: 'Matched NAICS codes with name and confidence', + items: { type: 'object', properties: CLASSIFICATION_CODE_OUTPUT_PROPERTIES }, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/classify_sic.ts b/apps/sim/tools/context_dev/classify_sic.ts new file mode 100644 index 00000000000..a45b9ebb5d6 --- /dev/null +++ b/apps/sim/tools/context_dev/classify_sic.ts @@ -0,0 +1,117 @@ +import type { + ContextDevClassifySicParams, + ContextDevClassifySicResponse, +} from '@/tools/context_dev/types' +import { CLASSIFICATION_CODE_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevClassifySicTool: ToolConfig< + ContextDevClassifySicParams, + ContextDevClassifySicResponse +> = { + id: 'context_dev_classify_sic', + name: 'Context.dev Classify SIC', + description: 'Classify a brand into SIC industry codes from its domain or company name.', + version: '1.0.0', + + params: { + input: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Brand domain or company name to classify (e.g., "stripe.com" or "Stripe")', + }, + type: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'SIC taxonomy version: "original_sic" (default) or "latest_sec"', + }, + minResults: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Minimum number of codes to return (1-10, default: 1)', + }, + maxResults: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of codes to return (1-10, default: 5)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/sic`) + appendParam(url.searchParams, 'input', params.input) + appendParam(url.searchParams, 'type', params.type) + appendParam(url.searchParams, 'minResults', params.minResults) + appendParam(url.searchParams, 'maxResults', params.maxResults) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + domain: data.domain ?? null, + type: data.type ?? null, + classification: data.classification ?? null, + codes: data.codes ?? [], + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Classification status' }, + domain: { type: 'string', description: 'Resolved domain', optional: true }, + type: { type: 'string', description: 'Input type that was resolved', optional: true }, + classification: { + type: 'string', + description: 'SIC taxonomy version used (original_sic or latest_sec)', + optional: true, + }, + codes: { + type: 'array', + description: 'Matched SIC codes with name, confidence, and group metadata', + items: { + type: 'object', + properties: { + ...CLASSIFICATION_CODE_OUTPUT_PROPERTIES, + majorGroup: { type: 'string', description: 'Major group code (original_sic only)' }, + majorGroupName: { type: 'string', description: 'Major group name (original_sic only)' }, + office: { type: 'string', description: 'SEC office (latest_sec only)' }, + }, + }, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/crawl.ts b/apps/sim/tools/context_dev/crawl.ts new file mode 100644 index 00000000000..6184899363b --- /dev/null +++ b/apps/sim/tools/context_dev/crawl.ts @@ -0,0 +1,144 @@ +import type { ContextDevCrawlParams, ContextDevCrawlResponse } from '@/tools/context_dev/types' +import { CRAWL_RESULT_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevCrawlTool: ToolConfig = { + id: 'context_dev_crawl', + name: 'Context.dev Crawl', + description: 'Crawl an entire website and return each discovered page as clean markdown.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The starting URL to crawl (must include http:// or https://)', + }, + maxPages: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of pages to crawl (1-500, default: 100)', + }, + maxDepth: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum link depth from the starting URL (0 = start page only)', + }, + urlRegex: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Regex pattern to filter which URLs are crawled', + }, + includeLinks: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Preserve hyperlinks in the markdown output (default: true)', + }, + includeImages: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Include image references in the markdown output (default: false)', + }, + useMainContentOnly: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Strip headers, footers, and sidebars from each page (default: false)', + }, + followSubdomains: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Follow links to subdomains of the starting domain (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 86400000)', + }, + waitForMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Browser wait time after page load in milliseconds (0-30000)', + }, + stopAfterMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Soft crawl time budget in milliseconds (10000-110000, default: 80000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/web/crawl`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { url: params.url } + if (params.maxPages != null) body.maxPages = params.maxPages + if (params.maxDepth != null) body.maxDepth = params.maxDepth + if (params.urlRegex) body.urlRegex = params.urlRegex + if (params.includeLinks != null) body.includeLinks = params.includeLinks + if (params.includeImages != null) body.includeImages = params.includeImages + if (params.useMainContentOnly != null) body.useMainContentOnly = params.useMainContentOnly + if (params.followSubdomains != null) body.followSubdomains = params.followSubdomains + if (params.maxAgeMs != null) body.maxAgeMs = params.maxAgeMs + if (params.waitForMs != null) body.waitForMs = params.waitForMs + if (params.stopAfterMs != null) body.stopAfterMs = params.stopAfterMs + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + results: data.results ?? [], + metadata: data.metadata ?? {}, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + results: { + type: 'array', + description: 'Crawled pages with markdown content and per-page metadata', + items: { type: 'object', properties: CRAWL_RESULT_OUTPUT_PROPERTIES }, + }, + metadata: { + type: 'object', + description: 'Crawl summary (numUrls, maxCrawlDepth, numSucceeded, numFailed, numSkipped)', + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/extract.ts b/apps/sim/tools/context_dev/extract.ts new file mode 100644 index 00000000000..21cefdb1e5d --- /dev/null +++ b/apps/sim/tools/context_dev/extract.ts @@ -0,0 +1,135 @@ +import type { ContextDevExtractParams, ContextDevExtractResponse } from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevExtractTool: ToolConfig = + { + id: 'context_dev_extract', + name: 'Context.dev Extract', + description: 'Crawl a website and extract structured data matching a provided JSON schema.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The starting website URL (must include http:// or https://)', + }, + schema: { + type: 'json', + required: true, + visibility: 'user-or-llm', + description: 'JSON Schema describing the structure of the data to extract', + }, + instructions: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional extraction guidance for link prioritization (max 2000 chars)', + }, + factCheck: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Require extracted values to be grounded in page facts (default: false)', + }, + followSubdomains: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Follow links on subdomains of the starting domain (default: false)', + }, + maxPages: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of pages to analyze (1-50, default: 5)', + }, + maxDepth: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum link depth from the starting URL', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 604800000)', + }, + stopAfterMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Soft crawl time budget in milliseconds (10000-110000, default: 80000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/web/extract`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { url: params.url, schema: params.schema } + if (params.instructions) body.instructions = params.instructions + if (params.factCheck != null) body.factCheck = params.factCheck + if (params.followSubdomains != null) body.followSubdomains = params.followSubdomains + if (params.maxPages != null) body.maxPages = params.maxPages + if (params.maxDepth != null) body.maxDepth = params.maxDepth + if (params.maxAgeMs != null) body.maxAgeMs = params.maxAgeMs + if (params.stopAfterMs != null) body.stopAfterMs = params.stopAfterMs + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + url: data.url ?? '', + urlsAnalyzed: data.urls_analyzed ?? [], + data: data.data ?? {}, + metadata: data.metadata ?? {}, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Extraction status' }, + url: { type: 'string', description: 'The starting URL that was crawled' }, + urlsAnalyzed: { + type: 'array', + description: 'URLs that were analyzed during extraction', + items: { type: 'string', description: 'Analyzed page URL' }, + }, + data: { type: 'json', description: 'Structured data matching the requested schema' }, + metadata: { + type: 'object', + description: 'Crawl summary (numUrls, maxCrawlDepth, numSucceeded, numFailed, numSkipped)', + }, + ...CREDIT_OUTPUTS, + }, + } diff --git a/apps/sim/tools/context_dev/extract_product.ts b/apps/sim/tools/context_dev/extract_product.ts new file mode 100644 index 00000000000..a70f39fa96f --- /dev/null +++ b/apps/sim/tools/context_dev/extract_product.ts @@ -0,0 +1,90 @@ +import type { + ContextDevExtractProductParams, + ContextDevExtractProductResponse, +} from '@/tools/context_dev/types' +import { PRODUCT_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevExtractProductTool: ToolConfig< + ContextDevExtractProductParams, + ContextDevExtractProductResponse +> = { + id: 'context_dev_extract_product', + name: 'Context.dev Extract Product', + description: 'Detect and extract structured product details from a single product page URL.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The product page URL (must include http:// or https://)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 604800000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/brand/ai/product`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { url: params.url } + if (params.maxAgeMs != null) body.maxAgeMs = params.maxAgeMs + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + isProductPage: data.is_product_page ?? false, + platform: data.platform ?? null, + product: data.product ?? null, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + isProductPage: { type: 'boolean', description: 'Whether the URL is a product page' }, + platform: { + type: 'string', + description: 'Detected platform (amazon, tiktok_shop, etsy, generic)', + optional: true, + }, + product: { + type: 'object', + description: 'Extracted product details', + properties: PRODUCT_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/extract_products.ts b/apps/sim/tools/context_dev/extract_products.ts new file mode 100644 index 00000000000..aa22102a446 --- /dev/null +++ b/apps/sim/tools/context_dev/extract_products.ts @@ -0,0 +1,89 @@ +import type { + ContextDevExtractProductsParams, + ContextDevExtractProductsResponse, +} from '@/tools/context_dev/types' +import { PRODUCT_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevExtractProductsTool: ToolConfig< + ContextDevExtractProductsParams, + ContextDevExtractProductsResponse +> = { + id: 'context_dev_extract_products', + name: 'Context.dev Extract Products', + description: "Extract the product catalog from a brand's website by domain (beta).", + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to extract products from (e.g., "example.com")', + }, + maxProducts: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of products to extract (1-12)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 604800000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/brand/ai/products`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { domain: params.domain } + if (params.maxProducts != null) body.maxProducts = params.maxProducts + if (params.maxAgeMs != null) body.maxAgeMs = params.maxAgeMs + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + products: data.products ?? [], + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + products: { + type: 'array', + description: 'Extracted products with pricing, features, and metadata', + items: { type: 'object', properties: PRODUCT_OUTPUT_PROPERTIES }, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/get_brand.ts b/apps/sim/tools/context_dev/get_brand.ts new file mode 100644 index 00000000000..daffe65f08e --- /dev/null +++ b/apps/sim/tools/context_dev/get_brand.ts @@ -0,0 +1,88 @@ +import type { ContextDevBrandResponse, ContextDevGetBrandParams } from '@/tools/context_dev/types' +import { BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevGetBrandTool: ToolConfig = + { + id: 'context_dev_get_brand', + name: 'Context.dev Get Brand', + description: + 'Retrieve brand data for a domain: logos, colors, backdrops, socials, address, and industry.', + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to retrieve brand data for (e.g., "airbnb.com")', + }, + forceLanguage: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Override the detected language with a supported language code', + }, + maxSpeed: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Skip time-consuming operations for a faster response (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/retrieve`) + appendParam(url.searchParams, 'domain', params.domain) + appendParam(url.searchParams, 'force_language', params.forceLanguage) + appendParam(url.searchParams, 'maxSpeed', params.maxSpeed) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Retrieval status' }, + brand: { + type: 'object', + description: 'Brand data object', + properties: BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, + } diff --git a/apps/sim/tools/context_dev/get_brand_by_email.ts b/apps/sim/tools/context_dev/get_brand_by_email.ts new file mode 100644 index 00000000000..e93fbacdfdf --- /dev/null +++ b/apps/sim/tools/context_dev/get_brand_by_email.ts @@ -0,0 +1,93 @@ +import type { + ContextDevBrandResponse, + ContextDevGetBrandByEmailParams, +} from '@/tools/context_dev/types' +import { BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevGetBrandByEmailTool: ToolConfig< + ContextDevGetBrandByEmailParams, + ContextDevBrandResponse +> = { + id: 'context_dev_get_brand_by_email', + name: 'Context.dev Get Brand by Email', + description: + 'Retrieve brand data from a work email address. Free/disposable emails are rejected (422).', + version: '1.0.0', + + params: { + email: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Work email address; the domain is extracted (free providers are rejected)', + }, + forceLanguage: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Override the detected language with a supported language code', + }, + maxSpeed: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Skip time-consuming operations for a faster response (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/retrieve-by-email`) + appendParam(url.searchParams, 'email', params.email) + appendParam(url.searchParams, 'force_language', params.forceLanguage) + appendParam(url.searchParams, 'maxSpeed', params.maxSpeed) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Retrieval status' }, + brand: { + type: 'object', + description: 'Brand data object', + properties: BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/get_brand_by_name.ts b/apps/sim/tools/context_dev/get_brand_by_name.ts new file mode 100644 index 00000000000..78f8970e49e --- /dev/null +++ b/apps/sim/tools/context_dev/get_brand_by_name.ts @@ -0,0 +1,100 @@ +import type { + ContextDevBrandResponse, + ContextDevGetBrandByNameParams, +} from '@/tools/context_dev/types' +import { BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevGetBrandByNameTool: ToolConfig< + ContextDevGetBrandByNameParams, + ContextDevBrandResponse +> = { + id: 'context_dev_get_brand_by_name', + name: 'Context.dev Get Brand by Name', + description: + 'Retrieve brand data by company name: logos, colors, socials, address, and industry.', + version: '1.0.0', + + params: { + name: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Company name to retrieve brand data for (3-30 chars, e.g., "Apple Inc")', + }, + countryGl: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ISO 2-letter country code to prioritize (e.g., "us")', + }, + forceLanguage: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Override the detected language with a supported language code', + }, + maxSpeed: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Skip time-consuming operations for a faster response (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/retrieve-by-name`) + appendParam(url.searchParams, 'name', params.name) + appendParam(url.searchParams, 'country_gl', params.countryGl) + appendParam(url.searchParams, 'force_language', params.forceLanguage) + appendParam(url.searchParams, 'maxSpeed', params.maxSpeed) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Retrieval status' }, + brand: { + type: 'object', + description: 'Brand data object', + properties: BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/get_brand_by_ticker.ts b/apps/sim/tools/context_dev/get_brand_by_ticker.ts new file mode 100644 index 00000000000..ff0d92b4018 --- /dev/null +++ b/apps/sim/tools/context_dev/get_brand_by_ticker.ts @@ -0,0 +1,99 @@ +import type { + ContextDevBrandResponse, + ContextDevGetBrandByTickerParams, +} from '@/tools/context_dev/types' +import { BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevGetBrandByTickerTool: ToolConfig< + ContextDevGetBrandByTickerParams, + ContextDevBrandResponse +> = { + id: 'context_dev_get_brand_by_ticker', + name: 'Context.dev Get Brand by Ticker', + description: 'Retrieve brand data for a public company by its stock ticker symbol.', + version: '1.0.0', + + params: { + ticker: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Stock ticker symbol (e.g., "AAPL", "GOOGL", "BRK.A")', + }, + tickerExchange: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Exchange code for the ticker (e.g., "NASDAQ", "NYSE", "LSE"). Default: NASDAQ', + }, + forceLanguage: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Override the detected language with a supported language code', + }, + maxSpeed: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Skip time-consuming operations for a faster response (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/retrieve-by-ticker`) + appendParam(url.searchParams, 'ticker', params.ticker) + appendParam(url.searchParams, 'ticker_exchange', params.tickerExchange) + appendParam(url.searchParams, 'force_language', params.forceLanguage) + appendParam(url.searchParams, 'maxSpeed', params.maxSpeed) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Retrieval status' }, + brand: { + type: 'object', + description: 'Brand data object', + properties: BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/get_brand_simplified.ts b/apps/sim/tools/context_dev/get_brand_simplified.ts new file mode 100644 index 00000000000..f120104139c --- /dev/null +++ b/apps/sim/tools/context_dev/get_brand_simplified.ts @@ -0,0 +1,78 @@ +import type { + ContextDevGetBrandSimplifiedParams, + ContextDevGetBrandSimplifiedResponse, +} from '@/tools/context_dev/types' +import { SIMPLIFIED_BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevGetBrandSimplifiedTool: ToolConfig< + ContextDevGetBrandSimplifiedParams, + ContextDevGetBrandSimplifiedResponse +> = { + id: 'context_dev_get_brand_simplified', + name: 'Context.dev Get Brand (Simplified)', + description: 'Retrieve essential brand data for a domain: title, colors, logos, and backdrops.', + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to retrieve simplified brand data for (e.g., "airbnb.com")', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/retrieve-simplified`) + appendParam(url.searchParams, 'domain', params.domain) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Retrieval status' }, + brand: { + type: 'object', + description: 'Simplified brand data (domain, title, colors, logos, backdrops)', + properties: SIMPLIFIED_BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/identify_transaction.ts b/apps/sim/tools/context_dev/identify_transaction.ts new file mode 100644 index 00000000000..47cba312dce --- /dev/null +++ b/apps/sim/tools/context_dev/identify_transaction.ts @@ -0,0 +1,121 @@ +import type { + ContextDevBrandResponse, + ContextDevIdentifyTransactionParams, +} from '@/tools/context_dev/types' +import { BRAND_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + parseContextDevResponse, + transformBrandResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevIdentifyTransactionTool: ToolConfig< + ContextDevIdentifyTransactionParams, + ContextDevBrandResponse +> = { + id: 'context_dev_identify_transaction', + name: 'Context.dev Identify Transaction', + description: + 'Identify the brand behind a raw bank/card transaction descriptor and return its brand data.', + version: '1.0.0', + + params: { + transactionInfo: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The raw transaction descriptor or identifier to resolve to a brand', + }, + countryGl: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ISO 2-letter country code from the transaction (e.g., "us", "gb")', + }, + city: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'City name to prioritize in the search', + }, + mcc: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Merchant Category Code for the business category', + }, + phone: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Phone number from the transaction for verification', + }, + highConfidenceOnly: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Enforce additional verification steps for higher confidence (default: false)', + }, + forceLanguage: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Override the detected language with a supported language code', + }, + maxSpeed: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Skip time-consuming operations for a faster response (default: false)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/brand/transaction_identifier`) + appendParam(url.searchParams, 'transaction_info', params.transactionInfo) + appendParam(url.searchParams, 'country_gl', params.countryGl) + appendParam(url.searchParams, 'city', params.city) + appendParam(url.searchParams, 'mcc', params.mcc) + appendParam(url.searchParams, 'phone', params.phone) + appendParam(url.searchParams, 'high_confidence_only', params.highConfidenceOnly) + appendParam(url.searchParams, 'force_language', params.forceLanguage) + appendParam(url.searchParams, 'maxSpeed', params.maxSpeed) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { success: true, output: transformBrandResponse(data) } + }, + + outputs: { + status: { type: 'string', description: 'Identification status' }, + brand: { + type: 'object', + description: 'Brand data for the identified merchant', + properties: BRAND_OUTPUT_PROPERTIES, + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/index.ts b/apps/sim/tools/context_dev/index.ts new file mode 100644 index 00000000000..9848723ebf3 --- /dev/null +++ b/apps/sim/tools/context_dev/index.ts @@ -0,0 +1,22 @@ +export { contextDevClassifyNaicsTool } from '@/tools/context_dev/classify_naics' +export { contextDevClassifySicTool } from '@/tools/context_dev/classify_sic' +export { contextDevCrawlTool } from '@/tools/context_dev/crawl' +export { contextDevExtractTool } from '@/tools/context_dev/extract' +export { contextDevExtractProductTool } from '@/tools/context_dev/extract_product' +export { contextDevExtractProductsTool } from '@/tools/context_dev/extract_products' +export { contextDevGetBrandTool } from '@/tools/context_dev/get_brand' +export { contextDevGetBrandByEmailTool } from '@/tools/context_dev/get_brand_by_email' +export { contextDevGetBrandByNameTool } from '@/tools/context_dev/get_brand_by_name' +export { contextDevGetBrandByTickerTool } from '@/tools/context_dev/get_brand_by_ticker' +export { contextDevGetBrandSimplifiedTool } from '@/tools/context_dev/get_brand_simplified' +export { contextDevIdentifyTransactionTool } from '@/tools/context_dev/identify_transaction' +export { contextDevMapTool } from '@/tools/context_dev/map' +export { contextDevPrefetchByEmailTool } from '@/tools/context_dev/prefetch_by_email' +export { contextDevPrefetchDomainTool } from '@/tools/context_dev/prefetch_domain' +export { contextDevScrapeFontsTool } from '@/tools/context_dev/scrape_fonts' +export { contextDevScrapeHtmlTool } from '@/tools/context_dev/scrape_html' +export { contextDevScrapeImagesTool } from '@/tools/context_dev/scrape_images' +export { contextDevScrapeMarkdownTool } from '@/tools/context_dev/scrape_markdown' +export { contextDevScrapeStyleguideTool } from '@/tools/context_dev/scrape_styleguide' +export { contextDevScreenshotTool } from '@/tools/context_dev/screenshot' +export { contextDevSearchTool } from '@/tools/context_dev/search' diff --git a/apps/sim/tools/context_dev/map.ts b/apps/sim/tools/context_dev/map.ts new file mode 100644 index 00000000000..c8491b02d5e --- /dev/null +++ b/apps/sim/tools/context_dev/map.ts @@ -0,0 +1,90 @@ +import type { ContextDevMapParams, ContextDevMapResponse } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevMapTool: ToolConfig = { + id: 'context_dev_map', + name: 'Context.dev Map', + description: 'Build a sitemap of a domain and return every discovered page URL.', + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to build a sitemap for (e.g., "example.com")', + }, + maxLinks: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of URLs to return (1-100000, default: 10000)', + }, + urlRegex: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'RE2-compatible regex to filter URLs (max 256 chars)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/scrape/sitemap`) + appendParam(url.searchParams, 'domain', params.domain) + appendParam(url.searchParams, 'maxLinks', params.maxLinks) + appendParam(url.searchParams, 'urlRegex', params.urlRegex) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + domain: data.domain ?? '', + urls: data.urls ?? [], + meta: data.meta ?? {}, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + domain: { type: 'string', description: 'The domain that was mapped' }, + urls: { + type: 'array', + description: 'All page URLs discovered from the sitemap', + items: { type: 'string', description: 'Page URL' }, + }, + meta: { + type: 'object', + description: 'Sitemap discovery stats (sitemapsDiscovered, sitemapsFetched, errors)', + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/prefetch_by_email.ts b/apps/sim/tools/context_dev/prefetch_by_email.ts new file mode 100644 index 00000000000..af0ed013cd6 --- /dev/null +++ b/apps/sim/tools/context_dev/prefetch_by_email.ts @@ -0,0 +1,75 @@ +import type { + ContextDevPrefetchByEmailParams, + ContextDevPrefetchResponse, +} from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevPrefetchByEmailTool: ToolConfig< + ContextDevPrefetchByEmailParams, + ContextDevPrefetchResponse +> = { + id: 'context_dev_prefetch_by_email', + name: 'Context.dev Prefetch by Email', + description: + "Queue an email's domain for brand-data prefetching to reduce later latency (subscribers; 0 credits). Free/disposable emails are rejected.", + version: '1.0.0', + + params: { + email: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Work email address whose domain should be prefetched (free providers rejected)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/brand/prefetch-by-email`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { email: params.email } + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + message: data.message ?? '', + domain: data.domain ?? '', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Prefetch status' }, + message: { type: 'string', description: 'Human-readable prefetch result message' }, + domain: { type: 'string', description: 'The domain queued for prefetching' }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/prefetch_domain.ts b/apps/sim/tools/context_dev/prefetch_domain.ts new file mode 100644 index 00000000000..77d33d08520 --- /dev/null +++ b/apps/sim/tools/context_dev/prefetch_domain.ts @@ -0,0 +1,75 @@ +import type { + ContextDevPrefetchDomainParams, + ContextDevPrefetchResponse, +} from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevPrefetchDomainTool: ToolConfig< + ContextDevPrefetchDomainParams, + ContextDevPrefetchResponse +> = { + id: 'context_dev_prefetch_domain', + name: 'Context.dev Prefetch Domain', + description: + 'Queue a domain for brand-data prefetching to reduce latency on later requests (subscribers; 0 credits).', + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to prefetch brand data for (e.g., "example.com")', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/brand/prefetch`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { domain: params.domain } + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + message: data.message ?? '', + domain: data.domain ?? '', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Prefetch status' }, + message: { type: 'string', description: 'Human-readable prefetch result message' }, + domain: { type: 'string', description: 'The domain queued for prefetching' }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/scrape_fonts.ts b/apps/sim/tools/context_dev/scrape_fonts.ts new file mode 100644 index 00000000000..c64c676bf9e --- /dev/null +++ b/apps/sim/tools/context_dev/scrape_fonts.ts @@ -0,0 +1,92 @@ +import type { + ContextDevScrapeFontsParams, + ContextDevScrapeFontsResponse, +} from '@/tools/context_dev/types' +import { FONT_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevScrapeFontsTool: ToolConfig< + ContextDevScrapeFontsParams, + ContextDevScrapeFontsResponse +> = { + id: 'context_dev_scrape_fonts', + name: 'Context.dev Scrape Fonts', + description: 'Extract the font families, usage stats, and font files used by a domain.', + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to extract fonts from (e.g., "example.com")', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/fonts`) + appendParam(url.searchParams, 'domain', params.domain) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + domain: data.domain ?? '', + fonts: data.fonts ?? [], + fontLinks: data.fontLinks ?? {}, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Extraction status' }, + domain: { type: 'string', description: 'The domain that was analyzed' }, + fonts: { + type: 'array', + description: 'Fonts with usage statistics and fallbacks', + items: { type: 'object', properties: FONT_OUTPUT_PROPERTIES }, + }, + fontLinks: { + type: 'json', + description: 'Font family download links keyed by font name (type, files, category)', + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/scrape_html.ts b/apps/sim/tools/context_dev/scrape_html.ts new file mode 100644 index 00000000000..b4cf5d42e2f --- /dev/null +++ b/apps/sim/tools/context_dev/scrape_html.ts @@ -0,0 +1,106 @@ +import type { + ContextDevScrapeHtmlParams, + ContextDevScrapeHtmlResponse, +} from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevScrapeHtmlTool: ToolConfig< + ContextDevScrapeHtmlParams, + ContextDevScrapeHtmlResponse +> = { + id: 'context_dev_scrape_html', + name: 'Context.dev Scrape HTML', + description: 'Scrape any URL and return the raw HTML content of the page.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The full URL to scrape (must include http:// or https://)', + }, + useMainContentOnly: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Return only main content, excluding headers, footers, and navigation', + }, + includeFrames: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Render iframe contents inline into the returned HTML (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 86400000)', + }, + waitForMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Browser wait time after page load in milliseconds (0-30000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/scrape/html`) + appendParam(url.searchParams, 'url', params.url) + appendParam(url.searchParams, 'useMainContentOnly', params.useMainContentOnly) + appendParam(url.searchParams, 'includeFrames', params.includeFrames) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'waitForMs', params.waitForMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + html: data.html ?? '', + url: data.url ?? '', + type: data.type ?? 'html', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + html: { type: 'string', description: 'Raw HTML content of the page' }, + url: { type: 'string', description: 'The scraped URL' }, + type: { + type: 'string', + description: 'Detected content type (html, xml, json, text, csv, markdown, svg, pdf)', + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/scrape_images.ts b/apps/sim/tools/context_dev/scrape_images.ts new file mode 100644 index 00000000000..d2dfade8acb --- /dev/null +++ b/apps/sim/tools/context_dev/scrape_images.ts @@ -0,0 +1,115 @@ +import type { + ContextDevScrapeImagesParams, + ContextDevScrapeImagesResponse, +} from '@/tools/context_dev/types' +import { IMAGE_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevScrapeImagesTool: ToolConfig< + ContextDevScrapeImagesParams, + ContextDevScrapeImagesResponse +> = { + id: 'context_dev_scrape_images', + name: 'Context.dev Scrape Images', + description: 'Discover every image asset on a page, with optional dimension and type enrichment.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The full URL to scrape images from (must include http:// or https://)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 86400000)', + }, + waitForMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Browser wait time after page load in milliseconds (0-30000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + enrichResolution: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Measure image dimensions (enables 5-credit enrichment)', + }, + enrichHostedUrl: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Host images on a CDN and return their URL and MIME type (enables enrichment)', + }, + enrichClassification: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Classify each image by visual asset type (enables enrichment)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/scrape/images`) + appendParam(url.searchParams, 'url', params.url) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'waitForMs', params.waitForMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + appendParam(url.searchParams, 'enrichment[resolution]', params.enrichResolution) + appendParam(url.searchParams, 'enrichment[hostedUrl]', params.enrichHostedUrl) + appendParam(url.searchParams, 'enrichment[classification]', params.enrichClassification) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + success: data.success ?? true, + images: data.images ?? [], + url: data.url ?? '', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + success: { type: 'boolean', description: 'Whether the scrape succeeded' }, + images: { + type: 'array', + description: 'Discovered image assets with source, element, type, and optional enrichment', + items: { type: 'object', properties: IMAGE_OUTPUT_PROPERTIES }, + }, + url: { type: 'string', description: 'The scraped URL' }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/scrape_markdown.ts b/apps/sim/tools/context_dev/scrape_markdown.ts new file mode 100644 index 00000000000..8faed1c8a57 --- /dev/null +++ b/apps/sim/tools/context_dev/scrape_markdown.ts @@ -0,0 +1,115 @@ +import type { + ContextDevScrapeMarkdownParams, + ContextDevScrapeMarkdownResponse, +} from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevScrapeMarkdownTool: ToolConfig< + ContextDevScrapeMarkdownParams, + ContextDevScrapeMarkdownResponse +> = { + id: 'context_dev_scrape_markdown', + name: 'Context.dev Scrape Markdown', + description: 'Scrape any URL and return clean, LLM-ready markdown content.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The full URL to scrape (must include http:// or https://)', + }, + useMainContentOnly: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Return only main content, excluding headers, footers, and navigation', + }, + includeLinks: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Preserve hyperlinks in the markdown output (default: true)', + }, + includeImages: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Include image references in the markdown output (default: false)', + }, + includeFrames: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Render iframe contents inline (default: false)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 86400000)', + }, + waitForMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Browser wait time after page load in milliseconds (0-30000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/scrape/markdown`) + appendParam(url.searchParams, 'url', params.url) + appendParam(url.searchParams, 'useMainContentOnly', params.useMainContentOnly) + appendParam(url.searchParams, 'includeLinks', params.includeLinks) + appendParam(url.searchParams, 'includeImages', params.includeImages) + appendParam(url.searchParams, 'includeFrames', params.includeFrames) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'waitForMs', params.waitForMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + markdown: data.markdown ?? '', + url: data.url ?? '', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + markdown: { type: 'string', description: 'Page content as clean markdown' }, + url: { type: 'string', description: 'The scraped URL' }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/scrape_styleguide.ts b/apps/sim/tools/context_dev/scrape_styleguide.ts new file mode 100644 index 00000000000..3be34c35d44 --- /dev/null +++ b/apps/sim/tools/context_dev/scrape_styleguide.ts @@ -0,0 +1,87 @@ +import type { + ContextDevScrapeStyleguideParams, + ContextDevScrapeStyleguideResponse, +} from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevScrapeStyleguideTool: ToolConfig< + ContextDevScrapeStyleguideParams, + ContextDevScrapeStyleguideResponse +> = { + id: 'context_dev_scrape_styleguide', + name: 'Context.dev Scrape Styleguide', + description: + "Extract a domain's design system: colors, typography, spacing, shadows, and UI components.", + version: '1.0.0', + + params: { + domain: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The domain to extract the styleguide from (e.g., "example.com")', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache max age in milliseconds (86400000-31536000000, default: 7776000000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/styleguide`) + appendParam(url.searchParams, 'domain', params.domain) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + status: data.status ?? '', + domain: data.domain ?? '', + styleguide: data.styleguide ?? null, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + status: { type: 'string', description: 'Extraction status' }, + domain: { type: 'string', description: 'The domain that was analyzed' }, + styleguide: { + type: 'json', + description: + 'Design system: mode, colors, typography, elementSpacing, shadows, fontLinks, components', + }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/screenshot.ts b/apps/sim/tools/context_dev/screenshot.ts new file mode 100644 index 00000000000..130402a8023 --- /dev/null +++ b/apps/sim/tools/context_dev/screenshot.ts @@ -0,0 +1,165 @@ +import type { + ContextDevScreenshotParams, + ContextDevScreenshotResponse, +} from '@/tools/context_dev/types' +import { + appendParam, + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig, ToolFileData } from '@/tools/types' + +/** Maps a lowercase image file extension to its MIME type. */ +const IMAGE_MIME_BY_EXTENSION: Record = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + webp: 'image/webp', + gif: 'image/gif', + avif: 'image/avif', +} + +/** + * Derives the file extension and MIME type for a stored screenshot from its URL, + * falling back to PNG when the URL has no recognizable image extension. + */ +function screenshotFileMeta(url: string): { extension: string; mimeType: string } { + try { + const ext = new URL(url).pathname.split('.').pop()?.toLowerCase() ?? '' + if (IMAGE_MIME_BY_EXTENSION[ext]) { + return { extension: ext, mimeType: IMAGE_MIME_BY_EXTENSION[ext] } + } + } catch { + // Unparseable URL — fall back to the default below. + } + return { extension: 'png', mimeType: 'image/png' } +} + +export const contextDevScreenshotTool: ToolConfig< + ContextDevScreenshotParams, + ContextDevScreenshotResponse +> = { + id: 'context_dev_screenshot', + name: 'Context.dev Screenshot', + description: 'Capture a screenshot of any web page and store it as a downloadable image file.', + version: '1.0.0', + + params: { + url: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The full URL to capture (must include http:// or https://)', + }, + fullScreenshot: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Capture the full scrollable page instead of just the viewport (default: false)', + }, + handleCookiePopup: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Attempt to dismiss cookie banners before capturing (default: false)', + }, + viewportWidth: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Viewport width in pixels (240-7680, default: 1920)', + }, + viewportHeight: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Viewport height in pixels (240-4320, default: 1080)', + }, + maxAgeMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Cache duration in milliseconds (0-2592000000, default: 86400000)', + }, + waitForMs: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Post-load delay before capturing in milliseconds (0-30000, default: 3000)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'GET', + url: (params) => { + const url = new URL(`${CONTEXT_DEV_BASE_URL}/web/screenshot`) + appendParam(url.searchParams, 'directUrl', params.url) + appendParam(url.searchParams, 'fullScreenshot', params.fullScreenshot) + appendParam(url.searchParams, 'handleCookiePopup', params.handleCookiePopup) + appendParam(url.searchParams, 'viewport[width]', params.viewportWidth) + appendParam(url.searchParams, 'viewport[height]', params.viewportHeight) + appendParam(url.searchParams, 'maxAgeMs', params.maxAgeMs) + appendParam(url.searchParams, 'waitForMs', params.waitForMs) + appendParam(url.searchParams, 'timeoutMS', params.timeoutMS) + return url.toString() + }, + headers: (params) => contextDevHeaders(params.apiKey), + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + const screenshotUrl: string = data.screenshot ?? '' + const domain: string | null = data.domain ?? null + + const { extension, mimeType } = screenshotFileMeta(screenshotUrl) + const file: ToolFileData | undefined = screenshotUrl + ? { + name: `${domain ?? 'screenshot'}.${extension}`, + mimeType, + url: screenshotUrl, + } + : undefined + + return { + success: true, + output: { + ...(file ? { file } : {}), + screenshotUrl, + screenshotType: data.screenshotType ?? null, + domain, + width: data.width ?? null, + height: data.height ?? null, + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + file: { type: 'file', description: 'Stored screenshot image file', optional: true }, + screenshotUrl: { type: 'string', description: 'Public URL of the captured screenshot' }, + screenshotType: { + type: 'string', + description: 'Screenshot type (viewport or fullPage)', + optional: true, + }, + domain: { type: 'string', description: 'Domain that was captured', optional: true }, + width: { type: 'number', description: 'Screenshot width in pixels', optional: true }, + height: { type: 'number', description: 'Screenshot height in pixels', optional: true }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/search.ts b/apps/sim/tools/context_dev/search.ts new file mode 100644 index 00000000000..2fd150d0b41 --- /dev/null +++ b/apps/sim/tools/context_dev/search.ts @@ -0,0 +1,108 @@ +import type { ContextDevSearchParams, ContextDevSearchResponse } from '@/tools/context_dev/types' +import { SEARCH_RESULT_OUTPUT_PROPERTIES } from '@/tools/context_dev/types' +import { + CONTEXT_DEV_BASE_URL, + CREDIT_OUTPUTS, + contextDevJsonHeaders, + extractCreditMetadata, + parseContextDevResponse, +} from '@/tools/context_dev/utils' +import type { ToolConfig } from '@/tools/types' + +export const contextDevSearchTool: ToolConfig = { + id: 'context_dev_search', + name: 'Context.dev Search', + description: 'Search the web with natural language and optionally scrape results to markdown.', + version: '1.0.0', + + params: { + query: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'The natural language search query (1-500 characters)', + }, + includeDomains: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'Only return results from these domains', + }, + excludeDomains: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'Exclude results from these domains', + }, + freshness: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Recency filter (last_24_hours, last_week, last_month, last_year)', + }, + queryFanout: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Expand the query into parallel variants for broader coverage', + }, + markdownEnabled: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Scrape each result page to markdown (default: false)', + }, + timeoutMS: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Request timeout in milliseconds (1000-300000)', + }, + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Context.dev API key', + }, + }, + + request: { + method: 'POST', + url: () => `${CONTEXT_DEV_BASE_URL}/web/search`, + headers: (params) => contextDevJsonHeaders(params.apiKey), + body: (params) => { + const body: Record = { query: params.query } + if (params.includeDomains?.length) body.includeDomains = params.includeDomains + if (params.excludeDomains?.length) body.excludeDomains = params.excludeDomains + if (params.freshness) body.freshness = params.freshness + if (params.queryFanout != null) body.queryFanout = params.queryFanout + if (params.markdownEnabled != null) { + body.markdownOptions = { enabled: params.markdownEnabled } + } + if (params.timeoutMS != null) body.timeoutMS = params.timeoutMS + return body + }, + }, + + transformResponse: async (response: Response) => { + const data = await parseContextDevResponse(response) + return { + success: true, + output: { + results: data.results ?? [], + query: data.query ?? '', + ...extractCreditMetadata(data.key_metadata), + }, + } + }, + + outputs: { + results: { + type: 'array', + description: 'Search results with url, title, description, relevance, and optional markdown', + items: { type: 'object', properties: SEARCH_RESULT_OUTPUT_PROPERTIES }, + }, + query: { type: 'string', description: 'The query that was searched' }, + ...CREDIT_OUTPUTS, + }, +} diff --git a/apps/sim/tools/context_dev/types.ts b/apps/sim/tools/context_dev/types.ts new file mode 100644 index 00000000000..63cde60c786 --- /dev/null +++ b/apps/sim/tools/context_dev/types.ts @@ -0,0 +1,464 @@ +import type { ToolFileData, ToolResponse } from '@/tools/types' + +/** Credit accounting fields surfaced on every Context.dev tool output. */ +interface CreditFields { + creditsConsumed: number | null + creditsRemaining: number | null +} + +export interface ContextDevScrapeMarkdownParams { + apiKey: string + url: string + useMainContentOnly?: boolean + includeLinks?: boolean + includeImages?: boolean + includeFrames?: boolean + maxAgeMs?: number + waitForMs?: number + timeoutMS?: number +} + +export interface ContextDevScrapeMarkdownResponse extends ToolResponse { + output: CreditFields & { + markdown: string + url: string + } +} + +export interface ContextDevScrapeHtmlParams { + apiKey: string + url: string + useMainContentOnly?: boolean + includeFrames?: boolean + maxAgeMs?: number + waitForMs?: number + timeoutMS?: number +} + +export interface ContextDevScrapeHtmlResponse extends ToolResponse { + output: CreditFields & { + html: string + url: string + type: string + } +} + +export interface ContextDevScreenshotParams { + apiKey: string + url: string + fullScreenshot?: boolean + handleCookiePopup?: boolean + viewportWidth?: number + viewportHeight?: number + maxAgeMs?: number + waitForMs?: number + timeoutMS?: number +} + +export interface ContextDevScreenshotResponse extends ToolResponse { + output: CreditFields & { + file?: ToolFileData + screenshotUrl: string + screenshotType: string | null + domain: string | null + width: number | null + height: number | null + } +} + +export interface ContextDevScrapeImagesParams { + apiKey: string + url: string + maxAgeMs?: number + waitForMs?: number + timeoutMS?: number + enrichResolution?: boolean + enrichHostedUrl?: boolean + enrichClassification?: boolean +} + +export interface ContextDevScrapeImagesResponse extends ToolResponse { + output: CreditFields & { + success: boolean + images: Array> + url: string + } +} + +export interface ContextDevCrawlParams { + apiKey: string + url: string + maxPages?: number + maxDepth?: number + urlRegex?: string + includeLinks?: boolean + includeImages?: boolean + useMainContentOnly?: boolean + followSubdomains?: boolean + maxAgeMs?: number + waitForMs?: number + stopAfterMs?: number + timeoutMS?: number +} + +export interface ContextDevCrawlResponse extends ToolResponse { + output: CreditFields & { + results: Array<{ + markdown: string + metadata: Record + }> + metadata: Record + } +} + +export interface ContextDevMapParams { + apiKey: string + domain: string + maxLinks?: number + urlRegex?: string + timeoutMS?: number +} + +export interface ContextDevMapResponse extends ToolResponse { + output: CreditFields & { + domain: string + urls: string[] + meta: Record + } +} + +export interface ContextDevSearchParams { + apiKey: string + query: string + includeDomains?: string[] + excludeDomains?: string[] + freshness?: string + queryFanout?: boolean + markdownEnabled?: boolean + timeoutMS?: number +} + +export interface ContextDevSearchResponse extends ToolResponse { + output: CreditFields & { + results: Array> + query: string + } +} + +export interface ContextDevExtractParams { + apiKey: string + url: string + schema: Record + instructions?: string + factCheck?: boolean + followSubdomains?: boolean + maxPages?: number + maxDepth?: number + maxAgeMs?: number + stopAfterMs?: number + timeoutMS?: number +} + +export interface ContextDevExtractResponse extends ToolResponse { + output: CreditFields & { + status: string + url: string + urlsAnalyzed: string[] + data: Record + metadata: Record + } +} + +export interface ContextDevExtractProductParams { + apiKey: string + url: string + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevExtractProductResponse extends ToolResponse { + output: CreditFields & { + isProductPage: boolean + platform: string | null + product: Record | null + } +} + +export interface ContextDevExtractProductsParams { + apiKey: string + domain: string + maxProducts?: number + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevExtractProductsResponse extends ToolResponse { + output: CreditFields & { + products: Array> + } +} + +export interface ContextDevScrapeFontsParams { + apiKey: string + domain: string + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevScrapeFontsResponse extends ToolResponse { + output: CreditFields & { + status: string + domain: string + fonts: Array> + fontLinks: Record + } +} + +export interface ContextDevScrapeStyleguideParams { + apiKey: string + domain: string + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevScrapeStyleguideResponse extends ToolResponse { + output: CreditFields & { + status: string + domain: string + styleguide: Record | null + } +} + +export interface ContextDevClassifyNaicsParams { + apiKey: string + input: string + minResults?: number + maxResults?: number + timeoutMS?: number +} + +export interface ContextDevClassifyNaicsResponse extends ToolResponse { + output: CreditFields & { + status: string + domain: string | null + type: string | null + codes: Array> + } +} + +export interface ContextDevClassifySicParams { + apiKey: string + input: string + type?: string + minResults?: number + maxResults?: number + timeoutMS?: number +} + +export interface ContextDevClassifySicResponse extends ToolResponse { + output: CreditFields & { + status: string + domain: string | null + type: string | null + classification: string | null + codes: Array> + } +} + +/** Shared response shape for every brand-returning endpoint (full brand object). */ +export interface ContextDevBrandResponse extends ToolResponse { + output: CreditFields & { + status: string + brand: Record | null + } +} + +export interface ContextDevGetBrandParams { + apiKey: string + domain: string + forceLanguage?: string + maxSpeed?: boolean + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevGetBrandByNameParams { + apiKey: string + name: string + countryGl?: string + forceLanguage?: string + maxSpeed?: boolean + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevGetBrandByEmailParams { + apiKey: string + email: string + forceLanguage?: string + maxSpeed?: boolean + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevGetBrandByTickerParams { + apiKey: string + ticker: string + tickerExchange?: string + forceLanguage?: string + maxSpeed?: boolean + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevIdentifyTransactionParams { + apiKey: string + transactionInfo: string + countryGl?: string + city?: string + mcc?: string + phone?: number + highConfidenceOnly?: boolean + forceLanguage?: string + maxSpeed?: boolean + timeoutMS?: number +} + +export interface ContextDevGetBrandSimplifiedParams { + apiKey: string + domain: string + maxAgeMs?: number + timeoutMS?: number +} + +export interface ContextDevGetBrandSimplifiedResponse extends ToolResponse { + output: CreditFields & { + status: string + brand: Record | null + } +} + +export interface ContextDevPrefetchByEmailParams { + apiKey: string + email: string + timeoutMS?: number +} + +export interface ContextDevPrefetchDomainParams { + apiKey: string + domain: string + timeoutMS?: number +} + +/** Shared response shape for the prefetch utility endpoints. */ +export interface ContextDevPrefetchResponse extends ToolResponse { + output: CreditFields & { + status: string + message: string + domain: string + } +} + +/** Output schema for a single web search result. */ +export const SEARCH_RESULT_OUTPUT_PROPERTIES = { + url: { type: 'string', description: 'Result page URL' }, + title: { type: 'string', description: 'Result page title' }, + description: { type: 'string', description: 'Result snippet/description' }, + relevance: { type: 'string', description: 'Relevance rating (high, medium, low)' }, + markdown: { + type: 'json', + description: 'Scraped markdown for the result (when markdown scraping is enabled)', + }, +} as const + +/** Output schema for a single crawled page. */ +export const CRAWL_RESULT_OUTPUT_PROPERTIES = { + markdown: { type: 'string', description: 'Page content as markdown' }, + metadata: { type: 'json', description: 'Page metadata (url, title, crawlDepth, statusCode)' }, +} as const + +/** Output schema for a single industry classification code. */ +export const CLASSIFICATION_CODE_OUTPUT_PROPERTIES = { + code: { type: 'string', description: 'Industry code' }, + name: { type: 'string', description: 'Industry name' }, + confidence: { type: 'string', description: 'Match confidence (high, medium, low)' }, +} as const + +/** Output schema for the full brand object returned by brand-intelligence endpoints. */ +export const BRAND_OUTPUT_PROPERTIES = { + domain: { type: 'string', description: 'Brand domain' }, + title: { type: 'string', description: 'Brand title' }, + description: { type: 'string', description: 'Brand description' }, + slogan: { type: 'string', description: 'Brand slogan' }, + colors: { type: 'json', description: 'Brand colors (hex and name)' }, + logos: { type: 'json', description: 'Brand logos with mode, colors, resolution, and type' }, + backdrops: { type: 'json', description: 'Brand backdrop images' }, + socials: { type: 'json', description: 'Social media profiles (type and url)' }, + address: { type: 'json', description: 'Brand address' }, + stock: { type: 'json', description: 'Stock info (ticker and exchange)' }, + is_nsfw: { type: 'boolean', description: 'Whether the brand contains adult content' }, + email: { type: 'string', description: 'Brand contact email' }, + phone: { type: 'string', description: 'Brand contact phone' }, + industries: { type: 'json', description: 'Industry taxonomy (eic industry/subindustry pairs)' }, + links: { type: 'json', description: 'Key brand links (careers, privacy, terms, blog, pricing)' }, + primary_language: { type: 'string', description: 'Primary language of the brand site' }, +} as const + +/** Output schema for the reduced brand object returned by the simplified endpoint. */ +export const SIMPLIFIED_BRAND_OUTPUT_PROPERTIES = { + domain: { type: 'string', description: 'Brand domain' }, + title: { type: 'string', description: 'Brand title' }, + colors: { type: 'json', description: 'Brand colors (hex and name)' }, + logos: { type: 'json', description: 'Brand logos with mode, colors, resolution, and type' }, + backdrops: { type: 'json', description: 'Brand backdrop images' }, +} as const + +/** Output schema for a single extracted product. */ +export const PRODUCT_OUTPUT_PROPERTIES = { + name: { type: 'string', description: 'Product name' }, + description: { type: 'string', description: 'Product description' }, + price: { type: 'number', description: 'Product price' }, + currency: { type: 'string', description: 'Price currency' }, + billing_frequency: { + type: 'string', + description: 'Billing frequency (monthly, yearly, one_time, usage_based)', + }, + pricing_model: { + type: 'string', + description: 'Pricing model (per_seat, flat, tiered, freemium, custom)', + }, + url: { type: 'string', description: 'Product URL' }, + category: { type: 'string', description: 'Product category' }, + features: { type: 'json', description: 'Product features' }, + target_audience: { type: 'json', description: 'Target audience' }, + tags: { type: 'json', description: 'Product tags' }, + image_url: { type: 'string', description: 'Primary product image URL' }, + images: { type: 'json', description: 'Product image URLs' }, + sku: { type: 'string', description: 'Product SKU' }, +} as const + +/** Output schema for a single font usage entry. */ +export const FONT_OUTPUT_PROPERTIES = { + font: { type: 'string', description: 'Font family name' }, + uses: { type: 'json', description: 'Where the font is used' }, + fallbacks: { type: 'json', description: 'Fallback font families' }, + num_elements: { type: 'number', description: 'Number of elements using the font' }, + num_words: { type: 'number', description: 'Number of words rendered in the font' }, + percent_words: { type: 'number', description: 'Percent of words using the font' }, + percent_elements: { type: 'number', description: 'Percent of elements using the font' }, +} as const + +/** Output schema for a single scraped image. */ +export const IMAGE_OUTPUT_PROPERTIES = { + src: { type: 'string', description: 'Image source URL or data' }, + element: { + type: 'string', + description: 'Source element (img, svg, link, source, video, css, object, meta, background)', + }, + type: { type: 'string', description: 'Image representation (url, html, base64)' }, + alt: { type: 'string', description: 'Alt text', optional: true }, + enrichment: { + type: 'json', + description: 'Optional enrichment (width, height, mimetype, url, type) when requested', + }, +} as const diff --git a/apps/sim/tools/context_dev/utils.ts b/apps/sim/tools/context_dev/utils.ts new file mode 100644 index 00000000000..b46a28d626a --- /dev/null +++ b/apps/sim/tools/context_dev/utils.ts @@ -0,0 +1,97 @@ +/** Base URL for all Context.dev API endpoints. */ +export const CONTEXT_DEV_BASE_URL = 'https://api.context.dev/v1' + +/** + * Builds the standard Context.dev request headers with Bearer authentication. + */ +export function contextDevHeaders(apiKey: string): Record { + return { + Authorization: `Bearer ${apiKey}`, + Accept: 'application/json', + } +} + +/** + * Builds JSON request headers with Bearer authentication for POST endpoints. + */ +export function contextDevJsonHeaders(apiKey: string): Record { + return { + ...contextDevHeaders(apiKey), + 'Content-Type': 'application/json', + } +} + +/** + * Throws a descriptive error when a Context.dev response is not successful. + * Returns the parsed JSON body on success. + */ +export async function parseContextDevResponse(response: Response): Promise { + if (!response.ok) { + const errorText = await response.text() + throw new Error(`Context.dev API error (${response.status}): ${errorText}`) + } + return response.json() +} + +/** Shape of the credit accounting object present on every Context.dev response. */ +interface ContextDevKeyMetadata { + credits_consumed?: number + credits_remaining?: number +} + +/** + * Extracts the credit accounting fields shared by every Context.dev response. + */ +export function extractCreditMetadata(keyMetadata: ContextDevKeyMetadata | undefined): { + creditsConsumed: number | null + creditsRemaining: number | null +} { + return { + creditsConsumed: keyMetadata?.credits_consumed ?? null, + creditsRemaining: keyMetadata?.credits_remaining ?? null, + } +} + +/** + * Normalizes a brand-returning Context.dev response into the shared tool output shape. + * Used by every endpoint that returns a `brand` object. + */ +export function transformBrandResponse(data: any): { + status: string + brand: Record | null + creditsConsumed: number | null + creditsRemaining: number | null +} { + return { + status: data.status ?? '', + brand: data.brand ?? null, + ...extractCreditMetadata(data.key_metadata), + } +} + +/** + * Appends a parameter to a URLSearchParams instance only when it is defined and non-empty. + * Booleans are serialized as the literal strings 'true' / 'false'. + */ +export function appendParam( + search: URLSearchParams, + key: string, + value: string | number | boolean | undefined | null +): void { + if (value === undefined || value === null || value === '') return + search.append(key, String(value)) +} + +/** Output definitions for the credit accounting fields, reused across every tool. */ +export const CREDIT_OUTPUTS = { + creditsConsumed: { + type: 'number', + description: 'Credits consumed by this request', + optional: true, + }, + creditsRemaining: { + type: 'number', + description: 'Credits remaining on the API key', + optional: true, + }, +} as const diff --git a/apps/sim/tools/emailbison/utils.ts b/apps/sim/tools/emailbison/utils.ts index 40f1a4ee4f8..07e8c3b2d71 100644 --- a/apps/sim/tools/emailbison/utils.ts +++ b/apps/sim/tools/emailbison/utils.ts @@ -1,4 +1,4 @@ -import { filterUndefined } from '@sim/utils/object' +import { filterUndefined, isRecordLike } from '@sim/utils/object' import type { EmailBisonBaseParams, EmailBisonCampaign, @@ -100,7 +100,7 @@ export async function emailBisonArrayData(response: Response, label: string): Pr export async function emailBisonRecordData(response: Response, label: string): Promise { const data = await emailBisonData(response) - if (!isRecord(data)) { + if (!isRecordLike(data)) { throw new Error(`Email Bison response did not include a valid ${label} object`) } return data @@ -441,12 +441,8 @@ function mapReplyAttachment(value: unknown): EmailBisonReplyAttachment { } } -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} - function toRecord(value: unknown): Record { - return isRecord(value) ? value : {} + return isRecordLike(value) ? value : {} } function toArray(value: unknown): unknown[] { diff --git a/apps/sim/tools/error-extractors.ts b/apps/sim/tools/error-extractors.ts index ff4c442e64b..0bfc70c7c57 100644 --- a/apps/sim/tools/error-extractors.ts +++ b/apps/sim/tools/error-extractors.ts @@ -176,6 +176,17 @@ const ERROR_EXTRACTORS: ErrorExtractorConfig[] = [ examples: ['Hunter.io API'], extract: (errorInfo) => errorInfo?.data?.errors?.[0]?.details, }, + { + id: 'square-errors', + description: 'Square API error format with errors[].detail and errors[].code', + examples: ['Square API'], + extract: (errorInfo) => { + const err = errorInfo?.data?.errors?.[0] + if (!err) return undefined + if (err.detail) return err.code ? `${err.detail} (${err.code})` : err.detail + return err.code + }, + }, { id: 'errors-array-string', description: 'Errors array containing strings or objects with messages', @@ -302,6 +313,7 @@ export const ErrorExtractorId = { BATCH_VALIDATION_ERRORS: 'batch-validation-errors', NESTJS_VALIDATION_ERRORS: 'nestjs-validation-errors', HUNTER_ERRORS: 'hunter-errors', + SQUARE_ERRORS: 'square-errors', ERRORS_ARRAY_STRING: 'errors-array-string', TELEGRAM_DESCRIPTION: 'telegram-description', STANDARD_MESSAGE: 'standard-message', diff --git a/apps/sim/tools/instantly/utils.ts b/apps/sim/tools/instantly/utils.ts index 885eab479a9..a7d3b62ce99 100644 --- a/apps/sim/tools/instantly/utils.ts +++ b/apps/sim/tools/instantly/utils.ts @@ -1,4 +1,4 @@ -import { filterUndefined } from '@sim/utils/object' +import { filterUndefined, isRecordLike } from '@sim/utils/object' import type { InstantlyCampaign, InstantlyEmail, @@ -56,7 +56,7 @@ export async function parseInstantlyResponse(response: Response): Promise { try { return await response.json() diff --git a/apps/sim/tools/mem0/get_memories.ts b/apps/sim/tools/mem0/get_memories.ts index 74d2addcc37..acaf7eacf81 100644 --- a/apps/sim/tools/mem0/get_memories.ts +++ b/apps/sim/tools/mem0/get_memories.ts @@ -1,18 +1,18 @@ +import { isRecordLike } from '@sim/utils/object' import { MEMORY_OUTPUT_PROPERTIES, type Mem0GetMemoriesParams } from '@/tools/mem0/types' -import { isRecord } from '@/tools/mem0/utils' import type { ToolConfig } from '@/tools/types' const getMemoriesFromResponse = (data: unknown): unknown[] => { if (Array.isArray(data)) return data - if (!isRecord(data)) return [] + if (!isRecordLike(data)) return [] if (Array.isArray(data.results)) return data.results - if (isRecord(data.memory)) return [data.memory] + if (isRecordLike(data.memory)) return [data.memory] if (data.id) return [data] return [] } const getMemoryId = (memory: unknown): string | undefined => - isRecord(memory) && typeof memory.id === 'string' ? memory.id : undefined + isRecordLike(memory) && typeof memory.id === 'string' ? memory.id : undefined /** * Get Memories Tool @@ -122,11 +122,11 @@ export const mem0GetMemoriesTool: ToolConfig = { output: { memories, ids, - ...(isRecord(data) && typeof data.count === 'number' ? { count: data.count } : {}), - ...(isRecord(data) && (typeof data.next === 'string' || data.next === null) + ...(isRecordLike(data) && typeof data.count === 'number' ? { count: data.count } : {}), + ...(isRecordLike(data) && (typeof data.next === 'string' || data.next === null) ? { next: data.next } : {}), - ...(isRecord(data) && (typeof data.previous === 'string' || data.previous === null) + ...(isRecordLike(data) && (typeof data.previous === 'string' || data.previous === null) ? { previous: data.previous } : {}), }, diff --git a/apps/sim/tools/mem0/search_memories.ts b/apps/sim/tools/mem0/search_memories.ts index 5f8dde791f4..2343accbf49 100644 --- a/apps/sim/tools/mem0/search_memories.ts +++ b/apps/sim/tools/mem0/search_memories.ts @@ -1,11 +1,12 @@ +import { isRecordLike } from '@sim/utils/object' import type { Mem0Response, Mem0SearchMemoriesParams } from '@/tools/mem0/types' import { SEARCH_RESULT_OUTPUT_PROPERTIES } from '@/tools/mem0/types' -import { isRecord, type JsonRecord } from '@/tools/mem0/utils' +import type { JsonRecord } from '@/tools/mem0/utils' import type { ToolConfig } from '@/tools/types' const getSearchResults = (data: unknown): JsonRecord[] => { - if (!isRecord(data) || !Array.isArray(data.results)) return [] - return data.results.filter(isRecord) + if (!isRecordLike(data) || !Array.isArray(data.results)) return [] + return data.results.filter(isRecordLike) } const getString = (value: unknown): string | undefined => @@ -85,7 +86,7 @@ export const mem0SearchMemoriesTool: ToolConfig -export const isRecord = (value: unknown): value is JsonRecord => - value !== null && typeof value === 'object' && !Array.isArray(value) - function isMem0Message(value: unknown): value is Mem0Message { return ( value !== null && diff --git a/apps/sim/tools/params.ts b/apps/sim/tools/params.ts index fc82a149f73..a506eb0bc7e 100644 --- a/apps/sim/tools/params.ts +++ b/apps/sim/tools/params.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import { isRecordLike } from '@sim/utils/object' import { extractInputFieldsFromBlocks } from '@/lib/workflows/input-format' import { buildCanonicalIndex, @@ -733,7 +734,7 @@ export function deepMergeInputMapping( if (typeof userInputMapping === 'string') { try { const parsed = JSON.parse(userInputMapping) - if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + if (isRecordLike(parsed)) { parsedUserMapping = parsed } } catch { diff --git a/apps/sim/tools/registry.ts b/apps/sim/tools/registry.ts index c8f7422f592..45fef1980aa 100644 --- a/apps/sim/tools/registry.ts +++ b/apps/sim/tools/registry.ts @@ -522,6 +522,30 @@ import { confluenceUpdateTool, confluenceUploadAttachmentTool, } from '@/tools/confluence' +import { + contextDevClassifyNaicsTool, + contextDevClassifySicTool, + contextDevCrawlTool, + contextDevExtractProductsTool, + contextDevExtractProductTool, + contextDevExtractTool, + contextDevGetBrandByEmailTool, + contextDevGetBrandByNameTool, + contextDevGetBrandByTickerTool, + contextDevGetBrandSimplifiedTool, + contextDevGetBrandTool, + contextDevIdentifyTransactionTool, + contextDevMapTool, + contextDevPrefetchByEmailTool, + contextDevPrefetchDomainTool, + contextDevScrapeFontsTool, + contextDevScrapeHtmlTool, + contextDevScrapeImagesTool, + contextDevScrapeMarkdownTool, + contextDevScrapeStyleguideTool, + contextDevScreenshotTool, + contextDevSearchTool, +} from '@/tools/context_dev' import { convexActionTool, convexDocumentDeltasTool, @@ -3111,6 +3135,42 @@ import { spotifyUpdatePlaylistTool, } from '@/tools/spotify' import { sqsSendTool } from '@/tools/sqs' +import { + squareBatchRetrieveInventoryCountsTool, + squareCancelInvoiceTool, + squareCancelPaymentTool, + squareCompletePaymentTool, + squareCreateCatalogImageTool, + squareCreateCustomerTool, + squareCreateInvoiceTool, + squareCreateOrderTool, + squareCreatePaymentTool, + squareDeleteCatalogObjectTool, + squareDeleteCustomerTool, + squareDeleteInvoiceTool, + squareGetCatalogObjectTool, + squareGetCustomerTool, + squareGetInvoiceTool, + squareGetLocationTool, + squareGetOrderTool, + squareGetPaymentTool, + squareGetRefundTool, + squareListCatalogTool, + squareListCustomersTool, + squareListInvoicesTool, + squareListLocationsTool, + squareListPaymentsTool, + squareListRefundsTool, + squarePayOrderTool, + squarePublishInvoiceTool, + squareRefundPaymentTool, + squareSearchCatalogObjectsTool, + squareSearchCustomersTool, + squareSearchInvoicesTool, + squareSearchOrdersTool, + squareUpdateCustomerTool, + squareUpsertCatalogObjectTool, +} from '@/tools/square' import { sshCheckCommandExistsTool, sshCheckFileExistsTool, @@ -5491,6 +5551,28 @@ export const tools: Record = { confluence_list_space_properties: confluenceListSpacePropertiesTool, confluence_create_space_property: confluenceCreateSpacePropertyTool, confluence_delete_space_property: confluenceDeleteSpacePropertyTool, + context_dev_scrape_markdown: contextDevScrapeMarkdownTool, + context_dev_scrape_html: contextDevScrapeHtmlTool, + context_dev_scrape_images: contextDevScrapeImagesTool, + context_dev_screenshot: contextDevScreenshotTool, + context_dev_crawl: contextDevCrawlTool, + context_dev_map: contextDevMapTool, + context_dev_search: contextDevSearchTool, + context_dev_extract: contextDevExtractTool, + context_dev_extract_product: contextDevExtractProductTool, + context_dev_extract_products: contextDevExtractProductsTool, + context_dev_scrape_fonts: contextDevScrapeFontsTool, + context_dev_scrape_styleguide: contextDevScrapeStyleguideTool, + context_dev_classify_naics: contextDevClassifyNaicsTool, + context_dev_classify_sic: contextDevClassifySicTool, + context_dev_get_brand: contextDevGetBrandTool, + context_dev_get_brand_by_name: contextDevGetBrandByNameTool, + context_dev_get_brand_by_email: contextDevGetBrandByEmailTool, + context_dev_get_brand_by_ticker: contextDevGetBrandByTickerTool, + context_dev_get_brand_simplified: contextDevGetBrandSimplifiedTool, + context_dev_identify_transaction: contextDevIdentifyTransactionTool, + context_dev_prefetch_domain: contextDevPrefetchDomainTool, + context_dev_prefetch_by_email: contextDevPrefetchByEmailTool, cursor_list_agents: cursorListAgentsTool, cursor_list_agents_v2: cursorListAgentsV2Tool, cursor_get_agent: cursorGetAgentTool, @@ -6999,6 +7081,40 @@ export const tools: Record = { spotify_set_repeat: spotifySetRepeatTool, spotify_set_shuffle: spotifySetShuffleTool, spotify_transfer_playback: spotifyTransferPlaybackTool, + square_create_payment: squareCreatePaymentTool, + square_get_payment: squareGetPaymentTool, + square_list_payments: squareListPaymentsTool, + square_cancel_payment: squareCancelPaymentTool, + square_complete_payment: squareCompletePaymentTool, + square_refund_payment: squareRefundPaymentTool, + square_get_refund: squareGetRefundTool, + square_list_refunds: squareListRefundsTool, + square_create_customer: squareCreateCustomerTool, + square_get_customer: squareGetCustomerTool, + square_list_customers: squareListCustomersTool, + square_search_customers: squareSearchCustomersTool, + square_update_customer: squareUpdateCustomerTool, + square_delete_customer: squareDeleteCustomerTool, + square_list_locations: squareListLocationsTool, + square_get_location: squareGetLocationTool, + square_create_order: squareCreateOrderTool, + square_get_order: squareGetOrderTool, + square_search_orders: squareSearchOrdersTool, + square_pay_order: squarePayOrderTool, + square_create_invoice: squareCreateInvoiceTool, + square_get_invoice: squareGetInvoiceTool, + square_list_invoices: squareListInvoicesTool, + square_search_invoices: squareSearchInvoicesTool, + square_publish_invoice: squarePublishInvoiceTool, + square_cancel_invoice: squareCancelInvoiceTool, + square_delete_invoice: squareDeleteInvoiceTool, + square_upsert_catalog_object: squareUpsertCatalogObjectTool, + square_get_catalog_object: squareGetCatalogObjectTool, + square_list_catalog: squareListCatalogTool, + square_search_catalog_objects: squareSearchCatalogObjectsTool, + square_create_catalog_image: squareCreateCatalogImageTool, + square_delete_catalog_object: squareDeleteCatalogObjectTool, + square_batch_retrieve_inventory_counts: squareBatchRetrieveInventoryCountsTool, upstash_redis_get: upstashRedisGetTool, upstash_redis_set: upstashRedisSetTool, upstash_redis_delete: upstashRedisDeleteTool, diff --git a/apps/sim/tools/square/batch_retrieve_inventory_counts.ts b/apps/sim/tools/square/batch_retrieve_inventory_counts.ts new file mode 100644 index 00000000000..686db627463 --- /dev/null +++ b/apps/sim/tools/square/batch_retrieve_inventory_counts.ts @@ -0,0 +1,112 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { + BatchRetrieveInventoryCountsParams, + InventoryCountListResponse, +} from '@/tools/square/types' +import { + INVENTORY_COUNT_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareBatchRetrieveInventoryCountsTool: ToolConfig< + BatchRetrieveInventoryCountsParams, + InventoryCountListResponse +> = { + id: 'square_batch_retrieve_inventory_counts', + name: 'Square Batch Retrieve Inventory Counts', + description: 'Retrieve current inventory counts for catalog items across locations', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + catalogObjectIds: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'IDs of the catalog item variations to retrieve counts for', + }, + locationIds: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'IDs of the locations to retrieve counts for (defaults to all locations)', + }, + states: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'Inventory states to filter by (e.g. IN_STOCK, SOLD, IN_TRANSIT)', + }, + updatedAfter: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Only return counts updated after this RFC 3339 timestamp', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page (1-1000)', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/inventory/counts/batch-retrieve`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = {} + if (params.catalogObjectIds) body.catalog_object_ids = params.catalogObjectIds + if (params.locationIds) body.location_ids = params.locationIds + if (params.states) body.states = params.states + if (params.updatedAfter) body.updated_after = params.updatedAfter + if (params.limit !== undefined) body.limit = params.limit + if (params.cursor) body.cursor = params.cursor + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const counts = data.counts ?? [] + return { + success: true, + output: { + counts, + metadata: { + count: counts.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + counts: { + type: 'array', + description: 'Array of inventory count objects', + items: INVENTORY_COUNT_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/cancel_invoice.ts b/apps/sim/tools/square/cancel_invoice.ts new file mode 100644 index 00000000000..8e864146db4 --- /dev/null +++ b/apps/sim/tools/square/cancel_invoice.ts @@ -0,0 +1,71 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CancelInvoiceParams, InvoiceResponse } from '@/tools/square/types' +import { + INVOICE_METADATA_OUTPUT_PROPERTIES, + INVOICE_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCancelInvoiceTool: ToolConfig = { + id: 'square_cancel_invoice', + name: 'Square Cancel Invoice', + description: 'Cancel a published invoice that is unpaid or partially paid', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + invoiceId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the invoice to cancel', + }, + version: { + type: 'number', + required: true, + visibility: 'user-or-llm', + description: 'Current version of the invoice', + }, + }, + + request: { + url: (params) => + `${SQUARE_BASE_URL}/v2/invoices/${encodeURIComponent(params.invoiceId)}/cancel`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => ({ version: params.version }), + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoice = data.invoice ?? {} + return { + success: true, + output: { + invoice, + metadata: { + id: invoice.id, + status: invoice.status ?? null, + version: invoice.version ?? null, + }, + }, + } + }, + + outputs: { + invoice: { ...INVOICE_OUTPUT, description: 'The canceled invoice object' }, + metadata: { + type: 'json', + description: 'Invoice summary metadata', + properties: INVOICE_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/cancel_payment.ts b/apps/sim/tools/square/cancel_payment.ts new file mode 100644 index 00000000000..8e4b4a7b81f --- /dev/null +++ b/apps/sim/tools/square/cancel_payment.ts @@ -0,0 +1,65 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CancelPaymentParams, PaymentResponse } from '@/tools/square/types' +import { + PAYMENT_METADATA_OUTPUT_PROPERTIES, + PAYMENT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCancelPaymentTool: ToolConfig = { + id: 'square_cancel_payment', + name: 'Square Cancel Payment', + description: 'Cancel (void) an authorized payment that has not been captured', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + paymentId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the payment to cancel', + }, + }, + + request: { + url: (params) => + `${SQUARE_BASE_URL}/v2/payments/${encodeURIComponent(params.paymentId)}/cancel`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: () => ({}), + }, + + transformResponse: async (response) => { + const data = await response.json() + const payment = data.payment ?? {} + return { + success: true, + output: { + payment, + metadata: { + id: payment.id, + status: payment.status ?? null, + order_id: payment.order_id ?? null, + }, + }, + } + }, + + outputs: { + payment: { ...PAYMENT_OUTPUT, description: 'The canceled payment object' }, + metadata: { + type: 'json', + description: 'Payment summary metadata', + properties: PAYMENT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/complete_payment.ts b/apps/sim/tools/square/complete_payment.ts new file mode 100644 index 00000000000..6d70634ba4c --- /dev/null +++ b/apps/sim/tools/square/complete_payment.ts @@ -0,0 +1,71 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CompletePaymentParams, PaymentResponse } from '@/tools/square/types' +import { + PAYMENT_METADATA_OUTPUT_PROPERTIES, + PAYMENT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCompletePaymentTool: ToolConfig = { + id: 'square_complete_payment', + name: 'Square Complete Payment', + description: 'Capture (complete) a payment that was authorized with delayed capture', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + paymentId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the payment to complete', + }, + versionToken: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional version token for optimistic concurrency control', + }, + }, + + request: { + url: (params) => + `${SQUARE_BASE_URL}/v2/payments/${encodeURIComponent(params.paymentId)}/complete`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => (params.versionToken ? { version_token: params.versionToken } : {}), + }, + + transformResponse: async (response) => { + const data = await response.json() + const payment = data.payment ?? {} + return { + success: true, + output: { + payment, + metadata: { + id: payment.id, + status: payment.status ?? null, + order_id: payment.order_id ?? null, + }, + }, + } + }, + + outputs: { + payment: { ...PAYMENT_OUTPUT, description: 'The completed payment object' }, + metadata: { + type: 'json', + description: 'Payment summary metadata', + properties: PAYMENT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/create_catalog_image.ts b/apps/sim/tools/square/create_catalog_image.ts new file mode 100644 index 00000000000..10be9b47fdc --- /dev/null +++ b/apps/sim/tools/square/create_catalog_image.ts @@ -0,0 +1,91 @@ +import type { CatalogObjectResponse, CreateCatalogImageParams } from '@/tools/square/types' +import { + CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + CATALOG_OBJECT_OUTPUT, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCreateCatalogImageTool: ToolConfig< + CreateCatalogImageParams, + CatalogObjectResponse +> = { + id: 'square_create_catalog_image', + name: 'Square Create Catalog Image', + description: 'Upload an image and attach it to the catalog, optionally to a specific item', + version: '1.0.0', + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + file: { + type: 'file', + required: true, + visibility: 'user-or-llm', + description: 'The image file to upload (UserFile object)', + }, + fileName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional filename override for the image', + }, + objectId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ID of the catalog object (e.g. an item) to attach the image to', + }, + caption: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Caption (alt text) for the image', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: '/api/tools/square/catalog-image', + method: 'POST', + headers: () => ({ + 'Content-Type': 'application/json', + }), + body: (params) => ({ + accessToken: params.apiKey, + file: params.file, + fileName: params.fileName, + objectId: params.objectId, + caption: params.caption, + idempotencyKey: params.idempotencyKey, + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + if (!data.success) { + throw new Error(data.error || 'Failed to upload catalog image') + } + return { + success: true, + output: data.output, + } + }, + + outputs: { + object: { ...CATALOG_OBJECT_OUTPUT, description: 'The created catalog image object' }, + metadata: { + type: 'json', + description: 'Catalog object summary metadata', + properties: CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/create_customer.ts b/apps/sim/tools/square/create_customer.ts new file mode 100644 index 00000000000..787ab46ddbf --- /dev/null +++ b/apps/sim/tools/square/create_customer.ts @@ -0,0 +1,141 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CreateCustomerParams, CustomerResponse } from '@/tools/square/types' +import { + CUSTOMER_METADATA_OUTPUT_PROPERTIES, + CUSTOMER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCreateCustomerTool: ToolConfig = { + id: 'square_create_customer', + name: 'Square Create Customer', + description: 'Create a new customer profile in the Square customer directory', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + givenName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'First name of the customer', + }, + familyName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Last name of the customer', + }, + companyName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Business name of the customer', + }, + nickname: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Nickname of the customer', + }, + emailAddress: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Email address of the customer', + }, + phoneNumber: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Phone number of the customer', + }, + birthday: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Birthday in YYYY-MM-DD or MM-DD format', + }, + note: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Note about the customer', + }, + referenceId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional external reference for the customer', + }, + address: { + type: 'json', + required: false, + visibility: 'user-or-llm', + description: 'Square address object for the customer', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/customers`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + idempotency_key: params.idempotencyKey || generateId(), + } + if (params.givenName) body.given_name = params.givenName + if (params.familyName) body.family_name = params.familyName + if (params.companyName) body.company_name = params.companyName + if (params.nickname) body.nickname = params.nickname + if (params.emailAddress) body.email_address = params.emailAddress + if (params.phoneNumber) body.phone_number = params.phoneNumber + if (params.birthday) body.birthday = params.birthday + if (params.note) body.note = params.note + if (params.referenceId) body.reference_id = params.referenceId + if (params.address) body.address = params.address + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const customer = data.customer ?? {} + return { + success: true, + output: { + customer, + metadata: { + id: customer.id, + email_address: customer.email_address ?? null, + given_name: customer.given_name ?? null, + family_name: customer.family_name ?? null, + }, + }, + } + }, + + outputs: { + customer: { ...CUSTOMER_OUTPUT, description: 'The created customer object' }, + metadata: { + type: 'json', + description: 'Customer summary metadata', + properties: CUSTOMER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/create_invoice.ts b/apps/sim/tools/square/create_invoice.ts new file mode 100644 index 00000000000..bd5e82a8dd8 --- /dev/null +++ b/apps/sim/tools/square/create_invoice.ts @@ -0,0 +1,75 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CreateInvoiceParams, InvoiceResponse } from '@/tools/square/types' +import { + INVOICE_METADATA_OUTPUT_PROPERTIES, + INVOICE_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCreateInvoiceTool: ToolConfig = { + id: 'square_create_invoice', + name: 'Square Create Invoice', + description: 'Create a draft invoice for an existing order and customer', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + invoice: { + type: 'json', + required: true, + visibility: 'user-or-llm', + description: + 'Square invoice object including location_id, order_id, primary_recipient, and payment_requests (e.g. {"location_id":"L1","order_id":"O1","primary_recipient":{"customer_id":"C1"},"payment_requests":[{"request_type":"BALANCE","due_date":"2026-07-01"}]})', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/invoices`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => ({ + idempotency_key: params.idempotencyKey || generateId(), + invoice: params.invoice, + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoice = data.invoice ?? {} + return { + success: true, + output: { + invoice, + metadata: { + id: invoice.id, + status: invoice.status ?? null, + version: invoice.version ?? null, + }, + }, + } + }, + + outputs: { + invoice: { ...INVOICE_OUTPUT, description: 'The created invoice object' }, + metadata: { + type: 'json', + description: 'Invoice summary metadata', + properties: INVOICE_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/create_order.ts b/apps/sim/tools/square/create_order.ts new file mode 100644 index 00000000000..5cd023b3ab9 --- /dev/null +++ b/apps/sim/tools/square/create_order.ts @@ -0,0 +1,75 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CreateOrderParams, OrderResponse } from '@/tools/square/types' +import { + ORDER_METADATA_OUTPUT_PROPERTIES, + ORDER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCreateOrderTool: ToolConfig = { + id: 'square_create_order', + name: 'Square Create Order', + description: 'Create an order with line items, taxes, discounts, and fulfillments', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + order: { + type: 'json', + required: true, + visibility: 'user-or-llm', + description: + 'Square order object including location_id and line_items (e.g. {"location_id":"L1","line_items":[{"name":"Coffee","quantity":"1","base_price_money":{"amount":250,"currency":"USD"}}]})', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/orders`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => ({ + idempotency_key: params.idempotencyKey || generateId(), + order: params.order, + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + const order = data.order ?? {} + return { + success: true, + output: { + order, + metadata: { + id: order.id, + state: order.state ?? null, + location_id: order.location_id ?? null, + }, + }, + } + }, + + outputs: { + order: { ...ORDER_OUTPUT, description: 'The created order object' }, + metadata: { + type: 'json', + description: 'Order summary metadata', + properties: ORDER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/create_payment.ts b/apps/sim/tools/square/create_payment.ts new file mode 100644 index 00000000000..02380bf8605 --- /dev/null +++ b/apps/sim/tools/square/create_payment.ts @@ -0,0 +1,132 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CreatePaymentParams, PaymentResponse } from '@/tools/square/types' +import { + PAYMENT_METADATA_OUTPUT_PROPERTIES, + PAYMENT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareCreatePaymentTool: ToolConfig = { + id: 'square_create_payment', + name: 'Square Create Payment', + description: 'Take a payment using a payment source such as a card nonce or a card on file', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + sourceId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the payment source (card nonce, card-on-file ID, or wallet token)', + }, + amount: { + type: 'number', + required: true, + visibility: 'user-or-llm', + description: 'Amount in the smallest currency denomination (e.g. 1000 = $10.00)', + }, + currency: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Three-letter ISO 4217 currency code (e.g. USD)', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + customerId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ID of the customer associated with the payment', + }, + locationId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ID of the location where the payment is taken (defaults to the main location)', + }, + orderId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'ID of the order associated with the payment', + }, + referenceId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional external reference for the payment', + }, + note: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional note attached to the payment', + }, + autocomplete: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Whether to immediately capture the payment (defaults to true)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/payments`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + idempotency_key: params.idempotencyKey || generateId(), + source_id: params.sourceId, + amount_money: { amount: params.amount, currency: params.currency }, + } + if (params.customerId) body.customer_id = params.customerId + if (params.locationId) body.location_id = params.locationId + if (params.orderId) body.order_id = params.orderId + if (params.referenceId) body.reference_id = params.referenceId + if (params.note) body.note = params.note + if (params.autocomplete !== undefined) body.autocomplete = params.autocomplete + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const payment = data.payment ?? {} + return { + success: true, + output: { + payment, + metadata: { + id: payment.id, + status: payment.status ?? null, + order_id: payment.order_id ?? null, + }, + }, + } + }, + + outputs: { + payment: { ...PAYMENT_OUTPUT, description: 'The created payment object' }, + metadata: { + type: 'json', + description: 'Payment summary metadata', + properties: PAYMENT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/delete_catalog_object.ts b/apps/sim/tools/square/delete_catalog_object.ts new file mode 100644 index 00000000000..9cf1e37a095 --- /dev/null +++ b/apps/sim/tools/square/delete_catalog_object.ts @@ -0,0 +1,62 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CatalogDeleteResponse, DeleteCatalogObjectParams } from '@/tools/square/types' +import { SQUARE_BASE_URL, squareHeaders } from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareDeleteCatalogObjectTool: ToolConfig< + DeleteCatalogObjectParams, + CatalogDeleteResponse +> = { + id: 'square_delete_catalog_object', + name: 'Square Delete Catalog Object', + description: 'Delete a catalog object and its children (e.g. an item and its variations)', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + objectId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the catalog object to delete', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/catalog/object/${encodeURIComponent(params.objectId)}`, + method: 'DELETE', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + return { + success: true, + output: { + deleted: true, + deleted_object_ids: data.deleted_object_ids ?? [], + deleted_at: data.deleted_at ?? null, + }, + } + }, + + outputs: { + deleted: { type: 'boolean', description: 'Whether the catalog object was deleted' }, + deleted_object_ids: { + type: 'array', + description: 'IDs of all catalog objects deleted (including children)', + items: { type: 'string' }, + }, + deleted_at: { + type: 'string', + description: 'Timestamp when the deletion occurred (RFC 3339)', + optional: true, + }, + }, +} diff --git a/apps/sim/tools/square/delete_customer.ts b/apps/sim/tools/square/delete_customer.ts new file mode 100644 index 00000000000..14d255d31ce --- /dev/null +++ b/apps/sim/tools/square/delete_customer.ts @@ -0,0 +1,49 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CustomerDeleteResponse, DeleteCustomerParams } from '@/tools/square/types' +import { SQUARE_BASE_URL, squareHeaders } from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareDeleteCustomerTool: ToolConfig = { + id: 'square_delete_customer', + name: 'Square Delete Customer', + description: 'Delete a customer profile from the Square customer directory', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the customer to delete', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/customers/${encodeURIComponent(params.customerId)}`, + method: 'DELETE', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response, params) => { + await response.json().catch(() => ({})) + return { + success: true, + output: { + deleted: true, + id: params?.customerId ?? '', + }, + } + }, + + outputs: { + deleted: { type: 'boolean', description: 'Whether the customer was deleted' }, + id: { type: 'string', description: 'ID of the deleted customer' }, + }, +} diff --git a/apps/sim/tools/square/delete_invoice.ts b/apps/sim/tools/square/delete_invoice.ts new file mode 100644 index 00000000000..4b8e8064825 --- /dev/null +++ b/apps/sim/tools/square/delete_invoice.ts @@ -0,0 +1,60 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { DeleteInvoiceParams, InvoiceDeleteResponse } from '@/tools/square/types' +import { SQUARE_BASE_URL, squareHeaders } from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareDeleteInvoiceTool: ToolConfig = { + id: 'square_delete_invoice', + name: 'Square Delete Invoice', + description: 'Delete a draft invoice', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + invoiceId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the draft invoice to delete', + }, + version: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Current version of the invoice (required if the invoice has been updated)', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/invoices/${encodeURIComponent(params.invoiceId)}`) + if (params.version !== undefined) + url.searchParams.append('version', params.version.toString()) + return url.toString() + }, + method: 'DELETE', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response, params) => { + await response.json().catch(() => ({})) + return { + success: true, + output: { + deleted: true, + id: params?.invoiceId ?? '', + }, + } + }, + + outputs: { + deleted: { type: 'boolean', description: 'Whether the invoice was deleted' }, + id: { type: 'string', description: 'ID of the deleted invoice' }, + }, +} diff --git a/apps/sim/tools/square/get_catalog_object.ts b/apps/sim/tools/square/get_catalog_object.ts new file mode 100644 index 00000000000..d6651041f39 --- /dev/null +++ b/apps/sim/tools/square/get_catalog_object.ts @@ -0,0 +1,78 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CatalogObjectResponse, GetCatalogObjectParams } from '@/tools/square/types' +import { + CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + CATALOG_OBJECT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetCatalogObjectTool: ToolConfig = + { + id: 'square_get_catalog_object', + name: 'Square Get Catalog Object', + description: 'Retrieve a single catalog object by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + objectId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the catalog object to retrieve', + }, + includeRelatedObjects: { + type: 'boolean', + required: false, + visibility: 'user-or-llm', + description: 'Whether to include related objects such as an item variations', + }, + }, + + request: { + url: (params) => { + const url = new URL( + `${SQUARE_BASE_URL}/v2/catalog/object/${encodeURIComponent(params.objectId)}` + ) + if (params.includeRelatedObjects !== undefined) { + url.searchParams.append('include_related_objects', String(params.includeRelatedObjects)) + } + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const object = data.object ?? {} + return { + success: true, + output: { + object, + metadata: { + id: object.id, + type: object.type ?? null, + version: object.version ?? null, + }, + }, + } + }, + + outputs: { + object: { ...CATALOG_OBJECT_OUTPUT, description: 'The retrieved catalog object' }, + metadata: { + type: 'json', + description: 'Catalog object summary metadata', + properties: CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + }, + }, + } diff --git a/apps/sim/tools/square/get_customer.ts b/apps/sim/tools/square/get_customer.ts new file mode 100644 index 00000000000..950aca1457e --- /dev/null +++ b/apps/sim/tools/square/get_customer.ts @@ -0,0 +1,64 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CustomerResponse, GetCustomerParams } from '@/tools/square/types' +import { + CUSTOMER_METADATA_OUTPUT_PROPERTIES, + CUSTOMER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetCustomerTool: ToolConfig = { + id: 'square_get_customer', + name: 'Square Get Customer', + description: 'Retrieve a single customer profile by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the customer to retrieve', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/customers/${encodeURIComponent(params.customerId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const customer = data.customer ?? {} + return { + success: true, + output: { + customer, + metadata: { + id: customer.id, + email_address: customer.email_address ?? null, + given_name: customer.given_name ?? null, + family_name: customer.family_name ?? null, + }, + }, + } + }, + + outputs: { + customer: { ...CUSTOMER_OUTPUT, description: 'The retrieved customer object' }, + metadata: { + type: 'json', + description: 'Customer summary metadata', + properties: CUSTOMER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/get_invoice.ts b/apps/sim/tools/square/get_invoice.ts new file mode 100644 index 00000000000..bc89c9b6c61 --- /dev/null +++ b/apps/sim/tools/square/get_invoice.ts @@ -0,0 +1,63 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { GetInvoiceParams, InvoiceResponse } from '@/tools/square/types' +import { + INVOICE_METADATA_OUTPUT_PROPERTIES, + INVOICE_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetInvoiceTool: ToolConfig = { + id: 'square_get_invoice', + name: 'Square Get Invoice', + description: 'Retrieve a single invoice by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + invoiceId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the invoice to retrieve', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/invoices/${encodeURIComponent(params.invoiceId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoice = data.invoice ?? {} + return { + success: true, + output: { + invoice, + metadata: { + id: invoice.id, + status: invoice.status ?? null, + version: invoice.version ?? null, + }, + }, + } + }, + + outputs: { + invoice: { ...INVOICE_OUTPUT, description: 'The retrieved invoice object' }, + metadata: { + type: 'json', + description: 'Invoice summary metadata', + properties: INVOICE_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/get_location.ts b/apps/sim/tools/square/get_location.ts new file mode 100644 index 00000000000..17ae2755e8e --- /dev/null +++ b/apps/sim/tools/square/get_location.ts @@ -0,0 +1,60 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { GetLocationParams, LocationResponse } from '@/tools/square/types' +import { LOCATION_OUTPUT, SQUARE_BASE_URL, squareHeaders } from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetLocationTool: ToolConfig = { + id: 'square_get_location', + name: 'Square Get Location', + description: 'Retrieve a single location by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the location to retrieve (use "main" for the main location)', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/locations/${encodeURIComponent(params.locationId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const location = data.location ?? {} + return { + success: true, + output: { + location, + metadata: { + id: location.id, + name: location.name ?? null, + }, + }, + } + }, + + outputs: { + location: { ...LOCATION_OUTPUT, description: 'The retrieved location object' }, + metadata: { + type: 'json', + description: 'Location summary metadata', + properties: { + id: { type: 'string', description: 'Square location ID' }, + name: { type: 'string', description: 'Location name', optional: true }, + }, + }, + }, +} diff --git a/apps/sim/tools/square/get_order.ts b/apps/sim/tools/square/get_order.ts new file mode 100644 index 00000000000..b2277a32d6e --- /dev/null +++ b/apps/sim/tools/square/get_order.ts @@ -0,0 +1,63 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { GetOrderParams, OrderResponse } from '@/tools/square/types' +import { + ORDER_METADATA_OUTPUT_PROPERTIES, + ORDER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetOrderTool: ToolConfig = { + id: 'square_get_order', + name: 'Square Get Order', + description: 'Retrieve a single order by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + orderId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the order to retrieve', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/orders/${encodeURIComponent(params.orderId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const order = data.order ?? {} + return { + success: true, + output: { + order, + metadata: { + id: order.id, + state: order.state ?? null, + location_id: order.location_id ?? null, + }, + }, + } + }, + + outputs: { + order: { ...ORDER_OUTPUT, description: 'The retrieved order object' }, + metadata: { + type: 'json', + description: 'Order summary metadata', + properties: ORDER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/get_payment.ts b/apps/sim/tools/square/get_payment.ts new file mode 100644 index 00000000000..9114aa80a7e --- /dev/null +++ b/apps/sim/tools/square/get_payment.ts @@ -0,0 +1,63 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { GetPaymentParams, PaymentResponse } from '@/tools/square/types' +import { + PAYMENT_METADATA_OUTPUT_PROPERTIES, + PAYMENT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetPaymentTool: ToolConfig = { + id: 'square_get_payment', + name: 'Square Get Payment', + description: 'Retrieve details for a single payment by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + paymentId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the payment to retrieve', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/payments/${encodeURIComponent(params.paymentId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const payment = data.payment ?? {} + return { + success: true, + output: { + payment, + metadata: { + id: payment.id, + status: payment.status ?? null, + order_id: payment.order_id ?? null, + }, + }, + } + }, + + outputs: { + payment: { ...PAYMENT_OUTPUT, description: 'The retrieved payment object' }, + metadata: { + type: 'json', + description: 'Payment summary metadata', + properties: PAYMENT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/get_refund.ts b/apps/sim/tools/square/get_refund.ts new file mode 100644 index 00000000000..3ca9bc78030 --- /dev/null +++ b/apps/sim/tools/square/get_refund.ts @@ -0,0 +1,63 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { GetRefundParams, RefundResponse } from '@/tools/square/types' +import { + REFUND_METADATA_OUTPUT_PROPERTIES, + REFUND_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareGetRefundTool: ToolConfig = { + id: 'square_get_refund', + name: 'Square Get Refund', + description: 'Retrieve a single payment refund by its ID', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + refundId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the refund to retrieve', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/refunds/${encodeURIComponent(params.refundId)}`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const refund = data.refund ?? {} + return { + success: true, + output: { + refund, + metadata: { + id: refund.id, + status: refund.status ?? null, + payment_id: refund.payment_id ?? null, + }, + }, + } + }, + + outputs: { + refund: { ...REFUND_OUTPUT, description: 'The retrieved refund object' }, + metadata: { + type: 'json', + description: 'Refund summary metadata', + properties: REFUND_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/index.ts b/apps/sim/tools/square/index.ts new file mode 100644 index 00000000000..9daac26ec51 --- /dev/null +++ b/apps/sim/tools/square/index.ts @@ -0,0 +1,34 @@ +export { squareBatchRetrieveInventoryCountsTool } from '@/tools/square/batch_retrieve_inventory_counts' +export { squareCancelInvoiceTool } from '@/tools/square/cancel_invoice' +export { squareCancelPaymentTool } from '@/tools/square/cancel_payment' +export { squareCompletePaymentTool } from '@/tools/square/complete_payment' +export { squareCreateCatalogImageTool } from '@/tools/square/create_catalog_image' +export { squareCreateCustomerTool } from '@/tools/square/create_customer' +export { squareCreateInvoiceTool } from '@/tools/square/create_invoice' +export { squareCreateOrderTool } from '@/tools/square/create_order' +export { squareCreatePaymentTool } from '@/tools/square/create_payment' +export { squareDeleteCatalogObjectTool } from '@/tools/square/delete_catalog_object' +export { squareDeleteCustomerTool } from '@/tools/square/delete_customer' +export { squareDeleteInvoiceTool } from '@/tools/square/delete_invoice' +export { squareGetCatalogObjectTool } from '@/tools/square/get_catalog_object' +export { squareGetCustomerTool } from '@/tools/square/get_customer' +export { squareGetInvoiceTool } from '@/tools/square/get_invoice' +export { squareGetLocationTool } from '@/tools/square/get_location' +export { squareGetOrderTool } from '@/tools/square/get_order' +export { squareGetPaymentTool } from '@/tools/square/get_payment' +export { squareGetRefundTool } from '@/tools/square/get_refund' +export { squareListCatalogTool } from '@/tools/square/list_catalog' +export { squareListCustomersTool } from '@/tools/square/list_customers' +export { squareListInvoicesTool } from '@/tools/square/list_invoices' +export { squareListLocationsTool } from '@/tools/square/list_locations' +export { squareListPaymentsTool } from '@/tools/square/list_payments' +export { squareListRefundsTool } from '@/tools/square/list_refunds' +export { squarePayOrderTool } from '@/tools/square/pay_order' +export { squarePublishInvoiceTool } from '@/tools/square/publish_invoice' +export { squareRefundPaymentTool } from '@/tools/square/refund_payment' +export { squareSearchCatalogObjectsTool } from '@/tools/square/search_catalog_objects' +export { squareSearchCustomersTool } from '@/tools/square/search_customers' +export { squareSearchInvoicesTool } from '@/tools/square/search_invoices' +export { squareSearchOrdersTool } from '@/tools/square/search_orders' +export { squareUpdateCustomerTool } from '@/tools/square/update_customer' +export { squareUpsertCatalogObjectTool } from '@/tools/square/upsert_catalog_object' diff --git a/apps/sim/tools/square/list_catalog.ts b/apps/sim/tools/square/list_catalog.ts new file mode 100644 index 00000000000..04ad484a93c --- /dev/null +++ b/apps/sim/tools/square/list_catalog.ts @@ -0,0 +1,78 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CatalogListResponse, ListCatalogParams } from '@/tools/square/types' +import { + CATALOG_OBJECT_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListCatalogTool: ToolConfig = { + id: 'square_list_catalog', + name: 'Square List Catalog', + description: 'List catalog objects, optionally filtered by type', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + types: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: + 'Comma-separated catalog object types to return (e.g. ITEM,CATEGORY). Defaults to all top-level types', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/catalog/list`) + if (params.types) url.searchParams.append('types', params.types) + if (params.cursor) url.searchParams.append('cursor', params.cursor) + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const objects = data.objects ?? [] + return { + success: true, + output: { + objects, + metadata: { + count: objects.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + objects: { + type: 'array', + description: 'Array of catalog objects', + items: CATALOG_OBJECT_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/list_customers.ts b/apps/sim/tools/square/list_customers.ts new file mode 100644 index 00000000000..7ffe04cec41 --- /dev/null +++ b/apps/sim/tools/square/list_customers.ts @@ -0,0 +1,91 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CustomerListResponse, ListCustomersParams } from '@/tools/square/types' +import { + CUSTOMER_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListCustomersTool: ToolConfig = { + id: 'square_list_customers', + name: 'Square List Customers', + description: 'List customer profiles in the Square customer directory', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page (max 100)', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + sortField: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Field to sort by (DEFAULT or CREATED_AT)', + }, + sortOrder: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Sort order (ASC or DESC)', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/customers`) + if (params.limit !== undefined) url.searchParams.append('limit', params.limit.toString()) + if (params.cursor) url.searchParams.append('cursor', params.cursor) + if (params.sortField) url.searchParams.append('sort_field', params.sortField) + if (params.sortOrder) url.searchParams.append('sort_order', params.sortOrder) + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const customers = data.customers ?? [] + return { + success: true, + output: { + customers, + metadata: { + count: customers.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + customers: { + type: 'array', + description: 'Array of customer objects', + items: CUSTOMER_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/list_invoices.ts b/apps/sim/tools/square/list_invoices.ts new file mode 100644 index 00000000000..752dc018d11 --- /dev/null +++ b/apps/sim/tools/square/list_invoices.ts @@ -0,0 +1,84 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { InvoiceListResponse, ListInvoicesParams } from '@/tools/square/types' +import { + INVOICE_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListInvoicesTool: ToolConfig = { + id: 'square_list_invoices', + name: 'Square List Invoices', + description: 'List invoices for a specific location', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the location to list invoices for', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/invoices`) + url.searchParams.append('location_id', params.locationId) + if (params.limit !== undefined) url.searchParams.append('limit', params.limit.toString()) + if (params.cursor) url.searchParams.append('cursor', params.cursor) + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoices = data.invoices ?? [] + return { + success: true, + output: { + invoices, + metadata: { + count: invoices.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + invoices: { + type: 'array', + description: 'Array of invoice objects', + items: INVOICE_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/list_locations.ts b/apps/sim/tools/square/list_locations.ts new file mode 100644 index 00000000000..e52bbaf6acd --- /dev/null +++ b/apps/sim/tools/square/list_locations.ts @@ -0,0 +1,56 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { ListLocationsParams, LocationListResponse } from '@/tools/square/types' +import { LOCATION_OUTPUT, SQUARE_BASE_URL, squareHeaders } from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListLocationsTool: ToolConfig = { + id: 'square_list_locations', + name: 'Square List Locations', + description: 'List all locations associated with the Square account', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/locations`, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const locations = data.locations ?? [] + return { + success: true, + output: { + locations, + metadata: { + count: locations.length, + }, + }, + } + }, + + outputs: { + locations: { + type: 'array', + description: 'Array of location objects', + items: LOCATION_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List metadata', + properties: { + count: { type: 'number', description: 'Number of locations returned' }, + }, + }, + }, +} diff --git a/apps/sim/tools/square/list_payments.ts b/apps/sim/tools/square/list_payments.ts new file mode 100644 index 00000000000..8ae3495390b --- /dev/null +++ b/apps/sim/tools/square/list_payments.ts @@ -0,0 +1,98 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { ListPaymentsParams, PaymentListResponse } from '@/tools/square/types' +import { + LIST_METADATA_OUTPUT_PROPERTIES, + PAYMENT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListPaymentsTool: ToolConfig = { + id: 'square_list_payments', + name: 'Square List Payments', + description: 'List payments taken by the account, optionally filtered by location and time range', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter payments by location ID', + }, + beginTime: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'RFC 3339 timestamp for the beginning of the reporting period', + }, + endTime: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'RFC 3339 timestamp for the end of the reporting period', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/payments`) + if (params.locationId) url.searchParams.append('location_id', params.locationId) + if (params.beginTime) url.searchParams.append('begin_time', params.beginTime) + if (params.endTime) url.searchParams.append('end_time', params.endTime) + if (params.limit !== undefined) url.searchParams.append('limit', params.limit.toString()) + if (params.cursor) url.searchParams.append('cursor', params.cursor) + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const payments = data.payments ?? [] + return { + success: true, + output: { + payments, + metadata: { + count: payments.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + payments: { + type: 'array', + description: 'Array of payment objects', + items: PAYMENT_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/list_refunds.ts b/apps/sim/tools/square/list_refunds.ts new file mode 100644 index 00000000000..c63cac762e6 --- /dev/null +++ b/apps/sim/tools/square/list_refunds.ts @@ -0,0 +1,105 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { ListRefundsParams, RefundListResponse } from '@/tools/square/types' +import { + LIST_METADATA_OUTPUT_PROPERTIES, + REFUND_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareListRefundsTool: ToolConfig = { + id: 'square_list_refunds', + name: 'Square List Refunds', + description: 'List payment refunds, optionally filtered by location, status, and time range', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter refunds by location ID', + }, + status: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Filter by refund status (PENDING, COMPLETED, REJECTED, or FAILED)', + }, + beginTime: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'RFC 3339 timestamp for the beginning of the reporting period', + }, + endTime: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'RFC 3339 timestamp for the end of the reporting period', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: (params) => { + const url = new URL(`${SQUARE_BASE_URL}/v2/refunds`) + if (params.locationId) url.searchParams.append('location_id', params.locationId) + if (params.status) url.searchParams.append('status', params.status) + if (params.beginTime) url.searchParams.append('begin_time', params.beginTime) + if (params.endTime) url.searchParams.append('end_time', params.endTime) + if (params.limit !== undefined) url.searchParams.append('limit', params.limit.toString()) + if (params.cursor) url.searchParams.append('cursor', params.cursor) + return url.toString() + }, + method: 'GET', + headers: (params) => squareHeaders(params.apiKey), + }, + + transformResponse: async (response) => { + const data = await response.json() + const refunds = data.refunds ?? [] + return { + success: true, + output: { + refunds, + metadata: { + count: refunds.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + refunds: { + type: 'array', + description: 'Array of refund objects', + items: REFUND_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/pay_order.ts b/apps/sim/tools/square/pay_order.ts new file mode 100644 index 00000000000..d2b60122ff2 --- /dev/null +++ b/apps/sim/tools/square/pay_order.ts @@ -0,0 +1,90 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { OrderResponse, PayOrderParams } from '@/tools/square/types' +import { + ORDER_METADATA_OUTPUT_PROPERTIES, + ORDER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squarePayOrderTool: ToolConfig = { + id: 'square_pay_order', + name: 'Square Pay Order', + description: 'Pay for an order using one or more already-approved payments', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + orderId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the order to pay for', + }, + paymentIds: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'IDs of approved payments to apply to the order', + }, + orderVersion: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Version of the order being paid (for optimistic concurrency)', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/orders/${encodeURIComponent(params.orderId)}/pay`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + idempotency_key: params.idempotencyKey || generateId(), + } + if (params.paymentIds) body.payment_ids = params.paymentIds + if (params.orderVersion !== undefined) body.order_version = params.orderVersion + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const order = data.order ?? {} + return { + success: true, + output: { + order, + metadata: { + id: order.id, + state: order.state ?? null, + location_id: order.location_id ?? null, + }, + }, + } + }, + + outputs: { + order: { ...ORDER_OUTPUT, description: 'The paid order object' }, + metadata: { + type: 'json', + description: 'Order summary metadata', + properties: ORDER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/publish_invoice.ts b/apps/sim/tools/square/publish_invoice.ts new file mode 100644 index 00000000000..418d1468c78 --- /dev/null +++ b/apps/sim/tools/square/publish_invoice.ts @@ -0,0 +1,81 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { InvoiceResponse, PublishInvoiceParams } from '@/tools/square/types' +import { + INVOICE_METADATA_OUTPUT_PROPERTIES, + INVOICE_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squarePublishInvoiceTool: ToolConfig = { + id: 'square_publish_invoice', + name: 'Square Publish Invoice', + description: 'Publish a draft invoice so it is sent to the customer and becomes payable', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + invoiceId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the invoice to publish', + }, + version: { + type: 'number', + required: true, + visibility: 'user-or-llm', + description: 'Current version of the invoice (use the version returned by Create Invoice)', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: (params) => + `${SQUARE_BASE_URL}/v2/invoices/${encodeURIComponent(params.invoiceId)}/publish`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => ({ + version: params.version, + idempotency_key: params.idempotencyKey || generateId(), + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoice = data.invoice ?? {} + return { + success: true, + output: { + invoice, + metadata: { + id: invoice.id, + status: invoice.status ?? null, + version: invoice.version ?? null, + }, + }, + } + }, + + outputs: { + invoice: { ...INVOICE_OUTPUT, description: 'The published invoice object' }, + metadata: { + type: 'json', + description: 'Invoice summary metadata', + properties: INVOICE_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/refund_payment.ts b/apps/sim/tools/square/refund_payment.ts new file mode 100644 index 00000000000..91cad5ce6a4 --- /dev/null +++ b/apps/sim/tools/square/refund_payment.ts @@ -0,0 +1,97 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { RefundPaymentParams, RefundResponse } from '@/tools/square/types' +import { + REFUND_METADATA_OUTPUT_PROPERTIES, + REFUND_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareRefundPaymentTool: ToolConfig = { + id: 'square_refund_payment', + name: 'Square Refund Payment', + description: 'Refund all or part of a completed payment', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + paymentId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the payment to refund', + }, + amount: { + type: 'number', + required: true, + visibility: 'user-or-llm', + description: 'Amount to refund in the smallest currency denomination (e.g. 100 = $1.00)', + }, + currency: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'Three-letter ISO 4217 currency code (e.g. USD)', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + reason: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Reason for the refund', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/refunds`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + idempotency_key: params.idempotencyKey || generateId(), + payment_id: params.paymentId, + amount_money: { amount: params.amount, currency: params.currency }, + } + if (params.reason) body.reason = params.reason + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const refund = data.refund ?? {} + return { + success: true, + output: { + refund, + metadata: { + id: refund.id, + status: refund.status ?? null, + payment_id: refund.payment_id ?? null, + }, + }, + } + }, + + outputs: { + refund: { ...REFUND_OUTPUT, description: 'The created refund object' }, + metadata: { + type: 'json', + description: 'Refund summary metadata', + properties: REFUND_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/search_catalog_objects.ts b/apps/sim/tools/square/search_catalog_objects.ts new file mode 100644 index 00000000000..c0cbb73678d --- /dev/null +++ b/apps/sim/tools/square/search_catalog_objects.ts @@ -0,0 +1,96 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CatalogListResponse, SearchCatalogObjectsParams } from '@/tools/square/types' +import { + CATALOG_OBJECT_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareSearchCatalogObjectsTool: ToolConfig< + SearchCatalogObjectsParams, + CatalogListResponse +> = { + id: 'square_search_catalog_objects', + name: 'Square Search Catalog Objects', + description: 'Search catalog objects by type and query filters', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + objectTypes: { + type: 'array', + required: false, + visibility: 'user-or-llm', + description: 'Array of catalog object types to search (e.g. ["ITEM","CATEGORY"])', + }, + query: { + type: 'json', + required: false, + visibility: 'user-or-llm', + description: + 'Square catalog query object (e.g. {"text_query":{"keywords":["coffee"]}} or {"prefix_query":{...}})', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/catalog/search`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = {} + if (params.objectTypes) body.object_types = params.objectTypes + if (params.query) body.query = params.query + if (params.limit !== undefined) body.limit = params.limit + if (params.cursor) body.cursor = params.cursor + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const objects = data.objects ?? [] + return { + success: true, + output: { + objects, + metadata: { + count: objects.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + objects: { + type: 'array', + description: 'Array of matching catalog objects', + items: CATALOG_OBJECT_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/search_customers.ts b/apps/sim/tools/square/search_customers.ts new file mode 100644 index 00000000000..55bdf1c4980 --- /dev/null +++ b/apps/sim/tools/square/search_customers.ts @@ -0,0 +1,86 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CustomerListResponse, SearchCustomersParams } from '@/tools/square/types' +import { + CUSTOMER_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareSearchCustomersTool: ToolConfig = { + id: 'square_search_customers', + name: 'Square Search Customers', + description: 'Search customer profiles using filters such as email, phone, or creation date', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + query: { + type: 'json', + required: false, + visibility: 'user-or-llm', + description: + 'Square customer query object with optional filter and sort (e.g. {"filter":{"email_address":{"exact":"a@b.com"}}})', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/customers/search`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = {} + if (params.query) body.query = params.query + if (params.limit !== undefined) body.limit = params.limit + if (params.cursor) body.cursor = params.cursor + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const customers = data.customers ?? [] + return { + success: true, + output: { + customers, + metadata: { + count: customers.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + customers: { + type: 'array', + description: 'Array of matching customer objects', + items: CUSTOMER_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/search_invoices.ts b/apps/sim/tools/square/search_invoices.ts new file mode 100644 index 00000000000..90fecaae2b0 --- /dev/null +++ b/apps/sim/tools/square/search_invoices.ts @@ -0,0 +1,88 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { InvoiceListResponse, SearchInvoicesParams } from '@/tools/square/types' +import { + INVOICE_OUTPUT, + LIST_METADATA_OUTPUT_PROPERTIES, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareSearchInvoicesTool: ToolConfig = { + id: 'square_search_invoices', + name: 'Square Search Invoices', + description: 'Search invoices across one or more locations', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the location to search within (Square allows one location per search)', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/invoices/search`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + query: { + filter: { location_ids: [params.locationId] }, + }, + } + if (params.limit !== undefined) body.limit = params.limit + if (params.cursor) body.cursor = params.cursor + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const invoices = data.invoices ?? [] + return { + success: true, + output: { + invoices, + metadata: { + count: invoices.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + invoices: { + type: 'array', + description: 'Array of matching invoice objects', + items: INVOICE_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/search_orders.ts b/apps/sim/tools/square/search_orders.ts new file mode 100644 index 00000000000..07945aad0da --- /dev/null +++ b/apps/sim/tools/square/search_orders.ts @@ -0,0 +1,94 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { OrderListResponse, SearchOrdersParams } from '@/tools/square/types' +import { + LIST_METADATA_OUTPUT_PROPERTIES, + ORDER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareSearchOrdersTool: ToolConfig = { + id: 'square_search_orders', + name: 'Square Search Orders', + description: 'Search orders across one or more locations using filters and sorting', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + locationIds: { + type: 'array', + required: true, + visibility: 'user-or-llm', + description: 'Array of location IDs to search within', + }, + query: { + type: 'json', + required: false, + visibility: 'user-or-llm', + description: + 'Square order query object with optional filter and sort (e.g. {"filter":{"state_filter":{"states":["OPEN"]}}})', + }, + limit: { + type: 'number', + required: false, + visibility: 'user-or-llm', + description: 'Maximum number of results to return per page', + }, + cursor: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Pagination cursor from a previous response', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/orders/search`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = { + location_ids: params.locationIds, + } + if (params.query) body.query = params.query + if (params.limit !== undefined) body.limit = params.limit + if (params.cursor) body.cursor = params.cursor + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const orders = data.orders ?? [] + return { + success: true, + output: { + orders, + metadata: { + count: orders.length, + cursor: data.cursor ?? null, + }, + }, + } + }, + + outputs: { + orders: { + type: 'array', + description: 'Array of matching order objects', + items: ORDER_OUTPUT, + }, + metadata: { + type: 'json', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/types.ts b/apps/sim/tools/square/types.ts new file mode 100644 index 00000000000..ff230d76766 --- /dev/null +++ b/apps/sim/tools/square/types.ts @@ -0,0 +1,1077 @@ +import type { OutputProperty, ToolResponse } from '@/tools/types' + +/** + * Shared constants, output property definitions, and TypeScript interfaces for + * the Square API. Reused across all Square tools to keep request building and + * output shapes consistent. + * + * @see https://developer.squareup.com/reference/square + */ + +/** Square production API base URL. */ +export const SQUARE_BASE_URL = 'https://connect.squareup.com' + +/** + * Square API version pinned for every request via the `Square-Version` header. + * Square is a date-versioned API; pinning avoids silent breaking changes. + */ +export const SQUARE_API_VERSION = '2026-05-20' + +/** + * Standard headers for a JSON Square request authenticated with a personal + * access token (or any Square access token) as a bearer token. + */ +export function squareHeaders(apiKey: string): Record { + return { + Authorization: `Bearer ${apiKey}`, + 'Square-Version': SQUARE_API_VERSION, + 'Content-Type': 'application/json', + } +} + +/** + * Output definition for a Square Money object. + * @see https://developer.squareup.com/reference/square/objects/Money + */ +export const MONEY_OUTPUT_PROPERTIES = { + amount: { + type: 'number', + description: 'Amount in the smallest denomination of the currency (e.g. cents for USD)', + optional: true, + }, + currency: { + type: 'string', + description: 'Three-letter ISO 4217 currency code (e.g. USD)', + optional: true, + }, +} as const satisfies Record + +export const MONEY_OUTPUT: OutputProperty = { + type: 'object', + description: 'Monetary amount with a currency', + optional: true, + properties: MONEY_OUTPUT_PROPERTIES, +} + +/** + * Output definition for a Square Address object. + * @see https://developer.squareup.com/reference/square/objects/Address + */ +export const ADDRESS_OUTPUT_PROPERTIES = { + address_line_1: { type: 'string', description: 'First line of the address', optional: true }, + address_line_2: { type: 'string', description: 'Second line of the address', optional: true }, + address_line_3: { type: 'string', description: 'Third line of the address', optional: true }, + locality: { type: 'string', description: 'City or town', optional: true }, + sublocality: { type: 'string', description: 'Neighborhood or district', optional: true }, + administrative_district_level_1: { + type: 'string', + description: 'State, province, or region', + optional: true, + }, + postal_code: { type: 'string', description: 'Postal or ZIP code', optional: true }, + country: { + type: 'string', + description: 'Two-letter ISO 3166-1 alpha-2 country code', + optional: true, + }, + first_name: { type: 'string', description: 'First name of the addressee', optional: true }, + last_name: { type: 'string', description: 'Last name of the addressee', optional: true }, +} as const satisfies Record + +export const ADDRESS_OUTPUT: OutputProperty = { + type: 'object', + description: 'Physical address', + optional: true, + properties: ADDRESS_OUTPUT_PROPERTIES, +} + +/** + * Output definition for a Square Payment object. + * @see https://developer.squareup.com/reference/square/objects/Payment + */ +export const PAYMENT_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the payment' }, + status: { + type: 'string', + description: 'Payment status (APPROVED, PENDING, COMPLETED, CANCELED, or FAILED)', + optional: true, + }, + amount_money: MONEY_OUTPUT, + total_money: MONEY_OUTPUT, + approved_money: MONEY_OUTPUT, + app_fee_money: MONEY_OUTPUT, + refunded_money: MONEY_OUTPUT, + tip_money: MONEY_OUTPUT, + source_type: { + type: 'string', + description: 'Source of the payment (CARD, BANK_ACCOUNT, WALLET, etc.)', + optional: true, + }, + card_details: { type: 'json', description: 'Details about a card payment', optional: true }, + location_id: { + type: 'string', + description: 'ID of the location where the payment was taken', + optional: true, + }, + order_id: { type: 'string', description: 'ID of the associated order', optional: true }, + customer_id: { type: 'string', description: 'ID of the associated customer', optional: true }, + reference_id: { + type: 'string', + description: 'Optional external reference for the payment', + optional: true, + }, + receipt_number: { type: 'string', description: 'Receipt number for the payment', optional: true }, + receipt_url: { type: 'string', description: 'URL of the payment receipt', optional: true }, + note: { type: 'string', description: 'Optional note attached to the payment', optional: true }, + refund_ids: { + type: 'array', + description: 'IDs of refunds associated with the payment', + optional: true, + items: { type: 'string' }, + }, + processing_fee: { + type: 'array', + description: 'Processing fees applied to the payment', + optional: true, + items: { type: 'object' }, + }, + created_at: { type: 'string', description: 'Timestamp when the payment was created (RFC 3339)' }, + updated_at: { + type: 'string', + description: 'Timestamp when the payment was last updated (RFC 3339)', + optional: true, + }, + version_token: { + type: 'string', + description: 'Optimistic concurrency token for the payment', + optional: true, + }, +} as const satisfies Record + +export const PAYMENT_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square Payment object', + properties: PAYMENT_OUTPUT_PROPERTIES, +} + +export const PAYMENT_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square payment ID' }, + status: { type: 'string', description: 'Current payment status', optional: true }, + order_id: { type: 'string', description: 'Associated order ID', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square PaymentRefund object. + * @see https://developer.squareup.com/reference/square/objects/PaymentRefund + */ +export const REFUND_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the refund' }, + status: { + type: 'string', + description: 'Refund status (PENDING, COMPLETED, REJECTED, or FAILED)', + optional: true, + }, + amount_money: MONEY_OUTPUT, + processing_fee: { + type: 'array', + description: 'Processing fees refunded', + optional: true, + items: { type: 'object' }, + }, + payment_id: { type: 'string', description: 'ID of the payment being refunded', optional: true }, + order_id: { type: 'string', description: 'ID of the associated order', optional: true }, + location_id: { type: 'string', description: 'ID of the associated location', optional: true }, + reason: { type: 'string', description: 'Reason for the refund', optional: true }, + created_at: { type: 'string', description: 'Timestamp when the refund was created (RFC 3339)' }, + updated_at: { + type: 'string', + description: 'Timestamp when the refund was last updated (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const REFUND_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square PaymentRefund object', + properties: REFUND_OUTPUT_PROPERTIES, +} + +export const REFUND_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square refund ID' }, + status: { type: 'string', description: 'Current refund status', optional: true }, + payment_id: { type: 'string', description: 'Refunded payment ID', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square Customer object. + * @see https://developer.squareup.com/reference/square/objects/Customer + */ +export const CUSTOMER_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the customer' }, + given_name: { type: 'string', description: 'First name of the customer', optional: true }, + family_name: { type: 'string', description: 'Last name of the customer', optional: true }, + nickname: { type: 'string', description: 'Nickname of the customer', optional: true }, + company_name: { type: 'string', description: 'Business name of the customer', optional: true }, + email_address: { type: 'string', description: 'Email address of the customer', optional: true }, + phone_number: { type: 'string', description: 'Phone number of the customer', optional: true }, + address: ADDRESS_OUTPUT, + birthday: { + type: 'string', + description: 'Birthday in YYYY-MM-DD or MM-DD format', + optional: true, + }, + reference_id: { + type: 'string', + description: 'Optional external reference for the customer', + optional: true, + }, + note: { type: 'string', description: 'Note about the customer', optional: true }, + creation_source: { + type: 'string', + description: 'How the customer profile was created', + optional: true, + }, + preferences: { type: 'json', description: 'Customer communication preferences', optional: true }, + group_ids: { + type: 'array', + description: 'IDs of customer groups the customer belongs to', + optional: true, + items: { type: 'string' }, + }, + segment_ids: { + type: 'array', + description: 'IDs of customer segments the customer belongs to', + optional: true, + items: { type: 'string' }, + }, + version: { + type: 'number', + description: 'Optimistic concurrency version of the customer', + optional: true, + }, + created_at: { type: 'string', description: 'Timestamp when the customer was created (RFC 3339)' }, + updated_at: { + type: 'string', + description: 'Timestamp when the customer was last updated (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const CUSTOMER_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square Customer object', + properties: CUSTOMER_OUTPUT_PROPERTIES, +} + +export const CUSTOMER_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square customer ID' }, + email_address: { type: 'string', description: 'Customer email address', optional: true }, + given_name: { type: 'string', description: 'Customer first name', optional: true }, + family_name: { type: 'string', description: 'Customer last name', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square Location object. + * @see https://developer.squareup.com/reference/square/objects/Location + */ +export const LOCATION_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the location' }, + name: { type: 'string', description: 'Name of the location', optional: true }, + address: ADDRESS_OUTPUT, + timezone: { type: 'string', description: 'IANA timezone of the location', optional: true }, + status: { type: 'string', description: 'Location status (ACTIVE or INACTIVE)', optional: true }, + type: { type: 'string', description: 'Location type (PHYSICAL or MOBILE)', optional: true }, + merchant_id: { + type: 'string', + description: 'ID of the merchant that owns the location', + optional: true, + }, + country: { type: 'string', description: 'Country code of the location', optional: true }, + language_code: { type: 'string', description: 'Language code of the location', optional: true }, + currency: { type: 'string', description: 'Currency used by the location', optional: true }, + phone_number: { type: 'string', description: 'Phone number of the location', optional: true }, + business_name: { + type: 'string', + description: 'Business name shown to customers', + optional: true, + }, + business_email: { type: 'string', description: 'Email of the business', optional: true }, + description: { type: 'string', description: 'Description of the location', optional: true }, + capabilities: { + type: 'array', + description: 'Capabilities of the location (e.g. CREDIT_CARD_PROCESSING)', + optional: true, + items: { type: 'string' }, + }, + created_at: { + type: 'string', + description: 'Timestamp when the location was created (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const LOCATION_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square Location object', + properties: LOCATION_OUTPUT_PROPERTIES, +} + +/** + * Output definition for a Square Order object. + * @see https://developer.squareup.com/reference/square/objects/Order + */ +export const ORDER_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the order' }, + location_id: { type: 'string', description: 'ID of the location for the order', optional: true }, + reference_id: { + type: 'string', + description: 'Optional external reference for the order', + optional: true, + }, + customer_id: { type: 'string', description: 'ID of the associated customer', optional: true }, + state: { + type: 'string', + description: 'Order state (OPEN, COMPLETED, or CANCELED)', + optional: true, + }, + version: { + type: 'number', + description: 'Optimistic concurrency version of the order', + optional: true, + }, + line_items: { + type: 'array', + description: 'Line items in the order', + optional: true, + items: { type: 'object' }, + }, + taxes: { + type: 'array', + description: 'Taxes applied to the order', + optional: true, + items: { type: 'object' }, + }, + discounts: { + type: 'array', + description: 'Discounts applied to the order', + optional: true, + items: { type: 'object' }, + }, + fulfillments: { + type: 'array', + description: 'Fulfillments for the order', + optional: true, + items: { type: 'object' }, + }, + net_amounts: { type: 'json', description: 'Net money amounts for the order', optional: true }, + total_money: MONEY_OUTPUT, + total_tax_money: MONEY_OUTPUT, + total_discount_money: MONEY_OUTPUT, + total_service_charge_money: MONEY_OUTPUT, + total_tip_money: MONEY_OUTPUT, + created_at: { + type: 'string', + description: 'Timestamp when the order was created (RFC 3339)', + optional: true, + }, + updated_at: { + type: 'string', + description: 'Timestamp when the order was last updated (RFC 3339)', + optional: true, + }, + closed_at: { + type: 'string', + description: 'Timestamp when the order was closed (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const ORDER_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square Order object', + properties: ORDER_OUTPUT_PROPERTIES, +} + +export const ORDER_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square order ID' }, + state: { type: 'string', description: 'Current order state', optional: true }, + location_id: { type: 'string', description: 'Order location ID', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square Invoice object. + * @see https://developer.squareup.com/reference/square/objects/Invoice + */ +export const INVOICE_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Unique ID for the invoice' }, + version: { + type: 'number', + description: 'Optimistic concurrency version of the invoice', + optional: true, + }, + location_id: { + type: 'string', + description: 'ID of the location for the invoice', + optional: true, + }, + order_id: { + type: 'string', + description: 'ID of the order the invoice bills for', + optional: true, + }, + status: { + type: 'string', + description: 'Invoice status (DRAFT, UNPAID, SCHEDULED, PARTIALLY_PAID, PAID, etc.)', + optional: true, + }, + invoice_number: { type: 'string', description: 'Human-readable invoice number', optional: true }, + title: { type: 'string', description: 'Title of the invoice', optional: true }, + description: { type: 'string', description: 'Description of the invoice', optional: true }, + public_url: { + type: 'string', + description: 'URL where the customer can view and pay the invoice', + optional: true, + }, + primary_recipient: { + type: 'json', + description: 'Primary recipient of the invoice', + optional: true, + }, + payment_requests: { + type: 'array', + description: 'Payment requests for the invoice', + optional: true, + items: { type: 'object' }, + }, + next_payment_amount_money: MONEY_OUTPUT, + scheduled_at: { + type: 'string', + description: 'Timestamp when the invoice is scheduled to be sent (RFC 3339)', + optional: true, + }, + timezone: { type: 'string', description: 'Timezone used for invoice dates', optional: true }, + delivery_method: { + type: 'string', + description: 'How the invoice is delivered (EMAIL, SHARE_MANUALLY, SMS)', + optional: true, + }, + created_at: { + type: 'string', + description: 'Timestamp when the invoice was created (RFC 3339)', + optional: true, + }, + updated_at: { + type: 'string', + description: 'Timestamp when the invoice was last updated (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const INVOICE_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square Invoice object', + properties: INVOICE_OUTPUT_PROPERTIES, +} + +export const INVOICE_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square invoice ID' }, + status: { type: 'string', description: 'Current invoice status', optional: true }, + version: { type: 'number', description: 'Invoice version', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square CatalogObject. + * Catalog objects are polymorphic; type-specific data lives in `*_data` fields. + * @see https://developer.squareup.com/reference/square/objects/CatalogObject + */ +export const CATALOG_OBJECT_OUTPUT_PROPERTIES = { + type: { + type: 'string', + description: 'Type of catalog object (ITEM, ITEM_VARIATION, CATEGORY, IMAGE, etc.)', + }, + id: { type: 'string', description: 'Unique ID for the catalog object' }, + version: { + type: 'number', + description: 'Optimistic concurrency version of the object', + optional: true, + }, + updated_at: { + type: 'string', + description: 'Timestamp when the object was last updated (RFC 3339)', + optional: true, + }, + is_deleted: { type: 'boolean', description: 'Whether the object is deleted', optional: true }, + present_at_all_locations: { + type: 'boolean', + description: 'Whether the object is present at all locations', + optional: true, + }, + item_data: { + type: 'json', + description: 'Item-specific data (when type is ITEM)', + optional: true, + }, + item_variation_data: { + type: 'json', + description: 'Variation-specific data (when type is ITEM_VARIATION)', + optional: true, + }, + category_data: { + type: 'json', + description: 'Category-specific data (when type is CATEGORY)', + optional: true, + }, + image_data: { + type: 'json', + description: 'Image-specific data (when type is IMAGE)', + optional: true, + }, +} as const satisfies Record + +export const CATALOG_OBJECT_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square CatalogObject', + properties: CATALOG_OBJECT_OUTPUT_PROPERTIES, +} + +export const CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES = { + id: { type: 'string', description: 'Square catalog object ID' }, + type: { type: 'string', description: 'Catalog object type', optional: true }, + version: { type: 'number', description: 'Catalog object version', optional: true }, +} as const satisfies Record + +/** + * Output definition for a Square InventoryCount object. + * @see https://developer.squareup.com/reference/square/objects/InventoryCount + */ +export const INVENTORY_COUNT_OUTPUT_PROPERTIES = { + catalog_object_id: { + type: 'string', + description: 'ID of the catalog object (item variation) being counted', + optional: true, + }, + catalog_object_type: { + type: 'string', + description: 'Type of the counted catalog object (usually ITEM_VARIATION)', + optional: true, + }, + state: { + type: 'string', + description: 'Inventory state (e.g. IN_STOCK, SOLD, WASTE)', + optional: true, + }, + location_id: { type: 'string', description: 'ID of the location for this count', optional: true }, + quantity: { + type: 'string', + description: 'Number of units in the given state at the location', + optional: true, + }, + calculated_at: { + type: 'string', + description: 'Timestamp when the count was calculated (RFC 3339)', + optional: true, + }, +} as const satisfies Record + +export const INVENTORY_COUNT_OUTPUT: OutputProperty = { + type: 'object', + description: 'Square InventoryCount object', + properties: INVENTORY_COUNT_OUTPUT_PROPERTIES, +} + +/** + * Pagination metadata for cursor-paged Square list/search endpoints. + */ +export const LIST_METADATA_OUTPUT_PROPERTIES = { + count: { type: 'number', description: 'Number of items returned in this page' }, + cursor: { + type: 'string', + description: 'Pagination cursor to fetch the next page, if more results exist', + optional: true, + }, +} as const satisfies Record + +export const LIST_METADATA_OUTPUT: OutputProperty = { + type: 'object', + description: 'List pagination metadata', + properties: LIST_METADATA_OUTPUT_PROPERTIES, +} + +interface SquareMoney { + amount?: number + currency?: string +} + +interface SquareAddress { + address_line_1?: string + address_line_2?: string + locality?: string + administrative_district_level_1?: string + postal_code?: string + country?: string + [key: string]: unknown +} + +interface SquareListMetadata { + count: number + cursor?: string +} + +interface PaymentObject { + id: string + status?: string + amount_money?: SquareMoney + order_id?: string + created_at: string + [key: string]: unknown +} + +interface RefundObject { + id: string + status?: string + amount_money?: SquareMoney + payment_id?: string + created_at: string + [key: string]: unknown +} + +interface CustomerObject { + id: string + given_name?: string + family_name?: string + email_address?: string + created_at: string + [key: string]: unknown +} + +interface LocationObject { + id: string + name?: string + [key: string]: unknown +} + +interface OrderObject { + id: string + state?: string + location_id?: string + [key: string]: unknown +} + +interface InvoiceObject { + id: string + status?: string + version?: number + [key: string]: unknown +} + +interface CatalogObject { + id: string + type: string + version?: number + [key: string]: unknown +} + +interface InventoryCountObject { + catalog_object_id?: string + catalog_object_type?: string + state?: string + location_id?: string + quantity?: string + calculated_at?: string + [key: string]: unknown +} + +export interface CreatePaymentParams { + apiKey: string + sourceId: string + amount: number + currency: string + idempotencyKey?: string + customerId?: string + locationId?: string + orderId?: string + referenceId?: string + note?: string + autocomplete?: boolean +} + +export interface GetPaymentParams { + apiKey: string + paymentId: string +} + +export interface ListPaymentsParams { + apiKey: string + locationId?: string + beginTime?: string + endTime?: string + limit?: number + cursor?: string +} + +export interface RefundPaymentParams { + apiKey: string + paymentId: string + amount: number + currency: string + idempotencyKey?: string + reason?: string +} + +export interface CreateCustomerParams { + apiKey: string + givenName?: string + familyName?: string + companyName?: string + nickname?: string + emailAddress?: string + phoneNumber?: string + birthday?: string + note?: string + referenceId?: string + address?: SquareAddress + idempotencyKey?: string +} + +export interface GetCustomerParams { + apiKey: string + customerId: string +} + +export interface ListCustomersParams { + apiKey: string + limit?: number + cursor?: string + sortField?: string + sortOrder?: string +} + +export interface SearchCustomersParams { + apiKey: string + query?: Record + limit?: number + cursor?: string +} + +export interface UpdateCustomerParams { + apiKey: string + customerId: string + givenName?: string + familyName?: string + companyName?: string + nickname?: string + emailAddress?: string + phoneNumber?: string + birthday?: string + note?: string + referenceId?: string + address?: SquareAddress +} + +export interface DeleteCustomerParams { + apiKey: string + customerId: string +} + +export interface ListLocationsParams { + apiKey: string +} + +export interface CreateOrderParams { + apiKey: string + order: Record + idempotencyKey?: string +} + +export interface GetOrderParams { + apiKey: string + orderId: string +} + +export interface SearchOrdersParams { + apiKey: string + locationIds: string[] + query?: Record + limit?: number + cursor?: string +} + +export interface CreateInvoiceParams { + apiKey: string + invoice: Record + idempotencyKey?: string +} + +export interface GetInvoiceParams { + apiKey: string + invoiceId: string +} + +export interface ListInvoicesParams { + apiKey: string + locationId: string + limit?: number + cursor?: string +} + +export interface PublishInvoiceParams { + apiKey: string + invoiceId: string + version: number + idempotencyKey?: string +} + +export interface UpsertCatalogObjectParams { + apiKey: string + object: Record + idempotencyKey?: string +} + +export interface GetCatalogObjectParams { + apiKey: string + objectId: string + includeRelatedObjects?: boolean +} + +export interface ListCatalogParams { + apiKey: string + types?: string + cursor?: string +} + +export interface SearchCatalogObjectsParams { + apiKey: string + objectTypes?: string[] + query?: Record + limit?: number + cursor?: string +} + +export interface CreateCatalogImageParams { + apiKey: string + file?: unknown + fileName?: string + objectId?: string + caption?: string + idempotencyKey?: string +} + +export interface CancelPaymentParams { + apiKey: string + paymentId: string +} + +export interface CompletePaymentParams { + apiKey: string + paymentId: string + versionToken?: string +} + +export interface GetRefundParams { + apiKey: string + refundId: string +} + +export interface ListRefundsParams { + apiKey: string + locationId?: string + status?: string + beginTime?: string + endTime?: string + limit?: number + cursor?: string +} + +export interface PayOrderParams { + apiKey: string + orderId: string + orderVersion?: number + paymentIds?: string[] + idempotencyKey?: string +} + +export interface SearchInvoicesParams { + apiKey: string + locationId: string + limit?: number + cursor?: string +} + +export interface CancelInvoiceParams { + apiKey: string + invoiceId: string + version: number +} + +export interface DeleteInvoiceParams { + apiKey: string + invoiceId: string + version?: number +} + +export interface DeleteCatalogObjectParams { + apiKey: string + objectId: string +} + +export interface GetLocationParams { + apiKey: string + locationId: string +} + +export interface BatchRetrieveInventoryCountsParams { + apiKey: string + catalogObjectIds?: string[] + locationIds?: string[] + states?: string[] + updatedAfter?: string + limit?: number + cursor?: string +} + +export interface PaymentResponse extends ToolResponse { + output: { + payment: PaymentObject + metadata: { id: string; status?: string; order_id?: string } + } +} + +export interface PaymentListResponse extends ToolResponse { + output: { + payments: PaymentObject[] + metadata: SquareListMetadata + } +} + +export interface RefundResponse extends ToolResponse { + output: { + refund: RefundObject + metadata: { id: string; status?: string; payment_id?: string } + } +} + +export interface CustomerResponse extends ToolResponse { + output: { + customer: CustomerObject + metadata: { id: string; email_address?: string; given_name?: string; family_name?: string } + } +} + +export interface CustomerListResponse extends ToolResponse { + output: { + customers: CustomerObject[] + metadata: SquareListMetadata + } +} + +export interface CustomerDeleteResponse extends ToolResponse { + output: { + deleted: boolean + id: string + } +} + +export interface LocationListResponse extends ToolResponse { + output: { + locations: LocationObject[] + metadata: { count: number } + } +} + +export interface OrderResponse extends ToolResponse { + output: { + order: OrderObject + metadata: { id: string; state?: string; location_id?: string } + } +} + +export interface OrderListResponse extends ToolResponse { + output: { + orders: OrderObject[] + metadata: SquareListMetadata + } +} + +export interface InvoiceResponse extends ToolResponse { + output: { + invoice: InvoiceObject + metadata: { id: string; status?: string; version?: number } + } +} + +export interface InvoiceListResponse extends ToolResponse { + output: { + invoices: InvoiceObject[] + metadata: SquareListMetadata + } +} + +export interface CatalogObjectResponse extends ToolResponse { + output: { + object: CatalogObject + metadata: { id: string; type?: string; version?: number } + } +} + +export interface CatalogListResponse extends ToolResponse { + output: { + objects: CatalogObject[] + metadata: SquareListMetadata + } +} + +export interface RefundListResponse extends ToolResponse { + output: { + refunds: RefundObject[] + metadata: SquareListMetadata + } +} + +export interface LocationResponse extends ToolResponse { + output: { + location: LocationObject + metadata: { id: string; name?: string } + } +} + +export interface InvoiceDeleteResponse extends ToolResponse { + output: { + deleted: boolean + id: string + } +} + +export interface CatalogDeleteResponse extends ToolResponse { + output: { + deleted: boolean + deleted_object_ids: string[] + deleted_at: string | null + } +} + +export interface InventoryCountListResponse extends ToolResponse { + output: { + counts: InventoryCountObject[] + metadata: SquareListMetadata + } +} + +export type SquareResponse = + | PaymentResponse + | PaymentListResponse + | RefundResponse + | RefundListResponse + | CustomerResponse + | CustomerListResponse + | CustomerDeleteResponse + | LocationListResponse + | LocationResponse + | OrderResponse + | OrderListResponse + | InvoiceResponse + | InvoiceListResponse + | InvoiceDeleteResponse + | CatalogObjectResponse + | CatalogListResponse + | CatalogDeleteResponse + | InventoryCountListResponse diff --git a/apps/sim/tools/square/update_customer.ts b/apps/sim/tools/square/update_customer.ts new file mode 100644 index 00000000000..f41f3eb6c88 --- /dev/null +++ b/apps/sim/tools/square/update_customer.ts @@ -0,0 +1,138 @@ +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CustomerResponse, UpdateCustomerParams } from '@/tools/square/types' +import { + CUSTOMER_METADATA_OUTPUT_PROPERTIES, + CUSTOMER_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareUpdateCustomerTool: ToolConfig = { + id: 'square_update_customer', + name: 'Square Update Customer', + description: 'Update fields on an existing customer profile', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + customerId: { + type: 'string', + required: true, + visibility: 'user-or-llm', + description: 'ID of the customer to update', + }, + givenName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'First name of the customer', + }, + familyName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Last name of the customer', + }, + companyName: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Business name of the customer', + }, + nickname: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Nickname of the customer', + }, + emailAddress: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Email address of the customer', + }, + phoneNumber: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Phone number of the customer', + }, + birthday: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Birthday in YYYY-MM-DD or MM-DD format', + }, + note: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Note about the customer', + }, + referenceId: { + type: 'string', + required: false, + visibility: 'user-or-llm', + description: 'Optional external reference for the customer', + }, + address: { + type: 'json', + required: false, + visibility: 'user-or-llm', + description: 'Square address object for the customer', + }, + }, + + request: { + url: (params) => `${SQUARE_BASE_URL}/v2/customers/${encodeURIComponent(params.customerId)}`, + method: 'PUT', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => { + const body: Record = {} + if (params.givenName !== undefined) body.given_name = params.givenName + if (params.familyName !== undefined) body.family_name = params.familyName + if (params.companyName !== undefined) body.company_name = params.companyName + if (params.nickname !== undefined) body.nickname = params.nickname + if (params.emailAddress !== undefined) body.email_address = params.emailAddress + if (params.phoneNumber !== undefined) body.phone_number = params.phoneNumber + if (params.birthday !== undefined) body.birthday = params.birthday + if (params.note !== undefined) body.note = params.note + if (params.referenceId !== undefined) body.reference_id = params.referenceId + if (params.address !== undefined) body.address = params.address + return body + }, + }, + + transformResponse: async (response) => { + const data = await response.json() + const customer = data.customer ?? {} + return { + success: true, + output: { + customer, + metadata: { + id: customer.id, + email_address: customer.email_address ?? null, + given_name: customer.given_name ?? null, + family_name: customer.family_name ?? null, + }, + }, + } + }, + + outputs: { + customer: { ...CUSTOMER_OUTPUT, description: 'The updated customer object' }, + metadata: { + type: 'json', + description: 'Customer summary metadata', + properties: CUSTOMER_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/square/upsert_catalog_object.ts b/apps/sim/tools/square/upsert_catalog_object.ts new file mode 100644 index 00000000000..69d3731da50 --- /dev/null +++ b/apps/sim/tools/square/upsert_catalog_object.ts @@ -0,0 +1,78 @@ +import { generateId } from '@sim/utils/id' +import { ErrorExtractorId } from '@/tools/error-extractors' +import type { CatalogObjectResponse, UpsertCatalogObjectParams } from '@/tools/square/types' +import { + CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + CATALOG_OBJECT_OUTPUT, + SQUARE_BASE_URL, + squareHeaders, +} from '@/tools/square/types' +import type { ToolConfig } from '@/tools/types' + +export const squareUpsertCatalogObjectTool: ToolConfig< + UpsertCatalogObjectParams, + CatalogObjectResponse +> = { + id: 'square_upsert_catalog_object', + name: 'Square Upsert Catalog Object', + description: 'Create or update a catalog object such as an item, variation, or category', + version: '1.0.0', + errorExtractor: ErrorExtractorId.SQUARE_ERRORS, + + params: { + apiKey: { + type: 'string', + required: true, + visibility: 'user-only', + description: 'Square access token (personal access token)', + }, + object: { + type: 'json', + required: true, + visibility: 'user-or-llm', + description: + 'Square catalog object to create or update. Use ID "#name" for new objects (e.g. {"type":"ITEM","id":"#Coffee","item_data":{"name":"Coffee"}})', + }, + idempotencyKey: { + type: 'string', + required: false, + visibility: 'user-only', + description: 'Unique key to make the request idempotent (auto-generated if omitted)', + }, + }, + + request: { + url: () => `${SQUARE_BASE_URL}/v2/catalog/object`, + method: 'POST', + headers: (params) => squareHeaders(params.apiKey), + body: (params) => ({ + idempotency_key: params.idempotencyKey || generateId(), + object: params.object, + }), + }, + + transformResponse: async (response) => { + const data = await response.json() + const object = data.catalog_object ?? {} + return { + success: true, + output: { + object, + metadata: { + id: object.id, + type: object.type ?? null, + version: object.version ?? null, + }, + }, + } + }, + + outputs: { + object: { ...CATALOG_OBJECT_OUTPUT, description: 'The created or updated catalog object' }, + metadata: { + type: 'json', + description: 'Catalog object summary metadata', + properties: CATALOG_OBJECT_METADATA_OUTPUT_PROPERTIES, + }, + }, +} diff --git a/apps/sim/tools/trello/shared.ts b/apps/sim/tools/trello/shared.ts index e99e83d73b1..2491d5add68 100644 --- a/apps/sim/tools/trello/shared.ts +++ b/apps/sim/tools/trello/shared.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import type { TrelloAction, TrelloActionBoardTarget, @@ -10,14 +11,8 @@ import type { TrelloMember, } from '@/tools/trello/types' -type TrelloRecord = Record - export const TRELLO_API_BASE_URL = 'https://api.trello.com/1' -function isRecord(value: unknown): value is TrelloRecord { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function getRequiredString(value: unknown, field: string): string { if (typeof value === 'string' && value.trim().length > 0) { return value @@ -67,7 +62,7 @@ function getIdArray(value: unknown): string[] { return [item] } - if (isRecord(item) && typeof item.id === 'string' && item.id.trim().length > 0) { + if (isRecordLike(item) && typeof item.id === 'string' && item.id.trim().length > 0) { return [item.id] } @@ -76,7 +71,7 @@ function getIdArray(value: unknown): string[] { } function mapTrelloLabel(value: unknown): TrelloLabel | null { - if (!isRecord(value) || typeof value.id !== 'string') { + if (!isRecordLike(value) || typeof value.id !== 'string') { return null } @@ -88,7 +83,7 @@ function mapTrelloLabel(value: unknown): TrelloLabel | null { } function mapTrelloMember(value: unknown): TrelloMember | null { - if (!isRecord(value) || typeof value.id !== 'string') { + if (!isRecordLike(value) || typeof value.id !== 'string') { return null } @@ -100,7 +95,7 @@ function mapTrelloMember(value: unknown): TrelloMember | null { } function mapActionCardTarget(value: unknown): TrelloActionCardTarget | null { - if (!isRecord(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { + if (!isRecordLike(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { return null } @@ -114,7 +109,7 @@ function mapActionCardTarget(value: unknown): TrelloActionCardTarget | null { } function mapActionBoardTarget(value: unknown): TrelloActionBoardTarget | null { - if (!isRecord(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { + if (!isRecordLike(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { return null } @@ -126,7 +121,7 @@ function mapActionBoardTarget(value: unknown): TrelloActionBoardTarget | null { } function mapActionListTarget(value: unknown): TrelloActionListTarget | null { - if (!isRecord(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { + if (!isRecordLike(value) || typeof value.id !== 'string' || typeof value.name !== 'string') { return null } @@ -137,7 +132,7 @@ function mapActionListTarget(value: unknown): TrelloActionListTarget | null { } export function mapTrelloList(value: unknown): TrelloList { - if (!isRecord(value)) { + if (!isRecordLike(value)) { throw new Error('Trello returned an invalid list object') } @@ -151,7 +146,7 @@ export function mapTrelloList(value: unknown): TrelloList { } export function mapTrelloCard(value: unknown): TrelloCard { - if (!isRecord(value)) { + if (!isRecordLike(value)) { throw new Error('Trello returned an invalid card object') } @@ -181,11 +176,11 @@ export function mapTrelloCard(value: unknown): TrelloCard { } export function mapTrelloAction(value: unknown): TrelloAction { - if (!isRecord(value)) { + if (!isRecordLike(value)) { throw new Error('Trello returned an invalid action object') } - const data = isRecord(value.data) ? value.data : null + const data = isRecordLike(value.data) ? value.data : null return { id: getRequiredString(value.id, 'id'), @@ -211,7 +206,7 @@ export function extractTrelloErrorMessage( ): string { const parts: string[] = [] - if (isRecord(data)) { + if (isRecordLike(data)) { const message = data.message const error = data.error diff --git a/apps/sim/tools/vanta/utils.ts b/apps/sim/tools/vanta/utils.ts index 4a9c3a00ccc..00aa5f55cce 100644 --- a/apps/sim/tools/vanta/utils.ts +++ b/apps/sim/tools/vanta/utils.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import type { VantaControl, VantaControlDetail, @@ -70,16 +71,12 @@ export function createVantaTransformResponse -function isJsonRecord(value: unknown): value is JsonRecord { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - /** * Coerces an unknown single-resource response body to a record so the * normalizers can run on it; non-object bodies normalize to all-null fields. */ export function asVantaRecord(value: unknown): JsonRecord { - return isJsonRecord(value) ? value : {} + return isRecordLike(value) ? value : {} } function getString(value: unknown): string | null { @@ -101,16 +98,16 @@ function getStringArray(value: unknown): string[] { function getRecordArray(value: unknown): JsonRecord[] { if (!Array.isArray(value)) return [] - return value.filter(isJsonRecord) + return value.filter(isRecordLike) } /** * Extracts a human-readable error message from a Vanta API error body. */ export function extractVantaError(data: unknown, fallback: string): string { - if (!isJsonRecord(data)) return fallback + if (!isRecordLike(data)) return fallback - if (isJsonRecord(data.error)) { + if (isRecordLike(data.error)) { const nested = getString(data.error.message) ?? getString(data.error.code) if (nested) return nested } @@ -198,7 +195,7 @@ async function exchangeVantaToken(params: VantaTokenParams, cacheKey: string): P throw new Error(extractVantaError(data, 'Failed to authenticate with Vanta')) } - if (!isJsonRecord(data) || typeof data.access_token !== 'string') { + if (!isRecordLike(data) || typeof data.access_token !== 'string') { throw new Error('Vanta authentication did not return an access token') } @@ -313,7 +310,7 @@ export function getVantaListResults(data: unknown): { data: JsonRecord[] pageInfo: VantaPageInfo | null } { - if (!isJsonRecord(data) || !isJsonRecord(data.results)) { + if (!isRecordLike(data) || !isRecordLike(data.results)) { return { data: [], pageInfo: null } } return { @@ -323,7 +320,7 @@ export function getVantaListResults(data: unknown): { } export function normalizeVantaPageInfo(value: unknown): VantaPageInfo | null { - if (!isJsonRecord(value)) return null + if (!isRecordLike(value)) return null return { startCursor: getString(value.startCursor), endCursor: getString(value.endCursor), @@ -333,7 +330,7 @@ export function normalizeVantaPageInfo(value: unknown): VantaPageInfo | null { } function normalizeVantaOwner(value: unknown): VantaOwner | null { - if (!isJsonRecord(value)) return null + if (!isRecordLike(value)) return null return { id: getString(value.id), displayName: getString(value.displayName), @@ -433,17 +430,17 @@ export function normalizeVantaControlDetail(resource: JsonRecord): VantaControlD } export function normalizeVantaTest(resource: JsonRecord): VantaTest { - const version = isJsonRecord(resource.version) + const version = isRecordLike(resource.version) ? { major: getNumber(resource.version.major), minor: getNumber(resource.version.minor) } : null - const deactivatedStatusInfo = isJsonRecord(resource.deactivatedStatusInfo) + const deactivatedStatusInfo = isRecordLike(resource.deactivatedStatusInfo) ? { isDeactivated: getBoolean(resource.deactivatedStatusInfo.isDeactivated), deactivatedReason: getString(resource.deactivatedStatusInfo.deactivatedReason), lastUpdatedDate: getString(resource.deactivatedStatusInfo.lastUpdatedDate), } : null - const remediationStatusInfo = isJsonRecord(resource.remediationStatusInfo) + const remediationStatusInfo = isRecordLike(resource.remediationStatusInfo) ? { status: getString(resource.remediationStatusInfo.status), soonestRemediateByDate: getString(resource.remediationStatusInfo.soonestRemediateByDate), @@ -496,7 +493,7 @@ export function normalizeVantaDocument(resource: JsonRecord): VantaDocument { } export function normalizeVantaDocumentDetail(resource: JsonRecord): VantaDocumentDetail { - const deactivatedStatus = isJsonRecord(resource.deactivatedStatus) + const deactivatedStatus = isRecordLike(resource.deactivatedStatus) ? { isDeactivated: getBoolean(resource.deactivatedStatus.isDeactivated), reason: getString(resource.deactivatedStatus.reason), @@ -517,7 +514,7 @@ export function normalizeVantaDocumentDetail(resource: JsonRecord): VantaDocumen } export function normalizeVantaUploadedFile(resource: JsonRecord): VantaUploadedFile { - const uploadedBy = isJsonRecord(resource.uploadedBy) + const uploadedBy = isRecordLike(resource.uploadedBy) ? { id: getString(resource.uploadedBy.id), type: getString(resource.uploadedBy.type) } : null @@ -537,14 +534,14 @@ export function normalizeVantaUploadedFile(resource: JsonRecord): VantaUploadedF } export function normalizeVantaPerson(resource: JsonRecord): VantaPerson { - const name = isJsonRecord(resource.name) + const name = isRecordLike(resource.name) ? { first: getString(resource.name.first), last: getString(resource.name.last), display: getString(resource.name.display), } : null - const employment = isJsonRecord(resource.employment) + const employment = isRecordLike(resource.employment) ? { status: getString(resource.employment.status), startDate: getString(resource.employment.startDate), @@ -552,14 +549,14 @@ export function normalizeVantaPerson(resource: JsonRecord): VantaPerson { jobTitle: getString(resource.employment.jobTitle), } : null - const leaveInfo = isJsonRecord(resource.leaveInfo) + const leaveInfo = isRecordLike(resource.leaveInfo) ? { status: getString(resource.leaveInfo.status), startDate: getString(resource.leaveInfo.startDate), endDate: getString(resource.leaveInfo.endDate), } : null - const tasksSummary = isJsonRecord(resource.tasksSummary) + const tasksSummary = isRecordLike(resource.tasksSummary) ? { status: getString(resource.tasksSummary.status), dueDate: getString(resource.tasksSummary.dueDate), @@ -588,7 +585,7 @@ function normalizeVantaPolicyDocument(resource: JsonRecord): VantaPolicyDocument } export function normalizeVantaPolicy(resource: JsonRecord): VantaPolicy { - const latestApprovedVersion = isJsonRecord(resource.latestApprovedVersion) + const latestApprovedVersion = isRecordLike(resource.latestApprovedVersion) ? { versionId: getString(resource.latestApprovedVersion.versionId), documents: getRecordArray(resource.latestApprovedVersion.documents).map( @@ -603,7 +600,7 @@ export function normalizeVantaPolicy(resource: JsonRecord): VantaPolicy { description: getString(resource.description), status: getString(resource.status), approvedAtDate: getString(resource.approvedAtDate), - latestVersionStatus: isJsonRecord(resource.latestVersion) + latestVersionStatus: isRecordLike(resource.latestVersion) ? getString(resource.latestVersion.status) : null, latestApprovedVersion, @@ -611,7 +608,7 @@ export function normalizeVantaPolicy(resource: JsonRecord): VantaPolicy { } export function normalizeVantaVendor(resource: JsonRecord): VantaVendor { - const authDetails = isJsonRecord(resource.authDetails) + const authDetails = isRecordLike(resource.authDetails) ? { method: getString(resource.authDetails.method), passwordMFA: getBoolean(resource.authDetails.passwordMFA), @@ -620,19 +617,19 @@ export function normalizeVantaVendor(resource: JsonRecord): VantaVendor { passwordRequiresSymbol: getBoolean(resource.authDetails.passwordRequiresSymbol), } : null - const contractAmount = isJsonRecord(resource.contractAmount) + const contractAmount = isRecordLike(resource.contractAmount) ? { amount: getNumber(resource.contractAmount.amount), currency: getString(resource.contractAmount.currency), } : null - const latestDecision = isJsonRecord(resource.latestDecision) + const latestDecision = isRecordLike(resource.latestDecision) ? { status: getString(resource.latestDecision.status), lastUpdatedAt: getString(resource.latestDecision.lastUpdatedAt), } : null - const procurementRequest = isJsonRecord(resource.linkedTaskTrackerTaskProcurementRequest) + const procurementRequest = isRecordLike(resource.linkedTaskTrackerTaskProcurementRequest) ? { url: getString(resource.linkedTaskTrackerTaskProcurementRequest.url), service: getString(resource.linkedTaskTrackerTaskProcurementRequest.service), @@ -644,7 +641,7 @@ export function normalizeVantaVendor(resource: JsonRecord): VantaVendor { name: getString(resource.name), status: getString(resource.status), websiteUrl: getString(resource.websiteUrl), - category: isJsonRecord(resource.category) ? getString(resource.category.displayName) : null, + category: isRecordLike(resource.category) ? getString(resource.category.displayName) : null, servicesProvided: getString(resource.servicesProvided), additionalNotes: getString(resource.additionalNotes), accountManagerName: getString(resource.accountManagerName), @@ -671,11 +668,11 @@ export function normalizeVantaVendor(resource: JsonRecord): VantaVendor { } function getComputerStatusOutcome(value: unknown): string | null { - return isJsonRecord(value) ? getString(value.outcome) : null + return isRecordLike(value) ? getString(value.outcome) : null } export function normalizeVantaMonitoredComputer(resource: JsonRecord): VantaMonitoredComputer { - const operatingSystem = isJsonRecord(resource.operatingSystem) + const operatingSystem = isRecordLike(resource.operatingSystem) ? { type: getString(resource.operatingSystem.type), version: getString(resource.operatingSystem.version), @@ -769,7 +766,7 @@ export function normalizeVantaVulnerableAsset(resource: JsonRecord): VantaVulner } export function normalizeVantaVulnerability(resource: JsonRecord): VantaVulnerability { - const deactivateMetadata = isJsonRecord(resource.deactivateMetadata) + const deactivateMetadata = isRecordLike(resource.deactivateMetadata) ? { isVulnDeactivatedIndefinitely: getBoolean( resource.deactivateMetadata.isVulnDeactivatedIndefinitely diff --git a/apps/sim/triggers/emailbison/utils.ts b/apps/sim/triggers/emailbison/utils.ts index 12d9ebbe789..5e3384d03e5 100644 --- a/apps/sim/triggers/emailbison/utils.ts +++ b/apps/sim/triggers/emailbison/utils.ts @@ -1,3 +1,4 @@ +import { isRecordLike } from '@sim/utils/object' import type { SubBlockConfig } from '@/blocks/types' import type { TriggerOutput } from '@/triggers/types' @@ -499,12 +500,8 @@ export function isEmailBisonEventMatch(triggerId: string, body: Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value) -} diff --git a/apps/sim/triggers/salesforce/utils.ts b/apps/sim/triggers/salesforce/utils.ts index 233274bc702..99a1fc10230 100644 --- a/apps/sim/triggers/salesforce/utils.ts +++ b/apps/sim/triggers/salesforce/utils.ts @@ -1,6 +1,7 @@ import { extractSalesforceObjectTypeFromPayload } from '@/lib/webhooks/providers/salesforce' import type { SubBlockConfig } from '@/blocks/types' import type { TriggerOutput } from '@/triggers/types' +import { normalizeToken } from '@/triggers/utils/tokens' /** * Dropdown options for the Salesforce trigger type selector. @@ -14,13 +15,6 @@ export const salesforceTriggerOptions = [ { label: 'Generic Webhook (All Events)', id: 'salesforce_webhook' }, ] -function normalizeToken(s: string): string { - return s - .trim() - .toLowerCase() - .replace(/[\s-]+/g, '_') -} - const RECORD_CREATED = new Set([ 'record_created', 'created', diff --git a/apps/sim/triggers/servicenow/utils.ts b/apps/sim/triggers/servicenow/utils.ts index 7c85b659618..67abcc556ae 100644 --- a/apps/sim/triggers/servicenow/utils.ts +++ b/apps/sim/triggers/servicenow/utils.ts @@ -1,5 +1,6 @@ import type { SubBlockConfig } from '@/blocks/types' import type { TriggerOutput } from '@/triggers/types' +import { normalizeToken } from '@/triggers/utils/tokens' /** * Shared trigger dropdown options for all ServiceNow triggers @@ -130,13 +131,6 @@ export function buildChangeRequestOutputs(): Record { } } -function normalizeToken(s: string): string { - return s - .trim() - .toLowerCase() - .replace(/[\s-]+/g, '_') -} - /** * Extracts the table name from a ServiceNow webhook payload. * Business Rule scripts can send tableName in multiple formats. diff --git a/apps/sim/triggers/utils/tokens.ts b/apps/sim/triggers/utils/tokens.ts new file mode 100644 index 00000000000..0b3c44efbd0 --- /dev/null +++ b/apps/sim/triggers/utils/tokens.ts @@ -0,0 +1,11 @@ +/** + * Normalizes a free-form token from a webhook payload to a canonical form for + * matching: trims surrounding whitespace, lowercases, and collapses runs of + * whitespace or hyphens into single underscores. + */ +export function normalizeToken(value: string): string { + return value + .trim() + .toLowerCase() + .replace(/[\s-]+/g, '_') +} diff --git a/package.json b/package.json index 397991fa7d3..63e3be668c6 100644 --- a/package.json +++ b/package.json @@ -33,8 +33,6 @@ "mship-contracts:check": "bun run scripts/sync-mothership-stream-contract.ts --check", "mship-tools:generate": "bun run scripts/sync-tool-catalog.ts", "mship-tools:check": "bun run scripts/sync-tool-catalog.ts --check", - "trace-contracts:generate": "bun run scripts/sync-request-trace-contract.ts", - "trace-contracts:check": "bun run scripts/sync-request-trace-contract.ts --check", "trace-spans-contract:generate": "bun run scripts/sync-trace-spans-contract.ts", "trace-spans-contract:check": "bun run scripts/sync-trace-spans-contract.ts --check", "trace-attributes-contract:generate": "bun run scripts/sync-trace-attributes-contract.ts", diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index d40a413271e..eb89a3de69a 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -12,7 +12,13 @@ export { } from './formatting.js' export { noop, sleep } from './helpers.js' export { generateId, generateShortId, isValidUuid } from './id.js' -export { filterUndefined, omit } from './object.js' +export { + filterUndefined, + isPlainRecord, + isRecordLike, + omit, + sortObjectKeysDeep, +} from './object.js' export { generateRandomBytes, generateRandomHex, @@ -24,4 +30,4 @@ export { } from './random.js' export type { BackoffOptions } from './retry.js' export { backoffWithJitter, parseRetryAfter } from './retry.js' -export { truncate } from './string.js' +export { normalizeEmail, truncate } from './string.js' diff --git a/packages/utils/src/object.test.ts b/packages/utils/src/object.test.ts new file mode 100644 index 00000000000..29f21e2a6d6 --- /dev/null +++ b/packages/utils/src/object.test.ts @@ -0,0 +1,71 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { isPlainRecord, isRecordLike, sortObjectKeysDeep } from './object.js' + +class Sample { + value = 1 +} + +describe('isRecordLike', () => { + it('returns true for plain objects, Date, and class instances', () => { + expect(isRecordLike({})).toBe(true) + expect(isRecordLike(new Date())).toBe(true) + expect(isRecordLike(new Sample())).toBe(true) + }) + + it('returns false for arrays, null, and primitives', () => { + expect(isRecordLike([])).toBe(false) + expect(isRecordLike(null)).toBe(false) + expect(isRecordLike('not-a-record')).toBe(false) + expect(isRecordLike(42)).toBe(false) + }) +}) + +describe('isPlainRecord', () => { + it('returns true for plain objects', () => { + expect(isPlainRecord({})).toBe(true) + expect(isPlainRecord(Object.create(null))).toBe(true) + }) + + it('returns false for Date, class instances, arrays, and null', () => { + expect(isPlainRecord(new Date())).toBe(false) + expect(isPlainRecord(new Sample())).toBe(false) + expect(isPlainRecord([])).toBe(false) + expect(isPlainRecord(null)).toBe(false) + }) +}) + +describe('sortObjectKeysDeep', () => { + it('sorts keys deeply and recurses into array elements', () => { + const input = { + b: 1, + a: { d: 4, c: 3 }, + list: [{ z: 26, y: 25 }], + } + const sorted = sortObjectKeysDeep(input) + expect(JSON.stringify(sorted)).toBe( + JSON.stringify({ a: { c: 3, d: 4 }, b: 1, list: [{ y: 25, z: 26 }] }) + ) + }) + + it('returns primitives and null unchanged', () => { + expect(sortObjectKeysDeep(null)).toBe(null) + expect(sortObjectKeysDeep(42)).toBe(42) + expect(sortObjectKeysDeep('x')).toBe('x') + }) + + it('preserves array order while sorting element keys', () => { + const sorted = sortObjectKeysDeep([ + { b: 1, a: 2 }, + { d: 3, c: 4 }, + ]) + expect(JSON.stringify(sorted)).toBe( + JSON.stringify([ + { a: 2, b: 1 }, + { c: 4, d: 3 }, + ]) + ) + }) +}) diff --git a/packages/utils/src/object.ts b/packages/utils/src/object.ts index b16f0f5c956..92505aa34bd 100644 --- a/packages/utils/src/object.ts +++ b/packages/utils/src/object.ts @@ -22,3 +22,51 @@ export function omit(obj: T, keys: K[]): Om export function filterUndefined>(obj: T): Partial { return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as Partial } + +/** + * Returns true only for object-map values, excluding arrays and null. + */ +export function isPlainRecord(value: unknown): value is Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false + } + + const prototype = Object.getPrototypeOf(value) + return prototype === Object.prototype || prototype === null +} + +/** + * Returns true for any non-null, non-array object — the LOOSE record check. + * Unlike {@link isPlainRecord}, this does NOT inspect the prototype, so it also + * accepts class instances, Date, Map, etc. Use this when you only need to know a + * value is an indexable object (e.g. before spreading or Object.entries), and + * reach for isPlainRecord when you must exclude exotic objects. + */ +export function isRecordLike(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Recursively sorts the keys of every plain object reachable from {@link value}, + * preserving array order while recursing into array elements. Primitives and + * `null` are returned unchanged. Produces a structurally equivalent value with + * deterministic key ordering, suitable for stable comparison or serialization. + * + * @remarks Only string keys are sorted and retained; symbol keys are dropped, + * matching the stable-serialization callers this serves. + */ +export function sortObjectKeysDeep(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(sortObjectKeysDeep) + } + if (value !== null && typeof value === 'object') { + const obj = value as Record + return Object.keys(obj) + .sort() + .reduce((result: Record, key: string) => { + result[key] = sortObjectKeysDeep(obj[key]) + return result + }, {}) + } + return value +} diff --git a/packages/utils/src/string.test.ts b/packages/utils/src/string.test.ts index 55a3d2a1088..aca1811866f 100644 --- a/packages/utils/src/string.test.ts +++ b/packages/utils/src/string.test.ts @@ -2,7 +2,7 @@ * @vitest-environment node */ import { describe, expect, it } from 'vitest' -import { isVersionedType, stripVersionSuffix, truncate } from './string.js' +import { isVersionedType, normalizeEmail, stripVersionSuffix, truncate } from './string.js' describe('truncate', () => { it('appends the suffix when the string exceeds the slice length', () => { @@ -55,3 +55,13 @@ describe('isVersionedType', () => { expect(isVersionedType('x')).toBe(false) }) }) + +describe('normalizeEmail', () => { + it('trims surrounding whitespace and lowercases', () => { + expect(normalizeEmail(' USER@Example.COM ')).toBe('user@example.com') + }) + + it('leaves an already-normalized email unchanged', () => { + expect(normalizeEmail('user@example.com')).toBe('user@example.com') + }) +}) diff --git a/packages/utils/src/string.ts b/packages/utils/src/string.ts index ddeb6b023b1..1cbea71cfbb 100644 --- a/packages/utils/src/string.ts +++ b/packages/utils/src/string.ts @@ -37,3 +37,11 @@ export function stripVersionSuffix(value: string): string { export function isVersionedType(value: string): boolean { return /_v\d+$/.test(value) } + +/** + * Normalizes an email address for comparison and storage by trimming + * surrounding whitespace and lowercasing. + */ +export function normalizeEmail(email: string): string { + return email.trim().toLowerCase() +} diff --git a/scripts/check-api-validation-contracts.ts b/scripts/check-api-validation-contracts.ts index ed468073fe8..d82996804ca 100644 --- a/scripts/check-api-validation-contracts.ts +++ b/scripts/check-api-validation-contracts.ts @@ -9,8 +9,8 @@ const QUERY_HOOKS_DIR = path.join(ROOT, 'apps/sim/hooks/queries') const SELECTOR_HOOKS_DIR = path.join(ROOT, 'apps/sim/hooks/selectors') const BASELINE = { - totalRoutes: 826, - zodRoutes: 826, + totalRoutes: 828, + zodRoutes: 828, nonZodRoutes: 0, } as const diff --git a/scripts/generate-mship-contracts.ts b/scripts/generate-mship-contracts.ts index 40526b39fc7..7509216598a 100644 --- a/scripts/generate-mship-contracts.ts +++ b/scripts/generate-mship-contracts.ts @@ -19,7 +19,6 @@ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') const GENERATORS = [ 'scripts/sync-mothership-stream-contract.ts', 'scripts/sync-tool-catalog.ts', - 'scripts/sync-request-trace-contract.ts', 'scripts/sync-trace-spans-contract.ts', 'scripts/sync-trace-attributes-contract.ts', 'scripts/sync-trace-attribute-values-contract.ts', diff --git a/scripts/sync-request-trace-contract.ts b/scripts/sync-request-trace-contract.ts deleted file mode 100644 index 4813ed41527..00000000000 --- a/scripts/sync-request-trace-contract.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { mkdir, readFile, writeFile } from 'node:fs/promises' -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' -import { compile } from 'json-schema-to-typescript' -import { formatGeneratedSource } from './format-generated-source' - -const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) -const ROOT = resolve(SCRIPT_DIR, '..') -const DEFAULT_CONTRACT_PATH = resolve( - ROOT, - '../copilot/copilot/contracts/request-trace-v1.schema.json' -) -const OUTPUT_PATH = resolve(ROOT, 'apps/sim/lib/copilot/generated/request-trace-v1.ts') - -function generateRuntimeConstants(schema: Record): string { - const defs = (schema.$defs ?? schema.definitions ?? {}) as Record - const lines: string[] = [] - - for (const [name, def] of Object.entries(defs)) { - if (!def || typeof def !== 'object') continue - const defObj = def as Record - const enumValues = defObj.enum - if (!Array.isArray(enumValues) || enumValues.length === 0) continue - if (!enumValues.every((v) => typeof v === 'string')) continue - - const entries = (enumValues as string[]) - .map((v) => ` ${JSON.stringify(v)}: ${JSON.stringify(v)}`) - .join(',\n') - - lines.push(`export const ${name} = {\n${entries},\n} as const;\n`) - } - - return lines.join('\n') -} - -async function main() { - const checkOnly = process.argv.includes('--check') - const inputPathArg = process.argv.find((arg) => arg.startsWith('--input=')) - const inputPath = inputPathArg - ? resolve(ROOT, inputPathArg.slice('--input='.length)) - : DEFAULT_CONTRACT_PATH - - const raw = await readFile(inputPath, 'utf8') - const schema = JSON.parse(raw) - const types = await compile(schema, 'RequestTraceV1SimReport', { - bannerComment: '// AUTO-GENERATED FILE. DO NOT EDIT.\n//', - unreachableDefinitions: true, - additionalProperties: false, - }) - - const constants = generateRuntimeConstants(schema) - const rendered = formatGeneratedSource( - constants ? `${types}\n${constants}\n` : types, - OUTPUT_PATH, - ROOT - ) - - if (checkOnly) { - const existing = await readFile(OUTPUT_PATH, 'utf8').catch(() => null) - if (existing !== rendered) { - throw new Error( - `Generated request trace contract is stale. Run: bun run trace-contracts:generate` - ) - } - console.log('Request trace contract is up to date.') - return - } - - await mkdir(dirname(OUTPUT_PATH), { recursive: true }) - await writeFile(OUTPUT_PATH, rendered, 'utf8') - console.log(`Generated request trace types -> ${OUTPUT_PATH}`) -} - -main().catch((err) => { - console.error(err) - process.exit(1) -})