@theaiplatform/miniapp-sdk 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2655 @@
1
+ import * as __rspack_external__rsbuild_core_3f0eaefe from "@rsbuild/core";
2
+ import * as __rspack_external__module_federation_rsbuild_plugin_99e96cf9 from "@module-federation/rsbuild-plugin";
3
+ import * as __rspack_external_ajv_dist_2020_js_e85899db from "ajv/dist/2020.js";
4
+ import * as __rspack_external_node_crypto_2e7c4b46 from "node:crypto";
5
+ import * as __rspack_external_node_module_9de3fa2f from "node:module";
6
+ import * as __rspack_external_node_fs_promises_3b710708 from "node:fs/promises";
7
+ import * as __rspack_external_node_path_806ed179 from "node:path";
8
+ import * as __rspack_external_node_url_3991086a from "node:url";
9
+ import * as __rspack_external_saxes from "saxes";
10
+ import * as __rspack_external_node_util_ac04460e from "node:util";
11
+ var config_schema_namespaceObject = /*#__PURE__*/ JSON.parse('{"$defs":{"ActorKind":{"enum":["human","specialist"],"type":"string"},"AuthorizationBinding":{"additionalProperties":false,"properties":{"allOf":{"items":{"type":"string"},"type":"array"},"effects":{"items":{"$ref":"#/$defs/RuntimeEffect"},"type":"array"}},"type":"object"},"AutonomyLevel":{"enum":["listen","plan","do"],"type":"string"},"BrowserExtensionOptions":{"additionalProperties":false,"properties":{"manifest":{"type":"string"},"permissions":{"items":{"type":"string"},"type":"array"},"restartRequired":{"default":false,"type":"boolean"}},"required":["manifest"],"type":"object"},"ChatBlockOptions":{"additionalProperties":false,"properties":{"accessibilityLabel":{"type":"string"},"fallbackFormat":{"$ref":"#/$defs/FallbackFormat"},"payloadSchema":{"type":"string"},"protocol":{"$ref":"#/$defs/ChatBlockProtocol"}},"required":["protocol","payloadSchema","fallbackFormat","accessibilityLabel"],"type":"object"},"ChatBlockProtocol":{"enum":["tap-primitives-v1","tap-federated-view-v1","isolated-html-v1","mcp-app-2026-01-26"],"type":"string"},"CommandOptions":{"additionalProperties":false,"properties":{"inputSchema":{"type":["string","null"]},"label":{"type":"string"},"placements":{"items":{"type":"string"},"type":"array"}},"required":["label"],"type":"object"},"CompositionOptions":{"additionalProperties":false,"properties":{"childPackageIds":{"items":{"type":"string"},"type":"array"},"contributionIds":{"items":{"type":"string"},"type":"array"}},"type":"object"},"ConsentPolicy":{"enum":["none","once","channel","reusable","fresh-decision"],"type":"string"},"ContributionScope":{"enum":["user","workspace","channel","conversation","project","resource"],"type":"string"},"ContributionTarget":{"additionalProperties":false,"description":"A target-specific expose selected for a contribution.","properties":{"expose":{"type":"string"},"runtime":{"$ref":"#/$defs/ExecutionRuntime"}},"required":["expose","runtime"],"type":"object"},"DeclarativeOptions":{"additionalProperties":false,"properties":{"schema":{"type":"string"}},"required":["schema"],"type":"object"},"EventDelivery":{"enum":["ephemeral","durable"],"type":"string"},"ExecutableOptions":{"additionalProperties":false,"properties":{"effects":{"items":{"$ref":"#/$defs/RuntimeEffect"},"type":"array"},"inputSchema":{"type":["string","null"]},"outputSchema":{"type":["string","null"]},"timeoutMs":{"format":"uint64","minimum":0,"type":["integer","null"]}},"type":"object"},"ExecutionRuntime":{"enum":["webview","quickjs","worker","node","workflow-host","host-declarative"],"type":"string"},"FallbackFormat":{"enum":["text","markdown"],"type":"string"},"FederationExpose":{"additionalProperties":false,"description":"One exposed module in the locked Federation graph.","properties":{"integrity":{"type":"string"},"runtime":{"$ref":"#/$defs/ExecutionRuntime"}},"required":["integrity","runtime"],"type":"object"},"FederationLibraryType":{"enum":["module","script","commonjs-module"],"type":"string"},"FederationTarget":{"additionalProperties":false,"description":"One target-specific Module Federation remote container.","properties":{"assetLock":{"description":"Relative path to the build-generated content-addressed asset graph lock.","type":"string"},"assetLockIntegrity":{"description":"SHA-256 integrity of the canonical asset-lock bytes.","type":"string"},"exposes":{"additionalProperties":{"$ref":"#/$defs/FederationExpose"},"type":"object"},"libraryType":{"$ref":"#/$defs/FederationLibraryType"},"manifest":{"type":["string","null"]},"manifestIntegrity":{"type":["string","null"]},"remoteEntry":{"type":"string"},"remoteEntryIntegrity":{"type":"string"},"remoteName":{"type":"string"}},"required":["remoteName","remoteEntry","remoteEntryIntegrity","assetLock","assetLockIntegrity","libraryType","exposes"],"type":"object"},"InstancePolicy":{"enum":["per-mount","per-conversation","per-channel","per-workspace","singleton"],"type":"string"},"KnowledgeOptions":{"additionalProperties":false,"properties":{"materialization":{"type":["string","null"]},"schema":{"type":"string"}},"required":["schema"],"type":"object"},"LifecycleScope":{"enum":["installation","realm","contribution","mount"],"type":"string"},"McpOptions":{"additionalProperties":false,"properties":{"protocolVersion":{"type":"string"},"resourceUri":{"type":["string","null"]},"transport":{"type":["string","null"]}},"required":["protocolVersion"],"type":"object"},"MiniAppBundleManifest":{"additionalProperties":false,"description":"Manifest for a single TAP miniapp bundle.","properties":{"$schema":{"description":"Optional JSON Schema reference for editor support.","type":["string","null"]},"description":{"description":"Short human-readable summary of the miniapp.","minLength":1,"type":"string"},"entry":{"$ref":"#/$defs/MiniAppSource","description":"Entry file, package specifier, or URL for the miniapp config."},"icon":{"description":"Lucide-compatible icon name shown by host UI surfaces.","minLength":1,"type":["string","null"]},"name":{"description":"Display name for the miniapp.","minLength":1,"type":"string"},"runtime":{"$ref":"#/$defs/TapRuntime","description":"TAP miniapp runtime version."},"version":{"description":"Miniapp version.","minLength":1,"type":"string"}},"required":["name","description","version","runtime","entry"],"title":"Tap Miniapp Bundle Manifest","type":"object"},"MiniAppReferencesManifest":{"additionalProperties":false,"description":"Manifest that references built TAP miniapp manifests.","properties":{"$schema":{"description":"Optional JSON Schema reference for editor support.","type":["string","null"]},"references":{"description":"References to built TAP miniapp manifests.\\n\\nString shorthand remains available for local and mutable development sources. An\\nimmutable remote collection uses the object form (`{ \\"url\\": ..., \\"hash\\": ... }`) so\\nevery child manifest carries its own SHA-256 integrity boundary.","items":{"$ref":"#/$defs/MiniAppSource"},"minItems":1,"type":"array"}},"required":["references"],"title":"Tap Miniapp References Manifest","type":"object"},"MiniAppSource":{"description":"Absolute URL or local path. Bundle entry paths are resolved relative to the manifest that declares them.","oneOf":[{"additionalProperties":false,"properties":{"Path":{"additionalProperties":false,"properties":{"path":{"minLength":1,"type":"string"}},"required":["path"],"type":"object"}},"required":["Path"],"type":"object"},{"additionalProperties":false,"properties":{"Url":{"additionalProperties":false,"properties":{"hash":{"description":"Expected SHA-256 hex digest for the remote source bytes.","type":["string","null"]},"url":{"format":"uri","type":"string"}},"required":["url"],"type":"object"}},"required":["Url"],"type":"object"},{"description":"Absolute URL or local path. Bundle entry paths are resolved relative to the manifest that declares them.","minLength":1,"type":"string"},{"additionalProperties":false,"properties":{"hash":{"description":"Expected SHA-256 hex digest for the remote source bytes.","type":["string","null"]},"url":{"format":"uri","type":"string"}},"required":["url"],"type":"object"}]},"PackageCompatibility":{"additionalProperties":false,"description":"Host and SDK compatibility checked before remote loading.","properties":{"tapHost":{"type":"string"},"tapSdk":{"type":"string"}},"required":["tapSdk","tapHost"],"type":"object"},"PackageContribution":{"description":"Strict contribution union covering the initial TAP extension catalog.","oneOf":[{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"ui.surface","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/UiSurfaceOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"ui.renderer","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/RendererOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"chat.block","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ChatBlockOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"action.command","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/CommandOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"prompt","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"skill","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"tool","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"specialist","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"task.type","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/TaskOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"task.attribute","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/TaskOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"task.view","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/TaskOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"task.action","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/TaskOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"task.template","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/TaskOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"workflow","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"workflow.node","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"automation.trigger","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.server","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.tool","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.prompt","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.resource","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.resource-template","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"mcp.app","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/McpOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"miniapp","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/CompositionOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"integration.connector","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/CompositionOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"browser.extension","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/BrowserExtensionOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"knowledge.plot-template","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/KnowledgeOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"knowledge.source-provider","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/KnowledgeOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"knowledge.enricher","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/KnowledgeOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"knowledge.retriever","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/KnowledgeOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"provider.adapter","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/ExecutableOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"template","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/DeclarativeOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"},{"additionalProperties":false,"description":"Fields shared by every package contribution.","properties":{"apiVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"authorization":{"$ref":"#/$defs/AuthorizationBinding","default":{}},"id":{"type":"string"},"kind":{"const":"permission.catalog","type":"string"},"lifecycleScope":{"$ref":"#/$defs/LifecycleScope","default":"mount"},"options":{"$ref":"#/$defs/PermissionCatalogOptions"},"publishes":{"items":{"type":"string"},"type":"array"},"subscribes":{"items":{"type":"string"},"type":"array"},"targets":{"additionalProperties":false,"properties":{"desktop":{"$ref":"#/$defs/ContributionTarget"},"mobile":{"$ref":"#/$defs/ContributionTarget"},"node":{"$ref":"#/$defs/ContributionTarget"},"quickjs":{"$ref":"#/$defs/ContributionTarget"},"worker":{"$ref":"#/$defs/ContributionTarget"},"workflow-host":{"$ref":"#/$defs/ContributionTarget"}},"type":"object"}},"required":["kind","id","apiVersion","options"],"type":"object"}]},"PackageDependency":{"additionalProperties":false,"properties":{"alias":{"type":"string"},"optional":{"default":false,"type":"boolean"},"packageId":{"type":"string"},"version":{"type":"string"}},"required":["alias","packageId","version"],"type":"object"},"PackageEventCatalog":{"additionalProperties":false,"description":"Package-defined published and consumed events.","properties":{"publishes":{"items":{"$ref":"#/$defs/PublishedEvent"},"type":"array"},"subscribes":{"items":{"$ref":"#/$defs/SubscribedEvent"},"type":"array"}},"type":"object"},"PackageIdentity":{"additionalProperties":false,"description":"Immutable identity carried by a package descriptor.","properties":{"namespace":{"type":"string"},"organizationId":{"type":["string","null"]},"packageId":{"type":"string"},"parentPackageId":{"type":["string","null"]},"publisherId":{"type":"string"},"slug":{"type":"string"}},"required":["packageId","publisherId","namespace","slug"],"type":"object"},"PackageLifecyclePolicy":{"additionalProperties":false,"properties":{"checkpoint":{"$ref":"#/$defs/PersistencePolicy","default":"none"},"checkpointSchema":{"type":["string","null"]},"lifecycleExpose":{"type":["string","null"]}},"type":"object"},"PackagePermissionAction":{"additionalProperties":false,"properties":{"autonomyCeiling":{"$ref":"#/$defs/AutonomyLevel"},"consent":{"$ref":"#/$defs/ConsentPolicy"},"delegatedActors":{"items":{"$ref":"#/$defs/ActorKind"},"type":"array"},"directActors":{"items":{"$ref":"#/$defs/ActorKind"},"type":"array"},"id":{"type":"string"},"resource":{"type":"string"},"risk":{"$ref":"#/$defs/PermissionRisk"},"scopes":{"items":{"$ref":"#/$defs/ContributionScope"},"type":"array"}},"required":["id","resource","scopes","directActors","delegatedActors","autonomyCeiling","consent","risk"],"type":"object"},"PackagePermissionLevel":{"additionalProperties":false,"properties":{"actions":{"items":{"type":"string"},"type":"array"},"assignableTo":{"items":{"$ref":"#/$defs/ActorKind"},"type":"array"},"id":{"type":"string"},"includes":{"items":{"type":"string"},"type":"array"}},"required":["id","assignableTo"],"type":"object"},"PackagePresentation":{"additionalProperties":false,"description":"Package presentation metadata and content-addressed visual assets.","properties":{"assets":{"items":{"$ref":"#/$defs/PresentationAsset"},"type":"array"},"description":{"type":"string"},"iconAssets":{"default":[],"description":"Ordered parent-package icon candidates. Empty inherits every app-icon\\nfor backwards compatibility; collection packages should select their\\nparent artwork explicitly so child surfaces cannot replace it.","items":{"type":"string"},"type":"array"},"name":{"type":"string"}},"required":["name","description"],"type":"object"},"PermissionCatalogOptions":{"additionalProperties":false,"description":"A signed package-local permission catalog. These are definitions, never grants.","properties":{"actions":{"items":{"$ref":"#/$defs/PackagePermissionAction"},"type":"array"},"levels":{"items":{"$ref":"#/$defs/PackagePermissionLevel"},"type":"array"},"roleRecommendations":{"items":{"$ref":"#/$defs/RoleRecommendation"},"type":"array"}},"type":"object"},"PermissionRisk":{"enum":["read","write","consequential","financial"],"type":"string"},"PersistencePolicy":{"enum":["none","checkpoint","retained"],"type":"string"},"PresentationAsset":{"additionalProperties":false,"description":"A PNG or SVG package, publisher, or organization presentation asset.","properties":{"integrity":{"type":"string"},"mediaType":{"$ref":"#/$defs/PresentationAssetMediaType"},"path":{"type":"string"},"role":{"$ref":"#/$defs/PresentationAssetRole"},"sizes":{"items":{"type":"string"},"type":"array"},"theme":{"$ref":"#/$defs/PresentationAssetTheme","default":"any"}},"required":["role","mediaType","path","integrity"],"type":"object"},"PresentationAssetMediaType":{"enum":["image/png","image/svg+xml"],"type":"string"},"PresentationAssetRole":{"enum":["app-icon","publisher-icon","organization-icon","marketplace-card","wordmark"],"type":"string"},"PresentationAssetTheme":{"enum":["any","light","dark"],"type":"string"},"PublishedEvent":{"additionalProperties":false,"properties":{"delivery":{"$ref":"#/$defs/EventDelivery"},"name":{"type":"string"},"schema":{"type":"string"},"schemaVersion":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"visibility":{"$ref":"#/$defs/ContributionScope"}},"required":["name","schema","schemaVersion","visibility","delivery"],"type":"object"},"ReleaseIdentity":{"additionalProperties":false,"description":"Immutable release identity carried by a package descriptor.","properties":{"contentDigest":{"type":"string"},"releaseId":{"type":"string"},"version":{"type":"string"}},"required":["releaseId","version","contentDigest"],"type":"object"},"RendererOptions":{"additionalProperties":false,"properties":{"payloadSchema":{"type":["string","null"]},"protocol":{"type":"string"}},"required":["protocol"],"type":"object"},"RoleRecommendation":{"additionalProperties":false,"properties":{"actor":{"$ref":"#/$defs/ActorKind"},"level":{"type":"string"},"workspaceRole":{"type":"string"}},"required":["actor","workspaceRole","level"],"type":"object"},"RuntimeEffect":{"additionalProperties":false,"properties":{"kind":{"type":"string"},"resources":{"items":{"type":"string"},"type":"array"}},"required":["kind"],"type":"object"},"SubscribedEvent":{"additionalProperties":false,"properties":{"dependency":{"type":["string","null"]},"event":{"type":"string"},"versions":{"items":{"format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"type":"array"}},"required":["event","versions"],"type":"object"},"TapPackageDescriptorV1":{"additionalProperties":false,"description":"Versioned package descriptor inspected before a remote entry is evaluated.","properties":{"$schema":{"description":"Optional JSON Schema reference for editor validation and completion.","type":["string","null"]},"compatibility":{"$ref":"#/$defs/PackageCompatibility","description":"Host and SDK compatibility requirements."},"contributions":{"description":"Statically declared contributions. Code cannot add undeclared contributions at runtime.","items":{"$ref":"#/$defs/PackageContribution"},"type":"array"},"dependencies":{"description":"Package dependencies and optional collection children.","items":{"$ref":"#/$defs/PackageDependency"},"type":"array"},"descriptorVersion":{"description":"Descriptor schema version. Version 1 is the first Federation package contract.","format":"uint16","maximum":1,"minimum":1,"type":"integer"},"events":{"$ref":"#/$defs/PackageEventCatalog","default":{},"description":"Statically declared package event catalog."},"lifecycle":{"$ref":"#/$defs/PackageLifecyclePolicy","default":{"checkpoint":"none"},"description":"Package lifecycle and checkpoint policy."},"package":{"$ref":"#/$defs/PackageIdentity","description":"Immutable package, publisher, namespace, and collection identity."},"presentation":{"$ref":"#/$defs/PackagePresentation","description":"Marketplace and host presentation metadata."},"release":{"$ref":"#/$defs/ReleaseIdentity","description":"Immutable release identity and content digest."},"targets":{"additionalProperties":false,"description":"Target-specific Module Federation containers.","properties":{"desktop":{"$ref":"#/$defs/FederationTarget"},"mobile":{"$ref":"#/$defs/FederationTarget"},"node":{"$ref":"#/$defs/FederationTarget"},"quickjs":{"$ref":"#/$defs/FederationTarget"},"worker":{"$ref":"#/$defs/FederationTarget"},"workflow-host":{"$ref":"#/$defs/FederationTarget"}},"type":"object"}},"required":["descriptorVersion","package","release","presentation","compatibility","targets","contributions"],"type":"object"},"TapRuntime":{"description":"Supported TAP miniapp runtime versions.","enum":[0,1],"type":"integer"},"TaskOptions":{"additionalProperties":false,"properties":{"canonicalStatuses":{"additionalProperties":{"type":"string"},"type":"object"},"migrationExpose":{"type":["string","null"]},"schema":{"type":"string"}},"required":["schema"],"type":"object"},"UiPlacement":{"enum":["workspace-left","channel-apps","chat-right","route","settings","dialog","standalone-window"],"type":"string"},"UiSurfaceOptions":{"additionalProperties":false,"properties":{"description":{"type":["string","null"]},"displayName":{"description":"Surface-specific label. Packages with multiple mini apps must not rely\\non the package-wide Marketplace name for every navigation entry.","type":["string","null"]},"iconAssets":{"default":[],"description":"Ordered package presentation assets eligible for this contribution.\\nEmpty inherits the package-level `presentation.iconAssets` selection.","items":{"type":"string"},"type":"array"},"instancePolicy":{"$ref":"#/$defs/InstancePolicy","default":"per-mount"},"persistence":{"$ref":"#/$defs/PersistencePolicy","default":"none"},"placement":{"$ref":"#/$defs/UiPlacement"},"scope":{"$ref":"#/$defs/ContributionScope"}},"required":["placement","scope"],"type":"object"}},"$id":"https://tap.local/schemas/manifest.tap.schema.json","$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/TapPackageDescriptorV1","description":"A static TAP package descriptor, validated before its remote code is evaluated."},{"$ref":"#/$defs/MiniAppBundleManifest","description":"A single miniapp bundle with its runtime entrypoint."},{"$ref":"#/$defs/MiniAppReferencesManifest","description":"A collection manifest that points at built miniapp manifests."}],"description":"Manifest for a Tap miniapp bundle or a collection of built miniapps.","title":"Tap Miniapp Manifest"}');
12
+ const MAX_SVG_DEPTH = 64;
13
+ const MAX_SVG_ELEMENTS = 10000;
14
+ const MAX_SVG_ATTRIBUTES_PER_ELEMENT = 64;
15
+ const MAX_SVG_ATTRIBUTES = 50000;
16
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
17
+ const XLINK_NAMESPACE = 'http://www.w3.org/1999/xlink';
18
+ const FORBIDDEN_SVG_ELEMENTS = new Set([
19
+ 'animation',
20
+ 'audio',
21
+ 'base',
22
+ 'discard',
23
+ 'embed',
24
+ 'foreignobject',
25
+ 'handler',
26
+ 'iframe',
27
+ 'image',
28
+ 'object',
29
+ "script",
30
+ 'set',
31
+ 'style',
32
+ 'video'
33
+ ]);
34
+ const FORBIDDEN_SVG_CSS_CONTENT = [
35
+ '@import',
36
+ '@keyframes',
37
+ "javascript:",
38
+ '/*',
39
+ 'animation:',
40
+ 'animation-name',
41
+ 'transition:',
42
+ 'behavior:',
43
+ '-moz-binding'
44
+ ];
45
+ const FORBIDDEN_SVG_CSS_FUNCTIONS = [
46
+ 'cross-fade(',
47
+ 'element(',
48
+ 'image(',
49
+ 'image-set(',
50
+ 'paint(',
51
+ 'src('
52
+ ];
53
+ class SvgPresentationAssetValidationError extends Error {
54
+ }
55
+ const invalidSvg = (assetPath, reason)=>new SvgPresentationAssetValidationError(`TAP presentation asset ${assetPath} ${reason}`);
56
+ const activeSvg = (assetPath, reason)=>invalidSvg(assetPath, `contains active or externally loaded SVG content: ${reason}.`);
57
+ const svgQualifiedName = (assetPath, name)=>{
58
+ const validSegment = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
59
+ const segments = name.split(':');
60
+ if (segments.length > 2 || segments.some((segment)=>!validSegment.test(segment))) throw invalidSvg(assetPath, 'has an unsupported XML name.');
61
+ return name.toLowerCase();
62
+ };
63
+ const containsEntityOutsideLiteralSections = (source)=>{
64
+ let index = 0;
65
+ while(index < source.length){
66
+ if (source.startsWith('<!--', index)) {
67
+ const end = source.indexOf('-->', index + 4);
68
+ if (-1 === end) return false;
69
+ index = end + 3;
70
+ continue;
71
+ }
72
+ if (source.startsWith('<![CDATA[', index)) {
73
+ const end = source.indexOf(']]>', index + 9);
74
+ if (-1 === end) return false;
75
+ index = end + 3;
76
+ continue;
77
+ }
78
+ if ('&' === source[index]) return true;
79
+ index += 1;
80
+ }
81
+ return false;
82
+ };
83
+ const validateSvgCssContent = (assetPath, value)=>{
84
+ const lowercase = value.toLowerCase();
85
+ const compact = lowercase.replace(/\s+/gu, '');
86
+ if (FORBIDDEN_SVG_CSS_CONTENT.some((forbidden)=>lowercase.includes(forbidden) || compact.includes(forbidden)) || FORBIDDEN_SVG_CSS_FUNCTIONS.some((forbidden)=>compact.includes(forbidden)) || /(?:https?:|data:|file:|blob:|filesystem:|\/\/)/u.test(compact)) throw activeSvg(assetPath, 'active or external CSS');
87
+ let offset = 0;
88
+ while(offset < lowercase.length){
89
+ const urlIndex = lowercase.indexOf('url', offset);
90
+ if (-1 === urlIndex) return;
91
+ const afterName = lowercase.slice(urlIndex + 3);
92
+ const leadingWhitespace = afterName.length - afterName.trimStart().length;
93
+ const openIndex = urlIndex + 3 + leadingWhitespace;
94
+ if ('(' !== lowercase[openIndex]) {
95
+ offset = urlIndex + 3;
96
+ continue;
97
+ }
98
+ const closeIndex = lowercase.indexOf(')', openIndex + 1);
99
+ if (-1 === closeIndex) throw activeSvg(assetPath, 'an unterminated CSS url()');
100
+ let target = lowercase.slice(openIndex + 1, closeIndex).trim();
101
+ if (target.length >= 2 && (target.startsWith("'") && target.endsWith("'") || target.startsWith('"') && target.endsWith('"'))) target = target.slice(1, -1);
102
+ if (target.length < 2 || !target.startsWith('#')) throw activeSvg(assetPath, 'an external CSS url()');
103
+ offset = closeIndex + 1;
104
+ }
105
+ };
106
+ const validateSvgCharacterData = (assetPath, value, insideRoot)=>{
107
+ if (!insideRoot && !/^\s*$/.test(value)) throw invalidSvg(assetPath, 'contains text outside the SVG root.');
108
+ };
109
+ const validateSvgElement = (assetPath, element, counters, isRoot)=>{
110
+ counters.elements += 1;
111
+ if (counters.elements > MAX_SVG_ELEMENTS) throw invalidSvg(assetPath, 'exceeds the XML element limit.');
112
+ const qualifiedName = svgQualifiedName(assetPath, element.name);
113
+ if (qualifiedName.includes(':')) throw activeSvg(assetPath, `foreign namespace element '${qualifiedName}'`);
114
+ const localName = qualifiedName;
115
+ if (FORBIDDEN_SVG_ELEMENTS.has(localName) || localName.startsWith('animate')) throw activeSvg(assetPath, `forbidden element '${localName}'`);
116
+ const attributes = Object.entries(element.attributes);
117
+ counters.attributes += attributes.length;
118
+ if (attributes.length > MAX_SVG_ATTRIBUTES_PER_ELEMENT || counters.attributes > MAX_SVG_ATTRIBUTES) throw invalidSvg(assetPath, 'exceeds the XML attribute limit.');
119
+ let hasSvgNamespace = false;
120
+ for (const [attributeName, value] of attributes){
121
+ const fullName = svgQualifiedName(assetPath, attributeName);
122
+ if ('xmlns' === attributeName) {
123
+ if (!isRoot || value !== SVG_NAMESPACE) throw activeSvg(assetPath, 'a foreign or relocated default namespace');
124
+ hasSvgNamespace = true;
125
+ continue;
126
+ }
127
+ if (attributeName.startsWith('xmlns:')) {
128
+ if (!isRoot || 'xmlns:xlink' !== attributeName || value !== XLINK_NAMESPACE) throw activeSvg(assetPath, `foreign namespace '${attributeName}'`);
129
+ continue;
130
+ }
131
+ const localAttributeName = fullName.split(':').at(-1) ?? '';
132
+ if (localAttributeName.startsWith('on') || 'style' === localAttributeName || 'xml:base' === fullName) throw activeSvg(assetPath, `forbidden attribute '${fullName}'`);
133
+ if (value.includes('&') || value.includes('\\')) throw activeSvg(assetPath, 'an encoded entity or CSS escape');
134
+ if ([
135
+ 'href',
136
+ 'src',
137
+ 'poster'
138
+ ].includes(localAttributeName)) {
139
+ const reference = value.trim();
140
+ if (reference.length < 2 || !reference.startsWith('#')) throw activeSvg(assetPath, `external reference in '${fullName}'`);
141
+ }
142
+ validateSvgCssContent(assetPath, value);
143
+ }
144
+ if (isRoot && !hasSvgNamespace) throw invalidSvg(assetPath, `must declare xmlns="${SVG_NAMESPACE}".`);
145
+ };
146
+ const validateSvgPresentationAsset = (assetPath, contents)=>{
147
+ let source;
148
+ try {
149
+ source = new __rspack_external_node_util_ac04460e.TextDecoder('utf-8', {
150
+ fatal: true
151
+ }).decode(contents);
152
+ } catch {
153
+ throw invalidSvg(assetPath, 'declares image/svg+xml but is not valid UTF-8.');
154
+ }
155
+ if (containsEntityOutsideLiteralSections(source)) throw activeSvg(assetPath, 'an entity reference');
156
+ let depth = 0;
157
+ let seenRoot = false;
158
+ const counters = {
159
+ elements: 0,
160
+ attributes: 0
161
+ };
162
+ const parser = new __rspack_external_saxes.SaxesParser({
163
+ xmlns: false
164
+ });
165
+ parser.on('xmldecl', (declaration)=>{
166
+ if (![
167
+ '1.0',
168
+ '1.1'
169
+ ].includes(declaration.version ?? '')) throw invalidSvg(assetPath, 'uses an unsupported XML version.');
170
+ const encoding = declaration.encoding?.toLowerCase();
171
+ if (void 0 !== encoding && ![
172
+ 'utf-8',
173
+ 'utf8'
174
+ ].includes(encoding)) throw invalidSvg(assetPath, 'must declare UTF-8 encoding.');
175
+ });
176
+ parser.on('processinginstruction', ()=>{
177
+ throw activeSvg(assetPath, 'a processing instruction');
178
+ });
179
+ parser.on('doctype', ()=>{
180
+ throw activeSvg(assetPath, 'a document type declaration');
181
+ });
182
+ parser.on('opentag', (element)=>{
183
+ const isRoot = 0 === depth;
184
+ if (isRoot) {
185
+ if (seenRoot) throw invalidSvg(assetPath, 'contains multiple roots.');
186
+ if ('svg' !== element.name) throw invalidSvg(assetPath, 'does not contain an SVG root.');
187
+ seenRoot = true;
188
+ }
189
+ validateSvgElement(assetPath, element, counters, isRoot);
190
+ if (!element.isSelfClosing) {
191
+ depth += 1;
192
+ if (depth > MAX_SVG_DEPTH) throw invalidSvg(assetPath, 'exceeds the XML depth limit.');
193
+ }
194
+ });
195
+ parser.on('closetag', (element)=>{
196
+ if (!element.isSelfClosing) depth -= 1;
197
+ });
198
+ parser.on('text', (text)=>{
199
+ validateSvgCharacterData(assetPath, text, depth > 0);
200
+ });
201
+ parser.on('cdata', (text)=>{
202
+ if (0 === depth) throw invalidSvg(assetPath, 'contains CDATA outside the SVG root.');
203
+ validateSvgCharacterData(assetPath, text, true);
204
+ });
205
+ try {
206
+ parser.write(source).close();
207
+ } catch (error) {
208
+ if (error instanceof SvgPresentationAssetValidationError) throw error;
209
+ throw invalidSvg(assetPath, 'declares image/svg+xml but is malformed XML.');
210
+ }
211
+ if (!seenRoot || 0 !== depth) throw invalidSvg(assetPath, 'does not contain one complete SVG root.');
212
+ };
213
+ const PLUGIN_NAME = 'plugin-tap-rspack';
214
+ const MINIAPP_DOCUMENT_ID_GLOBAL_KEY = 'zephyrcloudio.miniapp.document-id';
215
+ const MINIAPP_BROWSER_DEFINES = {
216
+ 'process.env.NODE_ENV': JSON.stringify('production')
217
+ };
218
+ const MINIAPP_BROWSER_CONDITION_NAMES = [
219
+ 'browser',
220
+ 'import',
221
+ 'module',
222
+ 'default'
223
+ ];
224
+ const MINIAPP_CLIENT_ALIASES = {
225
+ '@tanstack/router-core/isServer': '@tanstack/router-core/dist/esm/isServer/client.js'
226
+ };
227
+ const REACT_GLOBAL_ENTRY = 'data:text/javascript,import{Fragment as __tapReactFragment,createElement as __tapReactCreateElement}from"react";globalThis.React??={Fragment:__tapReactFragment,createElement:__tapReactCreateElement};';
228
+ const DEFAULT_MANIFEST_PATH = './manifest.tap.json';
229
+ const DEFAULT_ENTRY_NAME = 'config.tap';
230
+ const DEFAULT_PACKAGE_TARGET = 'desktop';
231
+ const PACKAGE_TARGETS_PATH = 'targets';
232
+ const PACKAGE_LOCK_FILE_NAME = 'tap.package.lock.json';
233
+ const FEDERATION_MANIFEST_FILE_NAME = 'mf-manifest.json';
234
+ const FEDERATION_STATS_FILE_NAME = 'mf-stats.json';
235
+ const FEDERATION_REMOTE_ENTRY_FILE_NAME = 'remoteEntry.mjs';
236
+ const TAP_FEDERATED_SURFACE_HTML_PATH = 'tap.surface.html';
237
+ const TAP_FEDERATED_SURFACE_RUNTIME_PATH = 'tap.surface.mjs';
238
+ const MAX_PACKAGE_ASSETS = 10000;
239
+ const MAX_PACKAGE_ASSET_BYTES = 33554432;
240
+ const MAX_PACKAGE_BYTES = 104857600;
241
+ const MAX_PACKAGE_ICON_BYTES = 2097152;
242
+ const MAX_PACKAGE_ICON_DIMENSION = 4096;
243
+ const MAX_PACKAGE_ICON_PIXELS = 16777216;
244
+ const MAX_PACKAGE_PRESENTATION_ASSETS = 64;
245
+ const MAX_PACKAGE_ICON_VARIANTS = 16;
246
+ const LOCAL_FILE_URL_PATTERN = /file:\/\/(?:\/|[A-Za-z0-9._-]+\/)/iu;
247
+ const TAP_PACKAGE_TARGETS = [
248
+ 'desktop',
249
+ 'mobile',
250
+ 'quickjs',
251
+ 'worker',
252
+ 'node',
253
+ 'workflow-host'
254
+ ];
255
+ const EMPTY_ENTRY = "data:text/javascript,export {};";
256
+ const QUICKJS_FORBIDDEN_GLOBALS = [
257
+ 'window',
258
+ 'document',
259
+ 'navigator',
260
+ 'location',
261
+ 'fetch',
262
+ 'XMLHttpRequest',
263
+ 'WebSocket',
264
+ 'EventSource',
265
+ 'importScripts',
266
+ 'self',
267
+ 'process',
268
+ 'require',
269
+ '__dirname',
270
+ '__filename',
271
+ 'Buffer',
272
+ 'Deno',
273
+ 'Bun'
274
+ ];
275
+ const HTML_LOADER_PATH = __rspack_external_node_path_806ed179["default"].join(__rspack_external_node_path_806ed179["default"].dirname((0, __rspack_external_node_url_3991086a.fileURLToPath)(import.meta.url)), 'html-loader.cjs');
276
+ const CSS_ENTRY_LOADER_PATH = __rspack_external_node_path_806ed179["default"].join(__rspack_external_node_path_806ed179["default"].dirname((0, __rspack_external_node_url_3991086a.fileURLToPath)(import.meta.url)), 'css-entry-loader.cjs');
277
+ const HTML_IMPORT_PATTERN = /import\s+(?:[^'"]+\s+from\s+)?["']([^"']+\.html(?:\?[^"']*)?)["'];?/g;
278
+ const SCRIPT_SRC_PATTERN = /<script\b([^>]*?)\bsrc=(["'])([^"']+)\2([^>]*)>/gi;
279
+ const STYLESHEET_HREF_PATTERN = /<link\b(?=[^>]*?\brel=(["'])stylesheet\1)([^>]*?)\bhref=(["'])([^"']+)\3([^>]*)>/gi;
280
+ const HTML_SCRIPT_TOKEN_PATTERN = /__TAP_HTML_SCRIPT:([a-zA-Z0-9_-]+)__/g;
281
+ const HTML_STYLESHEET_TOKEN_PATTERN = /__TAP_HTML_STYLESHEET:([a-zA-Z0-9_-]+)__/g;
282
+ const LOCAL_JS_NAMED_IMPORT_PATTERN = /import\s*\{([^}]+)\}\s*from\s*["']\.\/([^"']+\.js)["'];?/g;
283
+ const LOCAL_JS_SIDE_EFFECT_IMPORT_PATTERN = /import\s*["']\.\/([^"']+\.js)["'];?/g;
284
+ const RUNTIME_IMPORT_PATTERN = /import\s+\{\s*__webpack_require__\s*\}\s+from\s+(["'])\.\/[^"']+\.js\1;?\s*/g;
285
+ const FULL_RUNTIME_CHUNK_PATTERN = /(?:function __webpack_require__\(moduleId\)|var __webpack_require__ = function __webpack_require__\(moduleId\))/;
286
+ const FULL_RUNTIME_PREFIX_PATTERN = /var __webpack_modules__ = \{\};\s*var __webpack_module_cache__ = \{\};\s*(?:function __webpack_require__\(moduleId\)|var __webpack_require__ = function __webpack_require__\(moduleId\))\s*\{[\s\S]*?\(\(\)=>\{\s*__webpack_require__\.j = ["'][^"']+["'];\s*\}\)\(\);\s*/s;
287
+ let schemaValidator;
288
+ const packageTargetDirectory = (target)=>__rspack_external_node_path_806ed179["default"].posix.join(PACKAGE_TARGETS_PATH, target);
289
+ const packageTargetAssetPath = (target, fileName)=>__rspack_external_node_path_806ed179["default"].posix.join(packageTargetDirectory(target), fileName);
290
+ const packageTargetOutputPaths = (target)=>({
291
+ directory: packageTargetDirectory(target),
292
+ lock: packageTargetAssetPath(target, PACKAGE_LOCK_FILE_NAME),
293
+ manifest: packageTargetAssetPath(target, FEDERATION_MANIFEST_FILE_NAME),
294
+ remoteEntry: packageTargetAssetPath(target, FEDERATION_REMOTE_ENTRY_FILE_NAME),
295
+ stats: packageTargetAssetPath(target, FEDERATION_STATS_FILE_NAME)
296
+ });
297
+ const normalizeFederationOptions = (target, federation)=>{
298
+ const targetPaths = packageTargetOutputPaths(target);
299
+ const configuredManifest = isRecord(federation.manifest) ? {
300
+ ...federation.manifest
301
+ } : {};
302
+ delete configuredManifest.filePath;
303
+ delete configuredManifest.fileName;
304
+ return {
305
+ ...federation,
306
+ filename: targetPaths.remoteEntry,
307
+ manifest: {
308
+ ...configuredManifest,
309
+ filePath: targetPaths.directory
310
+ },
311
+ library: {
312
+ type: 'module'
313
+ },
314
+ dts: false
315
+ };
316
+ };
317
+ const TAP_FEDERATED_SURFACE_HTML = `<!doctype html>
318
+ <html lang="en">
319
+ <head>
320
+ <meta charset="utf-8">
321
+ <meta name="viewport" content="width=device-width,initial-scale=1">
322
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; form-action 'none'">
323
+ <title>TAP mini app</title>
324
+ <style>html,body,#tap-root{height:100%;width:100%;margin:0}body{overflow:hidden;background:transparent}#tap-error{box-sizing:border-box;display:none;min-height:100%;padding:24px;font:14px/1.5 system-ui,sans-serif;color:#b42318;background:#fff}</style>
325
+ </head>
326
+ <body>
327
+ <div id="tap-root" hidden></div>
328
+ <div id="tap-error" role="alert">This mini app could not be loaded.</div>
329
+ <script type="module" src="./${TAP_FEDERATED_SURFACE_RUNTIME_PATH}"></script>
330
+ </body>
331
+ </html>
332
+ `;
333
+ const TAP_FEDERATED_DOCUMENT_ID_GLOBAL_KEY = JSON.stringify(MINIAPP_DOCUMENT_ID_GLOBAL_KEY);
334
+ const TAP_FEDERATED_SURFACE_RUNTIME = String.raw`const params = new URLSearchParams(location.search);
335
+ const required = (name) => {
336
+ const value = params.get(name)?.trim();
337
+ if (!value) throw new Error('Missing federated surface parameter: ' + name);
338
+ return value;
339
+ };
340
+ const requiredEither = (name, fallbackName) => {
341
+ const value = params.get(name)?.trim() || params.get(fallbackName)?.trim();
342
+ if (!value) throw new Error('Missing federated surface parameter: ' + name);
343
+ return value;
344
+ };
345
+ const safeId = (name, fallbackName) => {
346
+ const value = fallbackName ? requiredEither(name, fallbackName) : required(name);
347
+ if (value.length > 512 || /[\u0000-\u001f\u007f]/u.test(value)) {
348
+ throw new Error('Invalid federated surface identity: ' + name);
349
+ }
350
+ return value;
351
+ };
352
+ const optionalSafeId = (name) => {
353
+ const value = params.get(name)?.trim();
354
+ if (!value) return undefined;
355
+ if (value.length > 512 || /[\u0000-\u001f\u007f]/u.test(value)) {
356
+ throw new Error('Invalid federated surface identity: ' + name);
357
+ }
358
+ return value;
359
+ };
360
+ const exactOrigin = (value) => {
361
+ const origin = new URL(value).origin;
362
+ if (origin === 'null') throw new Error('The TAP host origin must be concrete.');
363
+ return origin;
364
+ };
365
+ const packageId = safeId('packageId');
366
+ const packageNamespace = required('namespace');
367
+ if (!/^[a-z][a-z0-9-]{0,127}(?:\.[a-z0-9][a-z0-9-]{0,127})*$/u.test(packageNamespace)) {
368
+ throw new Error('Invalid TAP package namespace.');
369
+ }
370
+ const installationId = safeId('installationId');
371
+ const releaseId = safeId('releaseId');
372
+ const contributionId = safeId('contributionId');
373
+ // The logical instance is stable across a fresh-realm handoff so package
374
+ // checkpoint participants can restore the prior realm's state. The frame
375
+ // instance is unique per iframe and remains the authority on every host
376
+ // protocol message. Older hosts omit logicalInstanceId and retain the
377
+ // original single-identity behavior.
378
+ const frameInstanceId = safeId('instanceId', 'miniappInstanceId');
379
+ const instanceId = safeId('logicalInstanceId', 'instanceId');
380
+ const workspaceId = optionalSafeId('workspaceId');
381
+ const channelId = optionalSafeId('channelId');
382
+ const conversationId = optionalSafeId('conversationId');
383
+ const expose = required('expose');
384
+ if (!/^\.\/[A-Za-z0-9._/-]+$/u.test(expose) || expose.includes('..')) {
385
+ throw new Error('Invalid Module Federation expose.');
386
+ }
387
+ const remoteEntryPath = required('remoteEntry');
388
+ if (
389
+ remoteEntryPath.startsWith('/') ||
390
+ remoteEntryPath.startsWith('//') ||
391
+ remoteEntryPath.includes('\\') ||
392
+ remoteEntryPath.includes('?') ||
393
+ remoteEntryPath.includes('#') ||
394
+ remoteEntryPath.includes(':') ||
395
+ remoteEntryPath.includes('%') ||
396
+ /[\u0000-\u001f\u007f-\u009f]/u.test(remoteEntryPath) ||
397
+ remoteEntryPath.split('/').some((part) => !part || part === '.' || part === '..')
398
+ ) {
399
+ throw new Error('Invalid Module Federation remote entry path.');
400
+ }
401
+ const packageOrigin = location.origin;
402
+ if (packageOrigin === 'null') {
403
+ throw new Error('The TAP package origin must be concrete.');
404
+ }
405
+ const remoteEntry = new URL(remoteEntryPath, import.meta.url);
406
+ if (
407
+ remoteEntry.origin !== packageOrigin ||
408
+ remoteEntry.username ||
409
+ remoteEntry.password ||
410
+ remoteEntry.search ||
411
+ remoteEntry.hash
412
+ ) {
413
+ throw new Error('The Module Federation remote entry URL is not canonical.');
414
+ }
415
+ const packageAssetBase = new URL('./', remoteEntry);
416
+ const remoteEntryDirectoryPath = remoteEntryPath.slice(0, remoteEntryPath.lastIndexOf('/') + 1);
417
+ const expectedPackageAssetBase = new URL(remoteEntryDirectoryPath || './', import.meta.url);
418
+ if (
419
+ packageAssetBase.origin !== packageOrigin ||
420
+ packageAssetBase.username ||
421
+ packageAssetBase.password ||
422
+ packageAssetBase.search ||
423
+ packageAssetBase.hash ||
424
+ !packageAssetBase.pathname.endsWith('/') ||
425
+ packageAssetBase.href !== expectedPackageAssetBase.href ||
426
+ packageAssetBase.pathname !== remoteEntry.pathname.slice(0, remoteEntry.pathname.lastIndexOf('/') + 1)
427
+ ) {
428
+ throw new Error('The TAP package asset base URL is not canonical.');
429
+ }
430
+ const packageAssetBaseUrl = packageAssetBase.href;
431
+ const hostOrigin = exactOrigin(requiredEither('hostOrigin', 'miniappHostOrigin'));
432
+ const persistence = required('persistence');
433
+ if (!new Set(['none', 'checkpoint', 'retained']).has(persistence)) {
434
+ throw new Error('Invalid TAP mini app persistence policy.');
435
+ }
436
+ const declaredPublishedEvents = new Set(params.getAll('publishes'));
437
+ const declaredSubscribedEvents = new Set(params.getAll('subscribes'));
438
+ const eventListeners = new Map();
439
+ const postHost = (message) => window.parent.postMessage(Object.freeze(message), hostOrigin);
440
+ const CHECKPOINT_SAVE_ACTION = 'tap.package.checkpoint.save';
441
+ const CHECKPOINT_LOAD_ACTION = 'tap.package.checkpoint.load';
442
+ const HOST_ACTION_REQUEST = 'tap-miniapp-host-action';
443
+ const HOST_ACTION_RESPONSE = 'tap-miniapp-host-action-response';
444
+ const MAX_PENDING_HOST_ACTIONS = 32;
445
+ const MAX_CHECKPOINT_REFERENCE_CHARS = 512;
446
+ const MAX_CHECKPOINT_JSON_BYTES = 32 * 1024;
447
+ const HOST_ACTION_TIMEOUT_MS = 4000;
448
+ const pendingHostActions = new Map();
449
+ let hostActionSequence = 0;
450
+ const validCheckpointReference = (reference) =>
451
+ typeof reference === 'string' &&
452
+ reference.length > 0 &&
453
+ reference.trim() === reference &&
454
+ Array.from(reference).length <= MAX_CHECKPOINT_REFERENCE_CHARS &&
455
+ !/[\u0000-\u001f\u007f-\u009f]/u.test(reference);
456
+ const checkedCheckpointValue = (value) => {
457
+ let encoded;
458
+ try {
459
+ encoded = JSON.stringify(value);
460
+ } catch {
461
+ throw new Error('A checkpoint value must be JSON serializable.');
462
+ }
463
+ if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > MAX_CHECKPOINT_JSON_BYTES) {
464
+ throw new Error('A checkpoint value must be bounded JSON.');
465
+ }
466
+ return value;
467
+ };
468
+ const requestHostAction = (action, payload, timeoutMs = HOST_ACTION_TIMEOUT_MS) => {
469
+ if (pendingHostActions.size >= MAX_PENDING_HOST_ACTIONS) {
470
+ return Promise.reject(new Error('Too many miniapp host actions are pending.'));
471
+ }
472
+ const requestId = 'tap-host-action-' + (++hostActionSequence) + '-' +
473
+ (globalThis.crypto?.randomUUID?.() ?? Date.now().toString(36));
474
+ return new Promise((resolve, reject) => {
475
+ const timeout = setTimeout(() => {
476
+ pendingHostActions.delete(requestId);
477
+ reject(new Error('The miniapp host action timed out.'));
478
+ }, timeoutMs);
479
+ pendingHostActions.set(requestId, { resolve, reject, timeout });
480
+ postHost({
481
+ type: HOST_ACTION_REQUEST,
482
+ id: requestId,
483
+ action,
484
+ documentId,
485
+ payload,
486
+ instanceId: frameInstanceId,
487
+ });
488
+ });
489
+ };
490
+ const checkpointService = persistence === 'checkpoint'
491
+ ? Object.freeze({
492
+ async save(reference, value) {
493
+ if (!validCheckpointReference(reference)) {
494
+ throw new Error('Invalid checkpoint reference.');
495
+ }
496
+ await requestHostAction(CHECKPOINT_SAVE_ACTION, {
497
+ checkpointReference: reference,
498
+ value: checkedCheckpointValue(value),
499
+ });
500
+ },
501
+ async load(reference) {
502
+ if (!validCheckpointReference(reference)) {
503
+ throw new Error('Invalid checkpoint reference.');
504
+ }
505
+ return await requestHostAction(CHECKPOINT_LOAD_ACTION, {
506
+ checkpointReference: reference,
507
+ });
508
+ },
509
+ })
510
+ : undefined;
511
+ const lifecycleContext = (value) => {
512
+ const context = Object.create(null);
513
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
514
+ for (const [key, entry] of Object.entries(value)) {
515
+ if (key !== 'checkpoint') context[key] = entry;
516
+ }
517
+ }
518
+ if (checkpointService) context.checkpoint = checkpointService;
519
+ return Object.freeze(context);
520
+ };
521
+ const lifecycleTransition = (phase, value) => {
522
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
523
+ if (phase === 'lifecycleError') {
524
+ const transition = value.transition;
525
+ if (!transition || typeof transition !== 'object' || Array.isArray(transition)) {
526
+ return value;
527
+ }
528
+ return Object.freeze({
529
+ ...value,
530
+ transition: Object.freeze({
531
+ ...transition,
532
+ context: lifecycleContext(transition.context),
533
+ }),
534
+ });
535
+ }
536
+ return Object.freeze({ ...value, context: lifecycleContext(value.context) });
537
+ };
538
+ const events = Object.freeze({
539
+ publish(localName, payload = {}) {
540
+ if (!declaredPublishedEvents.has(localName)) {
541
+ throw new Error('The package attempted to publish an undeclared event.');
542
+ }
543
+ postHost({
544
+ type: 'tap.package.event.publish',
545
+ event: 'tap-pkg.' + packageNamespace + '.' + localName,
546
+ localName,
547
+ payload,
548
+ packageId,
549
+ releaseId,
550
+ installationId,
551
+ contributionId,
552
+ instanceId: frameInstanceId,
553
+ });
554
+ },
555
+ subscribe(eventName, listener) {
556
+ if (!declaredSubscribedEvents.has(eventName) || typeof listener !== 'function') {
557
+ throw new Error('The package attempted to subscribe to an undeclared event.');
558
+ }
559
+ const listeners = eventListeners.get(eventName) ?? new Set();
560
+ listeners.add(listener);
561
+ eventListeners.set(eventName, listeners);
562
+ return () => listeners.delete(listener);
563
+ },
564
+ });
565
+ const root = document.getElementById('tap-root');
566
+ const errorElement = document.getElementById('tap-error');
567
+ let mounted;
568
+ let surfaceMounted = false;
569
+ let uiModule;
570
+ let lifecyclePlugin;
571
+ let lifecycleModule;
572
+ let disposed = false;
573
+ let hostReadyAcknowledged = false;
574
+ let surfaceReadyAnnounced = false;
575
+ let releaseConfirmed = false;
576
+ let surfaceRevealReady = false;
577
+ const hostAuthorityListeners = new Set();
578
+ const hostAuthority = Object.freeze({
579
+ getSnapshot: () => releaseConfirmed,
580
+ subscribe(listener) {
581
+ if (typeof listener !== 'function') {
582
+ throw new Error('A host-authority subscriber must be a function.');
583
+ }
584
+ hostAuthorityListeners.add(listener);
585
+ return () => hostAuthorityListeners.delete(listener);
586
+ },
587
+ });
588
+ const documentIdKey = Symbol.for(${TAP_FEDERATED_DOCUMENT_ID_GLOBAL_KEY});
589
+ const existingDocumentId = globalThis[documentIdKey];
590
+ const documentId = typeof existingDocumentId === 'string'
591
+ ? existingDocumentId
592
+ : 'document-' + (globalThis.crypto?.randomUUID?.() ?? installationId + ':' + frameInstanceId + ':' + Date.now());
593
+ globalThis[documentIdKey] = documentId;
594
+
595
+ const requireOptionsObject = (options, label) => {
596
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
597
+ throw new Error(label + ' requires an options object.');
598
+ }
599
+ return options;
600
+ };
601
+ const requireOptionString = (value, label) => {
602
+ if (typeof value !== 'string' || !value.trim()) {
603
+ throw new Error(label + ' requires a non-empty string.');
604
+ }
605
+ };
606
+ const projectResultFields = (value, fields, label) => {
607
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
608
+ throw new Error(label + ' returned an invalid result.');
609
+ }
610
+ const projected = Object.create(null);
611
+ for (const field of fields) {
612
+ if (Object.prototype.hasOwnProperty.call(value, field)) {
613
+ projected[field] = value[field];
614
+ }
615
+ }
616
+ return Object.freeze(projected);
617
+ };
618
+ const invokeSdkHostAction = (action, options, label, timeoutMs = HOST_ACTION_TIMEOUT_MS) =>
619
+ requestHostAction(action, {
620
+ options: requireOptionsObject(options, label),
621
+ }, timeoutMs);
622
+ const channels = Object.freeze({
623
+ create(options) {
624
+ requireOptionString(options?.name, 'app.channels.create name');
625
+ return invokeSdkHostAction('createChannel', options, 'app.channels.create');
626
+ },
627
+ list(options = {}) {
628
+ return invokeSdkHostAction('listChannels', options, 'app.channels.list');
629
+ },
630
+ sendMessage(options) {
631
+ requireOptionString(options?.channelId, 'app.channels.sendMessage channelId');
632
+ requireOptionString(options?.content, 'app.channels.sendMessage content');
633
+ return invokeSdkHostAction('sendChannelMessage', options, 'app.channels.sendMessage');
634
+ },
635
+ sendSpecialistMessage(options) {
636
+ requireOptionString(
637
+ options?.channelId,
638
+ 'app.channels.sendSpecialistMessage channelId',
639
+ );
640
+ requireOptionString(
641
+ options?.specialistId,
642
+ 'app.channels.sendSpecialistMessage specialistId',
643
+ );
644
+ requireOptionString(
645
+ options?.projectId,
646
+ 'app.channels.sendSpecialistMessage projectId',
647
+ );
648
+ requireOptionString(
649
+ options?.clientMessageId,
650
+ 'app.channels.sendSpecialistMessage clientMessageId',
651
+ );
652
+ requireOptionString(
653
+ options?.body,
654
+ 'app.channels.sendSpecialistMessage body',
655
+ );
656
+ return invokeSdkHostAction(
657
+ 'sendSpecialistChannelMessage',
658
+ options,
659
+ 'app.channels.sendSpecialistMessage',
660
+ );
661
+ },
662
+ getAccess(options) {
663
+ requireOptionString(options?.channelId, 'app.channels.getAccess channelId');
664
+ return invokeSdkHostAction('getChannelAccess', options, 'app.channels.getAccess');
665
+ },
666
+ getTimeline(options) {
667
+ requireOptionString(options?.channelId, 'app.channels.getTimeline channelId');
668
+ return invokeSdkHostAction('getChannelTimeline', options, 'app.channels.getTimeline');
669
+ },
670
+ });
671
+ const projects = Object.freeze({
672
+ create(options) {
673
+ requireOptionString(options?.name, 'app.projects.create name');
674
+ return invokeSdkHostAction('createProject', options, 'app.projects.create');
675
+ },
676
+ get(options) {
677
+ requireOptionString(options?.projectId, 'app.projects.get projectId');
678
+ return invokeSdkHostAction('getProject', options, 'app.projects.get');
679
+ },
680
+ update(options) {
681
+ requireOptionString(options?.projectId, 'app.projects.update projectId');
682
+ return invokeSdkHostAction('updateProject', options, 'app.projects.update');
683
+ },
684
+ });
685
+ const workflows = Object.freeze({
686
+ list(options = {}) {
687
+ return invokeSdkHostAction('listWorkflows', options, 'app.workflows.list');
688
+ },
689
+ invokeSaved(options) {
690
+ requireOptionString(options?.workflowId, 'app.workflows.invokeSaved workflowId');
691
+ return invokeSdkHostAction('invokeSavedWorkflow', options, 'app.workflows.invokeSaved');
692
+ },
693
+ });
694
+ const navigation = Object.freeze({
695
+ open(options) {
696
+ requireOptionString(options?.path, 'app.navigation.open path');
697
+ return invokeSdkHostAction('navigateToPath', options, 'app.navigation.open');
698
+ },
699
+ });
700
+ const appChat = Object.freeze({
701
+ sendTextToChat(text) {
702
+ requireOptionString(text, 'app.chat.sendTextToChat text');
703
+ return invokeSdkHostAction('sendTextToChat', { text }, 'app.chat.sendTextToChat');
704
+ },
705
+ });
706
+
707
+ const platformAuth = Object.freeze({
708
+ getUserProfile() {
709
+ return invokeSdkHostAction(
710
+ 'tap.platform.auth.get-user-profile',
711
+ {},
712
+ 'platform.auth.getUserProfile',
713
+ ).then((profile) => profile === null ? null : projectResultFields(
714
+ profile,
715
+ [
716
+ 'sub', 'name', 'givenName', 'familyName', 'middleName', 'nickname',
717
+ 'preferredUsername', 'profile', 'picture', 'website', 'email',
718
+ 'emailVerified', 'gender', 'birthdate', 'zoneinfo', 'locale',
719
+ 'phoneNumber', 'phoneNumberVerified', 'address', 'updatedAt',
720
+ ],
721
+ 'platform.auth.getUserProfile',
722
+ ));
723
+ },
724
+ });
725
+ const platformVfs = Object.freeze({
726
+ provisionProjectChat(options) {
727
+ return invokeSdkHostAction(
728
+ 'tap.platform.vfs.provision-project-chat',
729
+ options,
730
+ 'platform.vfs.provisionProjectChat',
731
+ ).then((result) => projectResultFields(
732
+ result,
733
+ ['mountedRoots', 'worktreeBranch', 'worktreeBaseCommit'],
734
+ 'platform.vfs.provisionProjectChat',
735
+ ));
736
+ },
737
+ writeFile(conversationId, path, data) {
738
+ return invokeSdkHostAction(
739
+ 'tap.platform.vfs.write-file',
740
+ { conversationId, path, data },
741
+ 'platform.vfs.writeFile',
742
+ );
743
+ },
744
+ mkdir(conversationId, path) {
745
+ return invokeSdkHostAction(
746
+ 'tap.platform.vfs.mkdir',
747
+ { conversationId, path },
748
+ 'platform.vfs.mkdir',
749
+ );
750
+ },
751
+ });
752
+ const platformSpecialist = Object.freeze({
753
+ joinToChannel(channelId, specialistId) {
754
+ return invokeSdkHostAction(
755
+ 'tap.platform.specialist.join-to-channel',
756
+ { channelId, specialistId },
757
+ 'platform.specialist.joinToChannel',
758
+ );
759
+ },
760
+ listWorkspace(requestedWorkspaceId) {
761
+ requireOptionString(
762
+ requestedWorkspaceId,
763
+ 'platform.specialist.listWorkspace workspaceId',
764
+ );
765
+ return invokeSdkHostAction(
766
+ 'tap.platform.specialist.list-workspace',
767
+ { workspaceId: requestedWorkspaceId },
768
+ 'platform.specialist.listWorkspace',
769
+ ).then((result) => {
770
+ if (!Array.isArray(result)) {
771
+ throw new Error('platform.specialist.listWorkspace returned an invalid result.');
772
+ }
773
+ return result.map((specialist) => projectResultFields(
774
+ specialist,
775
+ [
776
+ 'id', 'slug', 'displayName', 'description', 'tags', 'version',
777
+ 'availability', 'canRunLocally', 'category', 'categoryDisplayName',
778
+ 'requiredCapabilities', 'omnipresence', 'displayIcon',
779
+ ],
780
+ 'platform.specialist.listWorkspace',
781
+ ));
782
+ });
783
+ },
784
+ create(options) {
785
+ return invokeSdkHostAction(
786
+ 'tap.platform.specialist.create',
787
+ options,
788
+ 'platform.specialist.create',
789
+ ).then((result) => projectResultFields(
790
+ result,
791
+ ['id', 'name', 'domain', 'description', 'isActive'],
792
+ 'platform.specialist.create',
793
+ ));
794
+ },
795
+ upsertManaged(specialist) {
796
+ requireOptionsObject(specialist, 'platform.specialist.upsertManaged specialist');
797
+ return invokeSdkHostAction(
798
+ 'tap.platform.specialist.upsert-managed',
799
+ { specialist },
800
+ 'platform.specialist.upsertManaged',
801
+ ).then((result) => projectResultFields(
802
+ result,
803
+ ['specialistId'],
804
+ 'platform.specialist.upsertManaged',
805
+ ));
806
+ },
807
+ runTurnWithTools(options) {
808
+ requireOptionsObject(options, 'platform.specialist.runTurnWithTools');
809
+ requireOptionString(options.workspaceId, 'platform.specialist.runTurnWithTools workspaceId');
810
+ requireOptionString(options.channelId, 'platform.specialist.runTurnWithTools channelId');
811
+ requireOptionString(options.specialistId, 'platform.specialist.runTurnWithTools specialistId');
812
+ requireOptionString(options.content, 'platform.specialist.runTurnWithTools content');
813
+ requireOptionString(options.modelOverride, 'platform.specialist.runTurnWithTools modelOverride');
814
+ if (options.messageId !== null) {
815
+ throw new Error('platform.specialist.runTurnWithTools requires a null messageId.');
816
+ }
817
+ requireOptionString(options.interactionMode, 'platform.specialist.runTurnWithTools interactionMode');
818
+ if (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1 || options.timeoutMs > 90000) {
819
+ throw new Error('platform.specialist.runTurnWithTools timeoutMs must be between 1 and 90000.');
820
+ }
821
+ return invokeSdkHostAction(
822
+ 'tap.platform.specialist.run-turn-with-tools',
823
+ {
824
+ workspaceId: options.workspaceId,
825
+ channelId: options.channelId,
826
+ specialistId: options.specialistId,
827
+ content: options.content,
828
+ modelOverride: options.modelOverride,
829
+ messageId: null,
830
+ interactionMode: options.interactionMode,
831
+ timeoutMs: options.timeoutMs,
832
+ },
833
+ 'platform.specialist.runTurnWithTools',
834
+ options.timeoutMs + 1000,
835
+ ).then((result) => {
836
+ const completionEvent = result?.completionEvent;
837
+ if (!completionEvent || !Array.isArray(completionEvent.parts)) {
838
+ throw new Error('platform.specialist.runTurnWithTools returned an invalid completion event.');
839
+ }
840
+ if (
841
+ completionEvent.finishReason !== undefined &&
842
+ typeof completionEvent.finishReason !== 'string'
843
+ ) {
844
+ throw new Error('platform.specialist.runTurnWithTools returned an invalid finish reason.');
845
+ }
846
+ if (
847
+ completionEvent.modelUsed !== undefined &&
848
+ typeof completionEvent.modelUsed !== 'string'
849
+ ) {
850
+ throw new Error('platform.specialist.runTurnWithTools returned an invalid model name.');
851
+ }
852
+ return {
853
+ completionEvent: {
854
+ parts: completionEvent.parts,
855
+ ...(completionEvent.finishReason !== undefined
856
+ ? { finishReason: completionEvent.finishReason }
857
+ : {}),
858
+ ...(completionEvent.modelUsed !== undefined
859
+ ? { modelUsed: completionEvent.modelUsed }
860
+ : {}),
861
+ },
862
+ };
863
+ });
864
+ },
865
+ });
866
+ const platformChat = Object.freeze({
867
+ joinChannelSpecialist(channelId, specialistId) {
868
+ return invokeSdkHostAction(
869
+ 'tap.platform.chat.join-channel-specialist',
870
+ { channelId, specialistId },
871
+ 'platform.chat.joinChannelSpecialist',
872
+ );
873
+ },
874
+ archiveConversation(workspaceId, userId, conversationId, projectId) {
875
+ requireOptionString(workspaceId, 'platform.chat.archiveConversation workspaceId');
876
+ requireOptionString(userId, 'platform.chat.archiveConversation userId');
877
+ requireOptionString(conversationId, 'platform.chat.archiveConversation conversationId');
878
+ requireOptionString(projectId, 'platform.chat.archiveConversation projectId');
879
+ return invokeSdkHostAction(
880
+ 'tap.platform.chat.archive-conversation',
881
+ { workspaceId, userId, conversationId, projectId },
882
+ 'platform.chat.archiveConversation',
883
+ );
884
+ },
885
+ });
886
+ const miniappChat = Object.freeze({
887
+ ...appChat,
888
+ ...platformChat,
889
+ });
890
+ const miniappSdk = Object.freeze({
891
+ channels,
892
+ projects,
893
+ workflows,
894
+ navigation,
895
+ chat: miniappChat,
896
+ auth: platformAuth,
897
+ vfs: platformVfs,
898
+ specialist: platformSpecialist,
899
+ hasEditorView: true,
900
+ hasHostHttpRequest: false,
901
+ });
902
+ Object.defineProperty(globalThis, Symbol.for('tap.internal.v1'), {
903
+ configurable: false,
904
+ enumerable: false,
905
+ value: miniappSdk,
906
+ writable: false,
907
+ });
908
+
909
+ // Keep the compatibility host slot while previously published packages move
910
+ // to the public SDK object above.
911
+ const miniappPlatformProvider = Object.freeze({
912
+ hasBrowserView: false,
913
+ hasUpdater: false,
914
+ hasEditorView: true,
915
+ hasHostHttpRequest: false,
916
+ hasQRCodeProvider: false,
917
+ hasQRCodeScanner: false,
918
+ auth: platformAuth,
919
+ vfs: platformVfs,
920
+ specialist: platformSpecialist,
921
+ chat: platformChat,
922
+ });
923
+ Object.defineProperty(globalThis, Symbol.for('tap.platform-provider.v1'), {
924
+ configurable: false,
925
+ enumerable: false,
926
+ value: miniappPlatformProvider,
927
+ writable: false,
928
+ });
929
+
930
+ const syncSurfaceVisibility = () => {
931
+ root.hidden = !(releaseConfirmed && surfaceRevealReady);
932
+ };
933
+ const setReleaseConfirmed = (confirmed) => {
934
+ if (releaseConfirmed === confirmed) return false;
935
+ releaseConfirmed = confirmed;
936
+ syncSurfaceVisibility();
937
+ for (const listener of [...hostAuthorityListeners]) {
938
+ try { listener(); } catch { /* isolate package observers */ }
939
+ }
940
+ return true;
941
+ };
942
+
943
+ const loadExpose = async (container, name) => {
944
+ const factory = await container.get(name);
945
+ if (typeof factory !== 'function') throw new Error('The federated expose did not return a module factory.');
946
+ return await factory();
947
+ };
948
+ const operationResult = async (requestId, ok, value) => {
949
+ postHost({
950
+ type: 'tap.miniapp.lifecycle.result',
951
+ requestId,
952
+ ok,
953
+ value,
954
+ packageId,
955
+ releaseId,
956
+ installationId,
957
+ contributionId,
958
+ instanceId: frameInstanceId,
959
+ });
960
+ };
961
+ const mountSurface = async () => {
962
+ if (surfaceMounted) return;
963
+ const mount = uiModule?.mount ?? uiModule?.default?.mount;
964
+ if (typeof mount !== 'function') throw new Error('The UI expose must export mount(container, context).');
965
+ mounted = await mount(root, Object.freeze({
966
+ packageId,
967
+ packageNamespace,
968
+ releaseId,
969
+ installationId,
970
+ contributionId,
971
+ instanceId,
972
+ hostOrigin,
973
+ packageAssetBaseUrl,
974
+ workspaceId,
975
+ channelId,
976
+ conversationId,
977
+ events,
978
+ hostAuthority,
979
+ }));
980
+ surfaceMounted = true;
981
+ if (!surfaceReadyAnnounced) {
982
+ surfaceReadyAnnounced = true;
983
+ postHost({ type: 'tap.miniapp.surface.ready', packageId, releaseId, installationId, contributionId, instanceId: frameInstanceId });
984
+ }
985
+ };
986
+ const unmountSurface = async () => {
987
+ if (!surfaceMounted) return;
988
+ surfaceMounted = false;
989
+ const handle = mounted;
990
+ mounted = undefined;
991
+ if (typeof handle === 'function') {
992
+ await handle();
993
+ } else if (typeof handle?.unmount === 'function') {
994
+ await handle.unmount();
995
+ }
996
+ };
997
+ const lifecycleMethods = new Set(['prepare', 'activate', 'mount', 'prePause', 'pause', 'preResume', 'resume', 'unmount', 'deactivate', 'uninstall', 'lifecycleError']);
998
+ const onHostMessage = async (event) => {
999
+ if (event.source !== window.parent || event.origin !== hostOrigin || !event.data || typeof event.data !== 'object') return;
1000
+ const message = event.data;
1001
+ if (message.type === 'zephyr-miniapp-host-ready-ack' && message.instanceId === frameInstanceId) {
1002
+ hostReadyAcknowledged = true;
1003
+ return;
1004
+ }
1005
+ if (
1006
+ message.type === 'tap.miniapp.release.gate' &&
1007
+ typeof message.confirmed === 'boolean' &&
1008
+ message.installationId === installationId &&
1009
+ message.packageId === packageId &&
1010
+ message.releaseId === releaseId &&
1011
+ message.contributionId === contributionId &&
1012
+ message.instanceId === frameInstanceId
1013
+ ) {
1014
+ setReleaseConfirmed(message.confirmed);
1015
+ return;
1016
+ }
1017
+ if (message.type === 'tap.package.event.deliver') {
1018
+ if (!declaredSubscribedEvents.has(message.event)) return;
1019
+ for (const listener of eventListeners.get(message.event) ?? []) {
1020
+ try { await listener(message.payload, message); } catch { /* isolate observer failures */ }
1021
+ }
1022
+ return;
1023
+ }
1024
+ if (message.type === HOST_ACTION_RESPONSE) {
1025
+ const requestId = typeof message.id === 'string' ? message.id : '';
1026
+ const pending = pendingHostActions.get(requestId);
1027
+ if (!pending) return;
1028
+ pendingHostActions.delete(requestId);
1029
+ clearTimeout(pending.timeout);
1030
+ if (message.ok === true) {
1031
+ pending.resolve(message.result);
1032
+ } else {
1033
+ const error = typeof message.error === 'string' && message.error.length <= 1024
1034
+ ? message.error
1035
+ : 'The miniapp host action failed.';
1036
+ pending.reject(new Error(error));
1037
+ }
1038
+ return;
1039
+ }
1040
+ if (message.type !== 'tap.miniapp.lifecycle.request') return;
1041
+ const requestId = typeof message.requestId === 'string' ? message.requestId : '';
1042
+ const phase = typeof message.phase === 'string' ? message.phase : '';
1043
+ if (
1044
+ !requestId ||
1045
+ !lifecycleMethods.has(phase) ||
1046
+ message.installationId !== installationId ||
1047
+ message.packageId !== packageId ||
1048
+ message.releaseId !== releaseId ||
1049
+ message.contributionId !== contributionId ||
1050
+ message.instanceId !== frameInstanceId
1051
+ ) return;
1052
+ try {
1053
+ const transition = lifecycleTransition(phase, message.transition);
1054
+ const handler = ['prePause', 'pause', 'preResume', 'resume', 'lifecycleError'].includes(phase)
1055
+ ? lifecyclePlugin?.[phase]
1056
+ : lifecycleModule?.[phase];
1057
+ let value;
1058
+ if (phase === 'mount') {
1059
+ const hidden = transition?.hidden === true;
1060
+ if (hidden) {
1061
+ surfaceRevealReady = false;
1062
+ syncSurfaceVisibility();
1063
+ }
1064
+ value = typeof handler === 'function' ? await handler(transition) : undefined;
1065
+ if (value !== false) {
1066
+ await mountSurface();
1067
+ if (!hidden) {
1068
+ surfaceRevealReady = true;
1069
+ syncSurfaceVisibility();
1070
+ }
1071
+ }
1072
+ } else if (phase === 'unmount') {
1073
+ await unmountSurface();
1074
+ surfaceRevealReady = false;
1075
+ syncSurfaceVisibility();
1076
+ value = typeof handler === 'function' ? await handler(transition) : undefined;
1077
+ } else {
1078
+ value = typeof handler === 'function' ? await handler(transition) : undefined;
1079
+ if (value !== false && phase === 'pause') {
1080
+ surfaceRevealReady = false;
1081
+ syncSurfaceVisibility();
1082
+ }
1083
+ if (value !== false && phase === 'resume') {
1084
+ surfaceRevealReady = true;
1085
+ syncSurfaceVisibility();
1086
+ }
1087
+ }
1088
+ await operationResult(requestId, true, value);
1089
+ } catch (error) {
1090
+ await operationResult(requestId, false, { message: error instanceof Error ? error.message : 'Lifecycle hook failed.' });
1091
+ }
1092
+ };
1093
+ window.addEventListener('message', onHostMessage);
1094
+
1095
+ try {
1096
+ const container = await import(remoteEntry.href);
1097
+ if (typeof container.init !== 'function' || typeof container.get !== 'function') {
1098
+ throw new Error('The package remote entry is not a Module Federation container.');
1099
+ }
1100
+ await container.init(Object.create(null));
1101
+ const lifecycleExpose = params.get('lifecycleExpose');
1102
+ if (lifecycleExpose) {
1103
+ lifecycleModule = await loadExpose(container, lifecycleExpose);
1104
+ const candidate = lifecycleModule.applicationLifecyclePlugin ?? lifecycleModule.default;
1105
+ if (candidate && typeof candidate === 'object') lifecyclePlugin = candidate;
1106
+ }
1107
+ uiModule = await loadExpose(container, expose);
1108
+ const mount = uiModule.mount ?? uiModule.default?.mount;
1109
+ if (typeof mount !== 'function') throw new Error('The UI expose must export mount(container, context).');
1110
+ const announceReady = () => {
1111
+ if (!hostReadyAcknowledged && !disposed) {
1112
+ postHost({ type: 'zephyr-miniapp-host-ready', documentId, instanceId: frameInstanceId });
1113
+ }
1114
+ };
1115
+ announceReady();
1116
+ const readyTimer = setInterval(announceReady, 250);
1117
+ setTimeout(() => clearInterval(readyTimer), 10000);
1118
+ if (!lifecycleExpose) {
1119
+ await mountSurface();
1120
+ surfaceRevealReady = true;
1121
+ syncSurfaceVisibility();
1122
+ }
1123
+ } catch (error) {
1124
+ root.replaceChildren();
1125
+ root.hidden = false;
1126
+ errorElement.style.display = 'block';
1127
+ postHost({
1128
+ type: 'tap.miniapp.surface.failed',
1129
+ packageId,
1130
+ releaseId,
1131
+ installationId,
1132
+ contributionId,
1133
+ instanceId: frameInstanceId,
1134
+ error: { message: error instanceof Error ? error.message : 'The mini app failed to load.' },
1135
+ });
1136
+ }
1137
+
1138
+ window.addEventListener('pagehide', () => {
1139
+ if (disposed) return;
1140
+ disposed = true;
1141
+ window.removeEventListener('message', onHostMessage);
1142
+ eventListeners.clear();
1143
+ hostAuthorityListeners.clear();
1144
+ for (const pending of pendingHostActions.values()) {
1145
+ clearTimeout(pending.timeout);
1146
+ pending.reject(new Error('The mini app document was removed.'));
1147
+ }
1148
+ pendingHostActions.clear();
1149
+ try { void unmountSurface(); } catch { /* page teardown is best-effort */ }
1150
+ }, { once: true });
1151
+ `;
1152
+ const isUrl = (value)=>{
1153
+ try {
1154
+ new URL(value);
1155
+ return true;
1156
+ } catch {
1157
+ return false;
1158
+ }
1159
+ };
1160
+ const getSchemaValidator = async ()=>{
1161
+ if (!schemaValidator) {
1162
+ const ajv = new __rspack_external_ajv_dist_2020_js_e85899db["default"]({
1163
+ allErrors: true
1164
+ });
1165
+ ajv.addFormat('uri', {
1166
+ type: 'string',
1167
+ validate: isUrl
1168
+ });
1169
+ ajv.addFormat('uint16', {
1170
+ type: 'number',
1171
+ validate: (value)=>Number.isInteger(value) && value >= 0 && value <= 65535
1172
+ });
1173
+ ajv.addFormat('uint64', {
1174
+ type: 'number',
1175
+ validate: (value)=>Number.isSafeInteger(value) && value >= 0
1176
+ });
1177
+ schemaValidator = ajv.compile(config_schema_namespaceObject);
1178
+ }
1179
+ return schemaValidator;
1180
+ };
1181
+ const isFileEntry = (entry)=>__rspack_external_node_path_806ed179["default"].isAbsolute(entry) || entry.startsWith('.') || entry.startsWith('/') || !entry.startsWith('@') && (entry.includes('/') || /\.[a-z0-9]+$/i.test(entry));
1182
+ const sourceString = (source)=>{
1183
+ if ('string' == typeof source) return source;
1184
+ if ('Path' in source) return source.Path.path;
1185
+ if ('Url' in source) return source.Url.url;
1186
+ if ('path' === source.type && 'string' == typeof source.path) return source.path;
1187
+ if ('url' === source.type && 'string' == typeof source.url) return source.url;
1188
+ if ('string' == typeof source.url) return source.url;
1189
+ if ('string' == typeof source.path) return source.path;
1190
+ throw new Error('Miniapp manifest entry must be a string or source object with url/path.');
1191
+ };
1192
+ const sourceIsUrl = (source)=>{
1193
+ if ('string' != typeof source) {
1194
+ if ('Url' in source) return true;
1195
+ if ('Path' in source) return false;
1196
+ return 'url' === source.type || 'string' == typeof source.url;
1197
+ }
1198
+ return isUrl(source);
1199
+ };
1200
+ const resolveBundlerEntry = (manifestPath, entry)=>{
1201
+ const entryValue = sourceString(entry);
1202
+ if (sourceIsUrl(entry)) return EMPTY_ENTRY;
1203
+ if (isFileEntry(entryValue)) return __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), entryValue);
1204
+ return entryValue;
1205
+ };
1206
+ const toPosixPath = (value)=>value.split(__rspack_external_node_path_806ed179["default"].sep).join(__rspack_external_node_path_806ed179["default"].posix.sep);
1207
+ const stripQuery = (value)=>value.split('?')[0];
1208
+ const isLocalReference = (value)=>!isUrl(value) && !value.startsWith('//') && !value.startsWith('#') && !value.startsWith('data:');
1209
+ const toEntryName = (filePath)=>stripQuery(filePath).replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9_./-]/g, '_');
1210
+ const toHtmlScriptEntryName = (filePath)=>`tap-html-${toEntryName(filePath).replace(/[^a-zA-Z0-9_-]/g, '_')}`;
1211
+ const toHtmlStylesheetEntryName = (filePath)=>`tap-html-css-${toEntryName(filePath).replace(/[^a-zA-Z0-9_-]/g, '_')}`;
1212
+ const resolveHtmlAssetPath = (manifestPath, htmlPath, assetPath)=>assetPath.startsWith('/') ? __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), stripQuery(assetPath).slice(1)) : __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(htmlPath), stripQuery(assetPath));
1213
+ const toHtmlLoaderRequest = (manifestPath)=>{
1214
+ const query = new URLSearchParams({
1215
+ manifestDirectory: __rspack_external_node_path_806ed179["default"].dirname(manifestPath)
1216
+ });
1217
+ return `${HTML_LOADER_PATH}?${query.toString()}`;
1218
+ };
1219
+ const toCssEntryLoaderRequest = (sourcePath)=>{
1220
+ const query = new URLSearchParams({
1221
+ source: sourcePath
1222
+ });
1223
+ return `${CSS_ENTRY_LOADER_PATH}?${query.toString()}!${EMPTY_ENTRY}`;
1224
+ };
1225
+ const toVersionedJsFilename = (outputPath)=>{
1226
+ const extension = __rspack_external_node_path_806ed179["default"].posix.extname(outputPath);
1227
+ const baseName = outputPath.slice(0, outputPath.length - extension.length);
1228
+ return `${baseName}.[contenthash:8]${extension || '.js'}`;
1229
+ };
1230
+ const toVersionedAssetPath = (filePath, contents)=>{
1231
+ const extension = __rspack_external_node_path_806ed179["default"].posix.extname(filePath);
1232
+ const baseName = filePath.slice(0, filePath.length - extension.length);
1233
+ const hash = __rspack_external_node_crypto_2e7c4b46["default"].createHash('sha256').update(contents).digest('hex').slice(0, 8);
1234
+ return `${baseName.replace(/\.[a-f0-9]{8}$/i, '')}.${hash}${extension}`;
1235
+ };
1236
+ const minifyInlineCss = (css)=>css.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').replace(/\s*([{}:;,>])\s*/g, '$1').trim();
1237
+ const minifyHtml = (html)=>html.replace(/<!--(?!\[if\b)[\s\S]*?-->/gi, '').replace(/<style\b([^>]*)>([\s\S]*?)<\/style>/gi, (_tag, attrs, css)=>`<style${attrs}>${minifyInlineCss(css)}</style>`).replace(/>\s+</g, '><').replace(/\s{2,}/g, ' ').trim();
1238
+ const toBuffer = (source)=>Buffer.isBuffer(source) ? source : Buffer.from(source);
1239
+ const isBundleManifest = (manifest)=>'entry' in manifest;
1240
+ const isPackageManifest = (manifest)=>"descriptorVersion" in manifest && 1 === manifest.descriptorVersion;
1241
+ const formatManifestPath = (error)=>error.instancePath || '/';
1242
+ const formatManifestError = (error)=>{
1243
+ if ('additionalProperties' === error.keyword) return `${formatManifestPath(error)} has unsupported property "${error.params.additionalProperty}"`;
1244
+ if ('required' === error.keyword) return `${formatManifestPath(error)} is missing required property "${error.params.missingProperty}"`;
1245
+ return `${formatManifestPath(error)} ${error.message ?? 'is invalid'}`;
1246
+ };
1247
+ const formatManifestErrors = (errors = [])=>{
1248
+ const relevantErrors = errors.filter((error)=>'oneOf' !== error.keyword);
1249
+ const formattedErrors = (relevantErrors.length > 0 ? relevantErrors : errors).map(formatManifestError);
1250
+ return [
1251
+ ...new Set(formattedErrors)
1252
+ ].map((message)=>`- ${message}`).join('\n');
1253
+ };
1254
+ const parseManifest = async (manifestPath, contents)=>{
1255
+ let manifest;
1256
+ try {
1257
+ manifest = JSON.parse(toBuffer(contents).toString('utf8'));
1258
+ } catch (error) {
1259
+ if (error instanceof SyntaxError) throw new Error(`${manifestPath} is not valid JSON. Fix the syntax and run the build again.`);
1260
+ throw error;
1261
+ }
1262
+ const validate = await getSchemaValidator();
1263
+ if (!validate(manifest)) throw new Error(`${manifestPath} does not match the TAP manifest schema.\nUse a descriptorVersion: 1 TAP package descriptor, a legacy miniapp manifest with name/description/version/runtime/entry, or a references manifest with references. Do not mix both shapes.\n` + formatManifestErrors(validate.errors ?? []));
1264
+ return manifest;
1265
+ };
1266
+ const readManifest = async (manifestPath)=>parseManifest(manifestPath, await __rspack_external_node_fs_promises_3b710708["default"].readFile(manifestPath));
1267
+ const readBundleManifest = async (manifestPath)=>{
1268
+ const manifest = await readManifest(manifestPath);
1269
+ if (!isBundleManifest(manifest)) throw new Error(`${manifestPath} is a references manifest, but the TAP rspack plugin needs a miniapp manifest with an "entry" field.\nPoint this build at an app manifest, or use the references manifest outside the rspack bundle step.`);
1270
+ return manifest;
1271
+ };
1272
+ const readPackageManifest = async (manifestPath)=>{
1273
+ const manifest = await readManifest(manifestPath);
1274
+ if (!isPackageManifest(manifest)) throw new Error(`${manifestPath} is not a TAP package descriptor, but Module Federation builds require descriptorVersion: 1.`);
1275
+ return manifest;
1276
+ };
1277
+ const parsePackageManifest = async (manifestPath, contents)=>{
1278
+ const manifest = await parseManifest(manifestPath, contents);
1279
+ if (!isPackageManifest(manifest)) throw new Error(`${manifestPath} is not a TAP package descriptor, but Module Federation builds require descriptorVersion: 1.`);
1280
+ return manifest;
1281
+ };
1282
+ const LOCAL_CODE_IMPORT_PATTERN = /(?:import|export)\s+(?:[^'"]+\s+from\s+)?["']([^"']+(?:\?[^"']*)?)["'];?/g;
1283
+ const resolveLocalCodeImport = async (fromPath, specifier)=>{
1284
+ const sourcePath = __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(fromPath), specifier);
1285
+ if (__rspack_external_node_path_806ed179["default"].extname(sourcePath) && await pathExists(sourcePath)) return sourcePath;
1286
+ for (const extension of [
1287
+ '.ts',
1288
+ '.tsx',
1289
+ '.js',
1290
+ '.jsx',
1291
+ '.mjs'
1292
+ ]){
1293
+ const candidate = `${sourcePath}${extension}`;
1294
+ if (await pathExists(candidate)) return candidate;
1295
+ }
1296
+ };
1297
+ const discoverHtmlEntrypointsFromFile = async (manifestPath, entryPath, seen)=>{
1298
+ const normalizedEntryPath = __rspack_external_node_path_806ed179["default"].resolve(entryPath);
1299
+ if (seen.has(normalizedEntryPath)) return [];
1300
+ seen.add(normalizedEntryPath);
1301
+ const entryContents = await __rspack_external_node_fs_promises_3b710708["default"].readFile(normalizedEntryPath, 'utf8');
1302
+ const htmlImports = [
1303
+ ...entryContents.matchAll(HTML_IMPORT_PATTERN)
1304
+ ].map((match)=>stripQuery(match[1])).filter(isLocalReference);
1305
+ const nestedImports = [
1306
+ ...entryContents.matchAll(LOCAL_CODE_IMPORT_PATTERN)
1307
+ ].map((match)=>stripQuery(match[1])).filter((specifier)=>isLocalReference(specifier) && !specifier.endsWith('.html'));
1308
+ const directEntrypoints = await Promise.all(htmlImports.map(async (htmlImport)=>{
1309
+ const sourcePath = __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(normalizedEntryPath), htmlImport);
1310
+ const html = await __rspack_external_node_fs_promises_3b710708["default"].readFile(sourcePath, 'utf8');
1311
+ const scripts = [
1312
+ ...html.matchAll(SCRIPT_SRC_PATTERN)
1313
+ ].map((match)=>match[3]).filter(isLocalReference).map((scriptSource)=>{
1314
+ const source = resolveHtmlAssetPath(manifestPath, sourcePath, scriptSource);
1315
+ const relativeScript = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), source));
1316
+ const entryName = toHtmlScriptEntryName(relativeScript);
1317
+ return {
1318
+ source,
1319
+ output: `${entryName}.js`
1320
+ };
1321
+ });
1322
+ const stylesheets = [
1323
+ ...html.matchAll(STYLESHEET_HREF_PATTERN)
1324
+ ].map((match)=>match[4]).filter(isLocalReference).map((stylesheetSource)=>{
1325
+ const source = resolveHtmlAssetPath(manifestPath, sourcePath, stylesheetSource);
1326
+ const relativeStylesheet = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), source));
1327
+ const entryName = toHtmlStylesheetEntryName(relativeStylesheet);
1328
+ return {
1329
+ source,
1330
+ output: `${entryName}.css`
1331
+ };
1332
+ });
1333
+ return {
1334
+ sourcePath,
1335
+ scripts,
1336
+ stylesheets
1337
+ };
1338
+ }));
1339
+ const nestedEntrypoints = await Promise.all(nestedImports.map(async (specifier)=>{
1340
+ const nestedPath = await resolveLocalCodeImport(normalizedEntryPath, specifier);
1341
+ return nestedPath ? discoverHtmlEntrypointsFromFile(manifestPath, nestedPath, seen) : [];
1342
+ }));
1343
+ return [
1344
+ ...directEntrypoints,
1345
+ ...nestedEntrypoints.flat()
1346
+ ];
1347
+ };
1348
+ const discoverHtmlEntrypoints = async (manifestPath, entryPath)=>{
1349
+ if (isUrl(entryPath)) return [];
1350
+ if (!__rspack_external_node_path_806ed179["default"].isAbsolute(entryPath)) return [];
1351
+ return discoverHtmlEntrypointsFromFile(manifestPath, entryPath, new Set());
1352
+ };
1353
+ const writeFileIfChanged = async (filePath, contents)=>{
1354
+ const nextContents = toBuffer(contents);
1355
+ try {
1356
+ if ((await __rspack_external_node_fs_promises_3b710708["default"].readFile(filePath)).equals(nextContents)) return;
1357
+ } catch (error) {
1358
+ const code = error.code;
1359
+ if ('ENOENT' !== code) throw error;
1360
+ }
1361
+ await __rspack_external_node_fs_promises_3b710708["default"].mkdir(__rspack_external_node_path_806ed179["default"].dirname(filePath), {
1362
+ recursive: true
1363
+ });
1364
+ await __rspack_external_node_fs_promises_3b710708["default"].writeFile(filePath, nextContents);
1365
+ };
1366
+ const pathExists = async (filePath)=>{
1367
+ try {
1368
+ await __rspack_external_node_fs_promises_3b710708["default"].access(filePath);
1369
+ return true;
1370
+ } catch {
1371
+ return false;
1372
+ }
1373
+ };
1374
+ const isRecord = (value)=>'object' == typeof value && null !== value;
1375
+ const readPackageJson = async (rootPath)=>{
1376
+ try {
1377
+ const parsed = JSON.parse(await __rspack_external_node_fs_promises_3b710708["default"].readFile(__rspack_external_node_path_806ed179["default"].join(rootPath, 'package.json'), 'utf8'));
1378
+ return isRecord(parsed) ? parsed : {};
1379
+ } catch (error) {
1380
+ if ('ENOENT' === error.code) return {};
1381
+ throw error;
1382
+ }
1383
+ };
1384
+ const packageDeclaresDependency = (packageJson, dependencyName)=>{
1385
+ for (const field of [
1386
+ 'dependencies',
1387
+ 'devDependencies',
1388
+ 'peerDependencies',
1389
+ 'optionalDependencies'
1390
+ ]){
1391
+ const dependencies = packageJson[field];
1392
+ if ('object' == typeof dependencies && null !== dependencies && dependencyName in dependencies) return true;
1393
+ }
1394
+ return false;
1395
+ };
1396
+ const configureMiniappRspack = (config)=>{
1397
+ config.optimization ??= {};
1398
+ config.optimization.runtimeChunk = 'single';
1399
+ config.optimization.splitChunks = false;
1400
+ config.optimization.usedExports = false;
1401
+ config.optimization.concatenateModules = false;
1402
+ config.resolve ??= {};
1403
+ config.resolve.conditionNames = MINIAPP_BROWSER_CONDITION_NAMES;
1404
+ config.resolve.alias = {
1405
+ ...MINIAPP_CLIENT_ALIASES,
1406
+ ...'object' == typeof config.resolve.alias && null !== config.resolve.alias ? config.resolve.alias : {}
1407
+ };
1408
+ config.output ??= {};
1409
+ config.output.asyncChunks = true;
1410
+ config.module ??= {};
1411
+ config.module.parser ??= {};
1412
+ config.module.parser.asset ??= {};
1413
+ config.module.parser.asset.dataUrlCondition ??= {};
1414
+ config.module.parser.asset.dataUrlCondition.maxSize = 1 / 0;
1415
+ config.plugins ??= [];
1416
+ config.plugins.push(new __rspack_external__rsbuild_core_3f0eaefe.rspack.DefinePlugin(MINIAPP_BROWSER_DEFINES));
1417
+ };
1418
+ const loadPostcssPlugins = async (rootPath)=>{
1419
+ const configPath = __rspack_external_node_path_806ed179["default"].join(rootPath, 'postcss.config.mjs');
1420
+ if (!await pathExists(configPath)) return [];
1421
+ const config = (await import(`${(0, __rspack_external_node_url_3991086a.pathToFileURL)(configPath).href}?t=${Date.now()}`)).default;
1422
+ const plugins = config?.plugins;
1423
+ if (!plugins || 'object' != typeof plugins || Array.isArray(plugins)) return [];
1424
+ const requireFromRoot = (0, __rspack_external_node_module_9de3fa2f.createRequire)(__rspack_external_node_path_806ed179["default"].join(rootPath, 'package.json'));
1425
+ return Promise.all(Object.entries(plugins).map(async ([pluginName, pluginOptions])=>{
1426
+ const pluginModule = await import(requireFromRoot.resolve(pluginName));
1427
+ const plugin = pluginModule.default ?? pluginModule;
1428
+ return 'function' == typeof plugin ? plugin(pluginOptions) : plugin;
1429
+ }));
1430
+ };
1431
+ const processCssFile = async (rootPath, sourcePath)=>{
1432
+ const css = await __rspack_external_node_fs_promises_3b710708["default"].readFile(sourcePath, 'utf8');
1433
+ const plugins = await loadPostcssPlugins(rootPath);
1434
+ if (0 === plugins.length) return css;
1435
+ const requireFromRoot = (0, __rspack_external_node_module_9de3fa2f.createRequire)(__rspack_external_node_path_806ed179["default"].join(rootPath, 'package.json'));
1436
+ const postcss = requireFromRoot('postcss');
1437
+ const result = await postcss(plugins).process(css, {
1438
+ from: sourcePath,
1439
+ to: sourcePath
1440
+ });
1441
+ return result.css;
1442
+ };
1443
+ const snapshotOutputAssets = async (outputPath)=>{
1444
+ const assets = new Map();
1445
+ const visit = async (directory)=>{
1446
+ let entries;
1447
+ try {
1448
+ entries = await __rspack_external_node_fs_promises_3b710708["default"].readdir(directory, {
1449
+ withFileTypes: true
1450
+ });
1451
+ } catch (error) {
1452
+ if ('ENOENT' === error.code) return;
1453
+ throw error;
1454
+ }
1455
+ await Promise.all(entries.map(async (entry)=>{
1456
+ const filePath = __rspack_external_node_path_806ed179["default"].join(directory, String(entry.name));
1457
+ if (entry.isDirectory()) return void await visit(filePath);
1458
+ if (!entry.isFile()) return;
1459
+ const [contents, stats] = await Promise.all([
1460
+ __rspack_external_node_fs_promises_3b710708["default"].readFile(filePath),
1461
+ __rspack_external_node_fs_promises_3b710708["default"].stat(filePath)
1462
+ ]);
1463
+ assets.set(toPosixPath(__rspack_external_node_path_806ed179["default"].relative(outputPath, filePath)), {
1464
+ contents,
1465
+ mtimeMs: stats.mtimeMs
1466
+ });
1467
+ }));
1468
+ };
1469
+ await visit(outputPath);
1470
+ return assets;
1471
+ };
1472
+ const getEntrypointJsFile = (compilation, entryName, outputPath)=>{
1473
+ const files = compilation.entrypoints.get(entryName)?.getFiles() ?? [];
1474
+ const jsFiles = files.filter((file)=>file.endsWith('.js') && !file.endsWith('.js.map'));
1475
+ const expectedBaseName = __rspack_external_node_path_806ed179["default"].posix.basename(stripQuery(outputPath)).replace(/\.[^.]+$/, '');
1476
+ return jsFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file).startsWith(`${expectedBaseName}.`)) ?? jsFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file) === `${expectedBaseName}.js`) ?? jsFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file).startsWith(`${entryName}.`)) ?? jsFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file) === `${entryName}.js`) ?? jsFiles[0];
1477
+ };
1478
+ const getEntrypointCssFile = (compilation, entryName, outputPath)=>{
1479
+ const files = compilation.entrypoints.get(entryName)?.getFiles() ?? [];
1480
+ const cssFiles = files.filter((file)=>file.endsWith('.css') && !file.endsWith('.css.map'));
1481
+ const expectedBaseName = __rspack_external_node_path_806ed179["default"].posix.basename(stripQuery(outputPath)).replace(/\.[^.]+$/, '');
1482
+ return cssFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file).startsWith(`${expectedBaseName}.`)) ?? cssFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file) === `${expectedBaseName}.css`) ?? cssFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file).startsWith(`${entryName}.`)) ?? cssFiles.find((file)=>__rspack_external_node_path_806ed179["default"].posix.basename(file) === `${entryName}.css`) ?? cssFiles[0];
1483
+ };
1484
+ const stripEsmExportsForInline = (source)=>source.replace(FULL_RUNTIME_PREFIX_PATTERN, '').replace(/^var __webpack_require__ = \{\};\s*\(\(\)=>\{\s*__webpack_require__\.j = ["'][^"']+["'];\s*\}\)\(\);\s*/s, '').replace(RUNTIME_IMPORT_PATTERN, '').replace(/export\s*\{[^}]*\};?/g, '').replace(/\bexport\s+(?=(?:async\s+)?function\b|class\b|const\b|let\b|var\b)/g, '');
1485
+ const getNamedImportBindings = (importedNames)=>importedNames.split(',').map((part)=>part.trim()).filter(Boolean).map((part)=>{
1486
+ const [imported, local = imported] = part.split(/\s+as\s+/).map((value)=>value.trim());
1487
+ return {
1488
+ imported,
1489
+ local
1490
+ };
1491
+ }).filter((binding)=>Boolean(binding.imported) && Boolean(binding.local));
1492
+ const inlineNamedImportSource = (source, importedNames)=>{
1493
+ const bindings = getNamedImportBindings(importedNames);
1494
+ const destructuredBindings = bindings.map(({ imported, local })=>imported === local ? imported : `${imported}: ${local}`).join(', ');
1495
+ const returnedBindings = bindings.map(({ imported })=>`${imported}: ${imported}`).join(', ');
1496
+ const runtimePrefix = source.match(FULL_RUNTIME_PREFIX_PATTERN)?.[0] ?? '';
1497
+ const inlinedSource = stripEsmExportsForInline(source);
1498
+ if (runtimePrefix) return `${runtimePrefix}\nconst { ${destructuredBindings} } = (() => {\n${inlinedSource}\nreturn { ${returnedBindings} };\n})();`;
1499
+ if (FULL_RUNTIME_CHUNK_PATTERN.test(inlinedSource)) return `const { ${destructuredBindings}, __tapWebpackRequire } = (() => {\n${inlinedSource}\nreturn { ${returnedBindings}, __tapWebpackRequire: __webpack_require__ };\n})();\nconst __webpack_require__ = __tapWebpackRequire;`;
1500
+ return `const { ${destructuredBindings} } = ((__webpack_require__) => {\n${inlinedSource}\nreturn { ${returnedBindings} };\n})(__webpack_require__);`;
1501
+ };
1502
+ const inlineSideEffectImportSource = (source)=>`(() => {\n${stripEsmExportsForInline(source)}\n})();`;
1503
+ const importsOnlyWebpackRuntime = (importedNames)=>{
1504
+ const bindings = getNamedImportBindings(importedNames);
1505
+ return 1 === bindings.length && bindings[0]?.imported === '__webpack_require__';
1506
+ };
1507
+ const normalizeInlinedRuntimeGuards = (source)=>{
1508
+ const runtimeId = source.match(/__webpack_require__\.j = ["']([^"']+)["']/)?.[1];
1509
+ if (!runtimeId) return source;
1510
+ return source.replace(/\b(?:\d+|["'][^"']+["']) == __webpack_require__\.j/g, `${runtimeId} == __webpack_require__.j`);
1511
+ };
1512
+ const inlineLocalStaticImports = (fileName, assets, seen = new Set(), runtimeFile)=>{
1513
+ if (seen.has(fileName)) return '';
1514
+ seen.add(fileName);
1515
+ const asset = assets[fileName];
1516
+ if (!asset) return '';
1517
+ return asset.source().toString().replace(LOCAL_JS_NAMED_IMPORT_PATTERN, (_importStatement, importedNames, importPath)=>{
1518
+ const importedFileName = toPosixPath(__rspack_external_node_path_806ed179["default"].posix.join(__rspack_external_node_path_806ed179["default"].posix.dirname(fileName), importPath));
1519
+ if (importedFileName === runtimeFile) return '';
1520
+ if (importsOnlyWebpackRuntime(importedNames)) return '';
1521
+ const importedSource = inlineLocalStaticImports(importedFileName, assets, seen, runtimeFile);
1522
+ return inlineNamedImportSource(importedSource, importedNames);
1523
+ }).replace(LOCAL_JS_SIDE_EFFECT_IMPORT_PATTERN, (_importStatement, importPath)=>{
1524
+ const importedFileName = toPosixPath(__rspack_external_node_path_806ed179["default"].posix.join(__rspack_external_node_path_806ed179["default"].posix.dirname(fileName), importPath));
1525
+ if (importedFileName === runtimeFile) return '';
1526
+ return inlineSideEffectImportSource(inlineLocalStaticImports(importedFileName, assets, seen, runtimeFile));
1527
+ });
1528
+ };
1529
+ const inlineEntrypointImports = (compilation, sources, entryOutputPaths)=>{
1530
+ for (const [entryName, outputPath] of entryOutputPaths){
1531
+ if (entryName.startsWith('tap-html-')) continue;
1532
+ const entryFile = getEntrypointJsFile(compilation, entryName, outputPath);
1533
+ if (entryFile && compilation.getAsset(entryFile)) compilation.updateAsset(entryFile, new sources.RawSource(normalizeInlinedRuntimeGuards(inlineLocalStaticImports(entryFile, compilation.assets))));
1534
+ }
1535
+ };
1536
+ const listOutputJsFiles = async (outputRoot)=>{
1537
+ const entries = await __rspack_external_node_fs_promises_3b710708["default"].readdir(outputRoot, {
1538
+ recursive: true
1539
+ });
1540
+ return entries.map((entry)=>toPosixPath(String(entry))).filter((entry)=>entry.endsWith('.js'));
1541
+ };
1542
+ const inlineQuickJsEntrypointOnDisk = async (outputRoot, entryFile)=>{
1543
+ const jsFiles = await listOutputJsFiles(outputRoot);
1544
+ const assets = {};
1545
+ await Promise.all(jsFiles.map(async (fileName)=>{
1546
+ assets[fileName] = new __rspack_external__rsbuild_core_3f0eaefe.rspack.sources.RawSource(await __rspack_external_node_fs_promises_3b710708["default"].readFile(__rspack_external_node_path_806ed179["default"].join(outputRoot, fileName), 'utf8'));
1547
+ }));
1548
+ const runtimeFile = findRuntimeChunk(assets, jsFiles);
1549
+ const runtimeSource = runtimeFile ? (assets[runtimeFile]?.source().toString() ?? '').replace(/export\s*\{[^}]*\};?/g, '').replace(/function __webpack_require__\(moduleId\)\s*\{/, 'var __webpack_require__ = function __webpack_require__(moduleId) {') : '';
1550
+ const inlinedSource = inlineLocalStaticImports(entryFile, assets, new Set(), runtimeFile);
1551
+ const source = normalizeInlinedRuntimeGuards(runtimeSource && inlinedSource.includes('__webpack_require__') && !FULL_RUNTIME_CHUNK_PATTERN.test(inlinedSource) ? `${runtimeSource}\n${inlinedSource.replace(RUNTIME_IMPORT_PATTERN, '')}` : inlinedSource);
1552
+ await writeFileIfChanged(__rspack_external_node_path_806ed179["default"].join(outputRoot, entryFile), Buffer.from(source));
1553
+ };
1554
+ const RUNTIME_CHUNK_EXPORT_PATTERN = /export\s*\{\s*__webpack_require__\s*\}/;
1555
+ const CHUNK_RUNTIME_ID_PATTERN = /(var __webpack_require__ = \{\};\s*\(\(\)=>\{\s*__webpack_require__\.j = )(["'])[^"']+\2(\s*;\s*\}\)\(\);)/;
1556
+ const findRuntimeChunk = (assets, jsFiles)=>jsFiles.find((fileName)=>{
1557
+ const source = assets[fileName]?.source().toString() ?? '';
1558
+ return RUNTIME_CHUNK_EXPORT_PATTERN.test(source) && FULL_RUNTIME_CHUNK_PATTERN.test(source);
1559
+ });
1560
+ const rewriteChunkRuntimeIdsOnDisk = async (outputRoot)=>{
1561
+ const jsFiles = await listOutputJsFiles(outputRoot);
1562
+ let runtimeFile;
1563
+ for (const fileName of jsFiles){
1564
+ const source = await __rspack_external_node_fs_promises_3b710708["default"].readFile(__rspack_external_node_path_806ed179["default"].join(outputRoot, fileName), 'utf8');
1565
+ if (RUNTIME_CHUNK_EXPORT_PATTERN.test(source) && FULL_RUNTIME_CHUNK_PATTERN.test(source)) {
1566
+ runtimeFile = fileName;
1567
+ break;
1568
+ }
1569
+ }
1570
+ if (!runtimeFile) return;
1571
+ const runtimeId = __rspack_external_node_path_806ed179["default"].posix.basename(runtimeFile, '.js');
1572
+ await Promise.all(jsFiles.map(async (fileName)=>{
1573
+ if (fileName === runtimeFile) return;
1574
+ const filePath = __rspack_external_node_path_806ed179["default"].join(outputRoot, fileName);
1575
+ const source = await __rspack_external_node_fs_promises_3b710708["default"].readFile(filePath, 'utf8');
1576
+ const nextSource = source.replace(CHUNK_RUNTIME_ID_PATTERN, `$1"${runtimeId}"$3`).replace(RUNTIME_IMPORT_PATTERN, `import { __webpack_require__ } from "./${runtimeFile}";`);
1577
+ if (nextSource !== source) await writeFileIfChanged(filePath, nextSource);
1578
+ }));
1579
+ };
1580
+ const sha256Integrity = (contents)=>`sha256-${__rspack_external_node_crypto_2e7c4b46["default"].createHash('sha256').update(toBuffer(contents)).digest('base64')}`;
1581
+ const isSafePackageAssetPath = (assetPath)=>{
1582
+ if (0 === assetPath.length || __rspack_external_node_path_806ed179["default"].posix.isAbsolute(assetPath) || assetPath.includes('\\') || assetPath.includes('?') || assetPath.includes('#') || assetPath.includes(':') || assetPath.includes('%') || /[\u0000-\u001f\u007f-\u009f]/u.test(assetPath)) return false;
1583
+ return assetPath.split('/').every((segment)=>segment.length > 0 && '.' !== segment && '..' !== segment);
1584
+ };
1585
+ const isTapPackageTarget = (value)=>TAP_PACKAGE_TARGETS.some((target)=>target === value);
1586
+ const isCanonicalSha256Integrity = (value)=>'string' == typeof value && /^sha256-[A-Za-z0-9+/]{43}=$/u.test(value);
1587
+ const hasExactKeys = (value, expected)=>{
1588
+ const actual = Object.keys(value).sort();
1589
+ const sortedExpected = [
1590
+ ...expected
1591
+ ].sort();
1592
+ return actual.join('\0') === sortedExpected.join('\0');
1593
+ };
1594
+ const parsePackageAssetLock = async (lockPath, contents)=>{
1595
+ const parsed = JSON.parse(toBuffer(contents).toString('utf8'));
1596
+ if (!isRecord(parsed) || !hasExactKeys(parsed, [
1597
+ 'lockVersion',
1598
+ 'packageId',
1599
+ 'releaseId',
1600
+ 'target',
1601
+ 'assets'
1602
+ ]) || 1 !== parsed.lockVersion || 'string' != typeof parsed.packageId || 'string' != typeof parsed.releaseId || 'string' != typeof parsed.target || !isTapPackageTarget(parsed.target) || !isRecord(parsed.assets)) throw new Error(`TAP package asset lock ${lockPath} is invalid.`);
1603
+ const assetEntries = [];
1604
+ const entries = Object.entries(parsed.assets);
1605
+ if (0 === entries.length || entries.length > MAX_PACKAGE_ASSETS) throw new Error(`TAP package asset lock ${lockPath} must contain 1..=${MAX_PACKAGE_ASSETS} assets.`);
1606
+ for (const [assetPath, definition] of entries){
1607
+ if (!isSafePackageAssetPath(assetPath) || !isRecord(definition) || !hasExactKeys(definition, [
1608
+ 'bytes',
1609
+ 'integrity'
1610
+ ]) || 'number' != typeof definition.bytes || !Number.isSafeInteger(definition.bytes) || definition.bytes < 0 || definition.bytes > MAX_PACKAGE_ASSET_BYTES || !isCanonicalSha256Integrity(definition.integrity)) throw new Error(`TAP package asset lock ${lockPath} has an invalid asset entry for ${assetPath}.`);
1611
+ assetEntries.push([
1612
+ assetPath,
1613
+ {
1614
+ bytes: definition.bytes,
1615
+ integrity: definition.integrity
1616
+ }
1617
+ ]);
1618
+ }
1619
+ return {
1620
+ lockVersion: 1,
1621
+ packageId: parsed.packageId,
1622
+ releaseId: parsed.releaseId,
1623
+ target: parsed.target,
1624
+ assets: Object.fromEntries(assetEntries)
1625
+ };
1626
+ };
1627
+ const lockedPackageAsset = (lock, assetPath)=>Object.hasOwn(lock.assets, assetPath) ? lock.assets[assetPath] : void 0;
1628
+ const canonicalizeJson = (value)=>{
1629
+ if (Array.isArray(value)) return value.map(canonicalizeJson);
1630
+ if (!isRecord(value)) return value;
1631
+ return Object.fromEntries(Object.entries(value).sort(([left], [right])=>left.localeCompare(right)).map(([key, nested])=>[
1632
+ key,
1633
+ canonicalizeJson(nested)
1634
+ ]));
1635
+ };
1636
+ const descriptorAssemblyContract = (descriptor)=>{
1637
+ const normalized = structuredClone(descriptor);
1638
+ normalized.release.contentDigest = '<assembled>';
1639
+ for (const asset of normalized.presentation.assets ?? [])asset.integrity = '<assembled>';
1640
+ for (const target of Object.values(normalized.targets)){
1641
+ target.remoteEntry = '<assembled>';
1642
+ target.remoteEntryIntegrity = '<assembled>';
1643
+ target.manifest = '<assembled>';
1644
+ target.manifestIntegrity = '<assembled>';
1645
+ target.assetLock = '<assembled>';
1646
+ target.assetLockIntegrity = '<assembled>';
1647
+ for (const expose of Object.values(target.exposes))expose.integrity = '<assembled>';
1648
+ }
1649
+ return JSON.stringify(canonicalizeJson(normalized));
1650
+ };
1651
+ const isPathWithin = (root, candidate)=>{
1652
+ const relative = __rspack_external_node_path_806ed179["default"].relative(root, candidate);
1653
+ return '' === relative || !__rspack_external_node_path_806ed179["default"].isAbsolute(relative) && !relative.startsWith(`..${__rspack_external_node_path_806ed179["default"].sep}`) && '..' !== relative;
1654
+ };
1655
+ const pathsOverlap = (left, right)=>isPathWithin(left, right) || isPathWithin(right, left);
1656
+ const confinedRegularFile = async (root, assetPath, label, expectedBytes, maxBytes = MAX_PACKAGE_ASSET_BYTES)=>{
1657
+ const candidate = __rspack_external_node_path_806ed179["default"].join(root, ...assetPath.split('/'));
1658
+ const realCandidate = await __rspack_external_node_fs_promises_3b710708["default"].realpath(candidate);
1659
+ const lexicalMetadata = await __rspack_external_node_fs_promises_3b710708["default"].lstat(candidate);
1660
+ if (!isPathWithin(root, realCandidate) || lexicalMetadata.isSymbolicLink()) throw new Error(`${label} must be a confined regular file.`);
1661
+ const handle = await __rspack_external_node_fs_promises_3b710708["default"].open(realCandidate, 'r');
1662
+ try {
1663
+ const metadata = await handle.stat();
1664
+ if (!metadata.isFile() || metadata.size < 0 || metadata.size > maxBytes || void 0 !== expectedBytes && metadata.size !== expectedBytes) throw new Error(`${label} must be a bounded regular file.`);
1665
+ const verifiedRealCandidate = await __rspack_external_node_fs_promises_3b710708["default"].realpath(candidate);
1666
+ const verifiedMetadata = await __rspack_external_node_fs_promises_3b710708["default"].stat(verifiedRealCandidate);
1667
+ if (!isPathWithin(root, verifiedRealCandidate) || verifiedMetadata.dev !== metadata.dev || verifiedMetadata.ino !== metadata.ino) throw new Error(`${label} changed while it was being confined.`);
1668
+ const contents = Buffer.alloc(metadata.size);
1669
+ let offset = 0;
1670
+ while(offset < contents.byteLength){
1671
+ const { bytesRead } = await handle.read(contents, offset, contents.byteLength - offset, offset);
1672
+ if (0 === bytesRead) break;
1673
+ offset += bytesRead;
1674
+ }
1675
+ const overflow = Buffer.alloc(1);
1676
+ const { bytesRead: overflowBytes } = await handle.read(overflow, 0, 1, metadata.size);
1677
+ if (offset !== metadata.size || 0 !== overflowBytes || void 0 !== expectedBytes && offset !== expectedBytes) throw new Error(`${label} changed while it was being assembled.`);
1678
+ return {
1679
+ contents,
1680
+ metadata,
1681
+ path: candidate
1682
+ };
1683
+ } finally{
1684
+ await handle.close();
1685
+ }
1686
+ };
1687
+ const assertPortableTapPackageArtifacts = async ({ output, forbiddenRoots = [] })=>{
1688
+ const outputRoot = await __rspack_external_node_fs_promises_3b710708["default"].realpath(__rspack_external_node_path_806ed179["default"].resolve(output));
1689
+ const forbiddenNeedles = forbiddenRoots.flatMap((root)=>{
1690
+ const absoluteRoot = __rspack_external_node_path_806ed179["default"].resolve(root);
1691
+ if (absoluteRoot === __rspack_external_node_path_806ed179["default"].parse(absoluteRoot).root) throw new Error('A filesystem root cannot be a portability scan needle.');
1692
+ return [
1693
+ absoluteRoot,
1694
+ toPosixPath(absoluteRoot),
1695
+ JSON.stringify(absoluteRoot).slice(1, -1)
1696
+ ];
1697
+ });
1698
+ const entries = await __rspack_external_node_fs_promises_3b710708["default"].readdir(outputRoot, {
1699
+ recursive: true
1700
+ });
1701
+ for (const entry of entries.map(String).sort()){
1702
+ const relativePath = toPosixPath(entry);
1703
+ const candidate = __rspack_external_node_path_806ed179["default"].join(outputRoot, ...relativePath.split('/'));
1704
+ const metadata = await __rspack_external_node_fs_promises_3b710708["default"].lstat(candidate);
1705
+ if (metadata.isSymbolicLink()) throw new Error(`TAP package artifact ${relativePath} must not be a symbolic link.`);
1706
+ if (!metadata.isFile()) continue;
1707
+ const source = (await __rspack_external_node_fs_promises_3b710708["default"].readFile(candidate)).toString('utf8');
1708
+ if (LOCAL_FILE_URL_PATTERN.test(source)) throw new Error(`TAP package artifact ${relativePath} contains a local file URL.`);
1709
+ if (forbiddenNeedles.some((needle)=>source.includes(needle))) throw new Error(`TAP package artifact ${relativePath} contains an absolute checkout path.`);
1710
+ }
1711
+ };
1712
+ const packageAssemblyTransactionPaths = (outputPath)=>({
1713
+ backup: `${outputPath}.tap-backup`,
1714
+ journal: `${outputPath}.tap-assembly.json`
1715
+ });
1716
+ const validateAssemblyDirectory = async (directoryPath)=>{
1717
+ if (!await pathExists(directoryPath)) return;
1718
+ const metadata = await __rspack_external_node_fs_promises_3b710708["default"].lstat(directoryPath);
1719
+ const realPath = await __rspack_external_node_fs_promises_3b710708["default"].realpath(directoryPath);
1720
+ if (!metadata.isDirectory() || metadata.isSymbolicLink() || realPath !== directoryPath) throw new Error(`TAP package assembly path ${directoryPath} must be a canonical directory.`);
1721
+ };
1722
+ const readPackageAssemblyJournal = async (journalPath, outputPath)=>{
1723
+ const journalFile = await confinedRegularFile(__rspack_external_node_path_806ed179["default"].dirname(journalPath), __rspack_external_node_path_806ed179["default"].basename(journalPath), `TAP package assembly journal ${journalPath}`, void 0, 16384);
1724
+ const contents = journalFile.contents;
1725
+ let parsed;
1726
+ try {
1727
+ parsed = JSON.parse(contents.toString('utf8'));
1728
+ } catch {
1729
+ throw new Error(`TAP package assembly journal ${journalPath} is invalid.`);
1730
+ }
1731
+ if (!isRecord(parsed) || !hasExactKeys(parsed, [
1732
+ 'journalVersion',
1733
+ 'stagingPath'
1734
+ ]) || 1 !== parsed.journalVersion || 'string' != typeof parsed.stagingPath) throw new Error(`TAP package assembly journal ${journalPath} is invalid.`);
1735
+ const stagingPath = __rspack_external_node_path_806ed179["default"].resolve(parsed.stagingPath);
1736
+ const outputParent = __rspack_external_node_path_806ed179["default"].dirname(outputPath);
1737
+ if (__rspack_external_node_path_806ed179["default"].dirname(stagingPath) !== outputParent || !__rspack_external_node_path_806ed179["default"].basename(stagingPath).startsWith(`.${__rspack_external_node_path_806ed179["default"].basename(outputPath)}.tap-`)) throw new Error(`TAP package assembly journal ${journalPath} has an invalid staging path.`);
1738
+ return stagingPath;
1739
+ };
1740
+ const recoverPackageAssembly = async (outputPath)=>{
1741
+ const transaction = packageAssemblyTransactionPaths(outputPath);
1742
+ if (!await pathExists(transaction.journal)) return;
1743
+ const stagingPath = await readPackageAssemblyJournal(transaction.journal, outputPath);
1744
+ const outputExists = await pathExists(outputPath);
1745
+ const backupExists = await pathExists(transaction.backup);
1746
+ if (outputExists) await validateAssemblyDirectory(outputPath);
1747
+ if (backupExists) await validateAssemblyDirectory(transaction.backup);
1748
+ if (!outputExists && backupExists) await __rspack_external_node_fs_promises_3b710708["default"].rename(transaction.backup, outputPath);
1749
+ else if (outputExists && backupExists) await __rspack_external_node_fs_promises_3b710708["default"].rm(transaction.backup, {
1750
+ force: true,
1751
+ recursive: true
1752
+ });
1753
+ await __rspack_external_node_fs_promises_3b710708["default"].rm(stagingPath, {
1754
+ force: true,
1755
+ recursive: true
1756
+ });
1757
+ await __rspack_external_node_fs_promises_3b710708["default"].rm(transaction.journal, {
1758
+ force: true
1759
+ });
1760
+ };
1761
+ const writePackageAssemblyJournal = async (journalPath, stagingPath)=>{
1762
+ const handle = await __rspack_external_node_fs_promises_3b710708["default"].open(journalPath, 'wx');
1763
+ try {
1764
+ await handle.writeFile(`${JSON.stringify({
1765
+ journalVersion: 1,
1766
+ stagingPath
1767
+ })}\n`);
1768
+ await handle.sync();
1769
+ } finally{
1770
+ await handle.close();
1771
+ }
1772
+ };
1773
+ const replaceDirectoryTransactionally = async (stagingPath, outputPath)=>{
1774
+ const transaction = packageAssemblyTransactionPaths(outputPath);
1775
+ if (await pathExists(transaction.journal) || await pathExists(transaction.backup)) throw new Error(`TAP package output ${outputPath} has an unresolved assembly transaction.`);
1776
+ await writePackageAssemblyJournal(transaction.journal, stagingPath);
1777
+ const hadOutput = await pathExists(outputPath);
1778
+ if (hadOutput) await __rspack_external_node_fs_promises_3b710708["default"].rename(outputPath, transaction.backup);
1779
+ try {
1780
+ await __rspack_external_node_fs_promises_3b710708["default"].rename(stagingPath, outputPath);
1781
+ } catch (error) {
1782
+ if (hadOutput) try {
1783
+ await __rspack_external_node_fs_promises_3b710708["default"].rename(transaction.backup, outputPath);
1784
+ } catch (restoreError) {
1785
+ throw new AggregateError([
1786
+ error,
1787
+ restoreError
1788
+ ], `TAP package assembly failed and could not restore ${outputPath}.`);
1789
+ }
1790
+ try {
1791
+ await __rspack_external_node_fs_promises_3b710708["default"].rm(transaction.journal, {
1792
+ force: true
1793
+ });
1794
+ } catch {}
1795
+ throw error;
1796
+ }
1797
+ try {
1798
+ if (hadOutput) await __rspack_external_node_fs_promises_3b710708["default"].rm(transaction.backup, {
1799
+ force: true,
1800
+ recursive: true
1801
+ });
1802
+ await __rspack_external_node_fs_promises_3b710708["default"].rm(transaction.journal, {
1803
+ force: true
1804
+ });
1805
+ } catch {}
1806
+ };
1807
+ const assembleTapPackage = async ({ manifest, output, targets })=>{
1808
+ const requestedManifestPath = __rspack_external_node_path_806ed179["default"].resolve(manifest);
1809
+ const manifestParent = await __rspack_external_node_fs_promises_3b710708["default"].realpath(__rspack_external_node_path_806ed179["default"].dirname(requestedManifestPath));
1810
+ const manifestPath = __rspack_external_node_path_806ed179["default"].join(manifestParent, __rspack_external_node_path_806ed179["default"].basename(requestedManifestPath));
1811
+ const manifestFile = await confinedRegularFile(manifestParent, __rspack_external_node_path_806ed179["default"].basename(manifestPath), `TAP package descriptor ${manifestPath}`);
1812
+ const requestedOutputPath = __rspack_external_node_path_806ed179["default"].resolve(output);
1813
+ const requestedOutputParent = __rspack_external_node_path_806ed179["default"].dirname(requestedOutputPath);
1814
+ await __rspack_external_node_fs_promises_3b710708["default"].mkdir(requestedOutputParent, {
1815
+ recursive: true
1816
+ });
1817
+ const outputParent = await __rspack_external_node_fs_promises_3b710708["default"].realpath(requestedOutputParent);
1818
+ const outputPath = __rspack_external_node_path_806ed179["default"].join(outputParent, __rspack_external_node_path_806ed179["default"].basename(requestedOutputPath));
1819
+ await recoverPackageAssembly(outputPath);
1820
+ await validateAssemblyDirectory(outputPath);
1821
+ const descriptor = await parsePackageManifest(manifestPath, manifestFile.contents);
1822
+ const descriptorContract = descriptorAssemblyContract(descriptor);
1823
+ const descriptorFileName = __rspack_external_node_path_806ed179["default"].basename(manifestPath);
1824
+ const descriptorTargets = Object.keys(descriptor.targets).sort();
1825
+ if (0 === descriptorTargets.length || descriptorTargets.some((target)=>!isTapPackageTarget(target))) throw new Error('TAP package assembly requires at least one known target.');
1826
+ const suppliedTargets = Object.entries(targets).filter((entry)=>'string' == typeof entry[1]).map(([target])=>target).sort();
1827
+ if (descriptorTargets.join('\0') !== suppliedTargets.join('\0')) throw new Error(`TAP package assembly targets must exactly match the descriptor. Descriptor: ${descriptorTargets.join(', ')}; supplied: ${suppliedTargets.join(', ')}.`);
1828
+ const targetRoots = new Map();
1829
+ for (const targetName of descriptorTargets){
1830
+ if (!isTapPackageTarget(targetName)) throw new Error(`Unsupported TAP package target ${targetName}.`);
1831
+ const configuredRoot = targets[targetName];
1832
+ if (!configuredRoot) throw new Error(`TAP package target ${targetName} has no build root.`);
1833
+ const root = await __rspack_external_node_fs_promises_3b710708["default"].realpath(__rspack_external_node_path_806ed179["default"].resolve(configuredRoot));
1834
+ if (pathsOverlap(root, outputPath)) throw new Error(`TAP package target root ${root} must not overlap assembled output ${outputPath}.`);
1835
+ for (const [otherTarget, otherRoot] of targetRoots)if (pathsOverlap(root, otherRoot)) throw new Error(`TAP package target roots ${otherTarget} and ${targetName} must not overlap.`);
1836
+ targetRoots.set(targetName, root);
1837
+ }
1838
+ const stagingPath = await __rspack_external_node_fs_promises_3b710708["default"].mkdtemp(__rspack_external_node_path_806ed179["default"].join(__rspack_external_node_path_806ed179["default"].dirname(outputPath), `.${__rspack_external_node_path_806ed179["default"].basename(outputPath)}.tap-`));
1839
+ const sharedPaths = new Set([
1840
+ TAP_FEDERATED_SURFACE_HTML_PATH,
1841
+ TAP_FEDERATED_SURFACE_RUNTIME_PATH,
1842
+ ...(descriptor.presentation.assets ?? []).map((asset)=>asset.path)
1843
+ ]);
1844
+ const assembledAssets = new Map();
1845
+ const targetLockIntegrities = new Map();
1846
+ const presentationIntegrities = new Map();
1847
+ let totalBytes = 0;
1848
+ try {
1849
+ for (const targetName of descriptorTargets){
1850
+ if (!isTapPackageTarget(targetName)) continue;
1851
+ const targetRoot = targetRoots.get(targetName);
1852
+ if (!targetRoot) throw new Error(`TAP package target ${targetName} has no build root.`);
1853
+ const builtDescriptorFile = await confinedRegularFile(targetRoot, descriptorFileName, `TAP package target ${targetName} descriptor`);
1854
+ const builtDescriptor = await parsePackageManifest(builtDescriptorFile.path, builtDescriptorFile.contents);
1855
+ if (descriptorAssemblyContract(builtDescriptor) !== descriptorContract) throw new Error(`TAP package target ${targetName} was built from a different descriptor contract.`);
1856
+ const builtTarget = builtDescriptor.targets[targetName];
1857
+ if (!builtTarget) throw new Error(`TAP package target ${targetName} is absent from its built descriptor.`);
1858
+ const targetPaths = packageTargetOutputPaths(targetName);
1859
+ if (builtTarget.remoteEntry !== targetPaths.remoteEntry || builtTarget.manifest !== targetPaths.manifest || builtTarget.assetLock !== targetPaths.lock) throw new Error(`TAP package target ${targetName} must use the canonical ${targetPaths.directory} output paths.`);
1860
+ const lockFile = await confinedRegularFile(targetRoot, targetPaths.lock, `TAP package target ${targetName} asset lock`);
1861
+ const lockPath = lockFile.path;
1862
+ const lockMetadata = lockFile.metadata;
1863
+ if (lockMetadata.size < 1 || lockMetadata.size > MAX_PACKAGE_ASSET_BYTES) throw new Error(`TAP package target ${targetName} asset lock must be a bounded regular file.`);
1864
+ const lockBytes = lockFile.contents;
1865
+ const lock = await parsePackageAssetLock(lockPath, lockBytes);
1866
+ const lockIntegrity = sha256Integrity(lockBytes);
1867
+ if (lock.packageId !== descriptor.package.packageId || lock.releaseId !== descriptor.release.releaseId || lock.target !== targetName || builtTarget.assetLockIntegrity !== lockIntegrity) throw new Error(`TAP package target ${targetName} asset lock does not match its descriptor identity.`);
1868
+ targetLockIntegrities.set(targetName, lockIntegrity);
1869
+ const requiredTargetAssets = [
1870
+ [
1871
+ builtTarget.remoteEntry,
1872
+ builtTarget.remoteEntryIntegrity
1873
+ ],
1874
+ [
1875
+ builtTarget.manifest,
1876
+ builtTarget.manifestIntegrity
1877
+ ]
1878
+ ];
1879
+ for (const [assetPath, integrity] of requiredTargetAssets){
1880
+ const locked = assetPath ? lockedPackageAsset(lock, assetPath) : void 0;
1881
+ if (!locked || locked.integrity !== integrity) throw new Error(`TAP package target ${targetName} lock does not match required asset ${String(assetPath)}.`);
1882
+ }
1883
+ for (const presentation of builtDescriptor.presentation.assets ?? []){
1884
+ const locked = lockedPackageAsset(lock, presentation.path);
1885
+ if (!locked || locked.integrity !== presentation.integrity) throw new Error(`TAP package target ${targetName} does not lock presentation asset ${presentation.path}.`);
1886
+ const canonicalPresentation = descriptor.presentation.assets?.find((asset)=>asset.path === presentation.path);
1887
+ if (!canonicalPresentation) throw new Error(`TAP package target ${targetName} introduced presentation asset ${presentation.path}.`);
1888
+ const existingIntegrity = presentationIntegrities.get(presentation.path);
1889
+ if (existingIntegrity && existingIntegrity !== presentation.integrity) throw new Error(`TAP package presentation asset ${presentation.path} differs between targets.`);
1890
+ presentationIntegrities.set(presentation.path, presentation.integrity);
1891
+ canonicalPresentation.integrity = presentation.integrity;
1892
+ }
1893
+ const targetAssetContents = new Map();
1894
+ for (const [assetPath, definition] of Object.entries(lock.assets)){
1895
+ const targetPrefix = `${targetPaths.directory}/`;
1896
+ if (!assetPath.startsWith(targetPrefix) && !sharedPaths.has(assetPath)) throw new Error(`TAP package target ${targetName} emits non-shared asset ${assetPath} outside ${targetPaths.directory}.`);
1897
+ const sourceFile = await confinedRegularFile(targetRoot, assetPath, `TAP package target ${targetName} asset ${assetPath}`, definition.bytes);
1898
+ const contents = sourceFile.contents;
1899
+ if (contents.byteLength !== definition.bytes || sha256Integrity(contents) !== definition.integrity) throw new Error(`TAP package target ${targetName} asset ${assetPath} does not match its lock.`);
1900
+ targetAssetContents.set(assetPath, contents);
1901
+ const existing = assembledAssets.get(assetPath);
1902
+ if (existing) {
1903
+ if (!sharedPaths.has(assetPath)) throw new Error(`TAP package targets ${existing.target} and ${targetName} collide at ${assetPath}.`);
1904
+ if (existing.bytes !== definition.bytes || existing.integrity !== definition.integrity) throw new Error(`Shared TAP package asset ${assetPath} differs between ${existing.target} and ${targetName}.`);
1905
+ continue;
1906
+ }
1907
+ totalBytes += definition.bytes;
1908
+ if (assembledAssets.size >= MAX_PACKAGE_ASSETS) throw new Error(`Assembled TAP package exceeds the ${MAX_PACKAGE_ASSETS}-asset graph limit.`);
1909
+ if (totalBytes > MAX_PACKAGE_BYTES) throw new Error(`Assembled TAP package exceeds the ${MAX_PACKAGE_BYTES}-byte graph limit.`);
1910
+ assembledAssets.set(assetPath, {
1911
+ ...definition,
1912
+ target: targetName
1913
+ });
1914
+ await writeFileIfChanged(__rspack_external_node_path_806ed179["default"].join(stagingPath, ...assetPath.split('/')), contents);
1915
+ }
1916
+ const federationManifestBytes = targetAssetContents.get(targetPaths.manifest);
1917
+ if (!federationManifestBytes) throw new Error(`TAP package target ${targetName} has no locked Federation manifest bytes.`);
1918
+ let federationManifest;
1919
+ try {
1920
+ federationManifest = JSON.parse(federationManifestBytes.toString('utf8'));
1921
+ } catch {
1922
+ throw new Error(`TAP package target ${targetName} Federation manifest is not valid JSON.`);
1923
+ }
1924
+ for (const [exposeName, expose] of Object.entries(builtTarget.exposes)){
1925
+ const exposeAssets = federationExposeAssetPaths(federationManifest, exposeName);
1926
+ for (const assetPath of exposeAssets)if (!isSafePackageAssetPath(assetPath) || !lockedPackageAsset(lock, assetPath)) throw new Error(`TAP package target ${targetName} expose ${exposeName} references unlocked asset ${assetPath}.`);
1927
+ const integrity = integrityForAssetGraph([
1928
+ targetPaths.remoteEntry,
1929
+ targetPaths.manifest,
1930
+ ...exposeAssets
1931
+ ], lock);
1932
+ if (integrity !== expose.integrity) throw new Error(`TAP package target ${targetName} expose ${exposeName} integrity does not match its locked graph.`);
1933
+ }
1934
+ totalBytes += lockBytes.byteLength;
1935
+ if (totalBytes > MAX_PACKAGE_BYTES) throw new Error(`Assembled TAP package exceeds the ${MAX_PACKAGE_BYTES}-byte graph limit.`);
1936
+ await writeFileIfChanged(__rspack_external_node_path_806ed179["default"].join(stagingPath, ...targetPaths.lock.split('/')), lockBytes);
1937
+ descriptor.targets[targetName] = structuredClone(builtTarget);
1938
+ }
1939
+ const contentGraph = [
1940
+ ...targetLockIntegrities
1941
+ ].sort(([left], [right])=>left.localeCompare(right)).map(([target, integrity])=>`${target}\0${packageTargetOutputPaths(target).lock}\0${integrity}`).join('\n');
1942
+ descriptor.release.contentDigest = sha256Integrity(contentGraph);
1943
+ await writeFileIfChanged(__rspack_external_node_path_806ed179["default"].join(stagingPath, descriptorFileName), `${JSON.stringify(descriptor, null, 2)}\n`);
1944
+ await readPackageManifest(__rspack_external_node_path_806ed179["default"].join(stagingPath, descriptorFileName));
1945
+ await replaceDirectoryTransactionally(stagingPath, outputPath);
1946
+ } finally{
1947
+ await __rspack_external_node_fs_promises_3b710708["default"].rm(stagingPath, {
1948
+ force: true,
1949
+ recursive: true
1950
+ });
1951
+ }
1952
+ };
1953
+ const validatePngIcon = (assetPath, contents)=>{
1954
+ const pngSignature = Buffer.from([
1955
+ 137,
1956
+ 80,
1957
+ 78,
1958
+ 71,
1959
+ 13,
1960
+ 10,
1961
+ 26,
1962
+ 10
1963
+ ]);
1964
+ if (contents.length < 24 || !contents.subarray(0, pngSignature.length).equals(pngSignature) || 'IHDR' !== contents.toString('ascii', 12, 16)) throw new Error(`TAP presentation asset ${assetPath} declares image/png but is not a valid PNG header.`);
1965
+ const width = contents.readUInt32BE(16);
1966
+ const height = contents.readUInt32BE(20);
1967
+ if (0 === width || 0 === height || width > MAX_PACKAGE_ICON_DIMENSION || height > MAX_PACKAGE_ICON_DIMENSION || width * height > MAX_PACKAGE_ICON_PIXELS) throw new Error(`TAP presentation asset ${assetPath} exceeds the ${MAX_PACKAGE_ICON_PIXELS}-pixel decode budget.`);
1968
+ return {
1969
+ width,
1970
+ height
1971
+ };
1972
+ };
1973
+ const parsePresentationAssetSize = (value)=>{
1974
+ if ('any' === value) return null;
1975
+ const match = /^(\d+)x(\d+)$/.exec(value);
1976
+ if (!match) return;
1977
+ const width = Number(match[1]);
1978
+ const height = Number(match[2]);
1979
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0 || width > MAX_PACKAGE_ICON_DIMENSION || height > MAX_PACKAGE_ICON_DIMENSION) return;
1980
+ return {
1981
+ width,
1982
+ height
1983
+ };
1984
+ };
1985
+ const validatePackagePresentationAsset = (asset, contents)=>{
1986
+ if (0 === contents.length || contents.length > MAX_PACKAGE_ICON_BYTES) throw new Error(`TAP presentation asset ${asset.path} must be between 1 and ${MAX_PACKAGE_ICON_BYTES} bytes.`);
1987
+ if (!Array.isArray(asset.sizes) || 0 === asset.sizes.length) throw new Error(`TAP presentation asset ${asset.path} must declare at least one size.`);
1988
+ if (new Set(asset.sizes).size !== asset.sizes.length) throw new Error(`TAP presentation asset ${asset.path} declares duplicate sizes.`);
1989
+ const parsedSizes = asset.sizes.map(parsePresentationAssetSize);
1990
+ if (parsedSizes.some((size)=>void 0 === size)) throw new Error(`TAP presentation asset ${asset.path} sizes must be "any" or bounded WIDTHxHEIGHT values.`);
1991
+ const validSizes = parsedSizes.filter((size)=>void 0 !== size);
1992
+ if ([
1993
+ 'app-icon',
1994
+ 'publisher-icon',
1995
+ 'organization-icon'
1996
+ ].includes(asset.role) && validSizes.some((size)=>null !== size && size.width !== size.height)) throw new Error(`TAP icon presentation asset ${asset.path} must declare square sizes.`);
1997
+ if ('image/png' === asset.mediaType) {
1998
+ const intrinsicSize = validSizes[0];
1999
+ if (1 !== validSizes.length || null == intrinsicSize) throw new Error(`TAP PNG presentation asset ${asset.path} must declare one fixed intrinsic size.`);
2000
+ const decoded = validatePngIcon(asset.path, contents);
2001
+ if (decoded.width !== intrinsicSize.width || decoded.height !== intrinsicSize.height) throw new Error(`TAP PNG presentation asset ${asset.path} IHDR dimensions do not match its declared size.`);
2002
+ return;
2003
+ }
2004
+ if (validSizes.includes(null) && 1 !== validSizes.length) throw new Error(`TAP scalable presentation asset ${asset.path} cannot mix "any" with fixed sizes.`);
2005
+ validateSvgPresentationAsset(asset.path, contents);
2006
+ };
2007
+ const validatePackagePresentationGraph = (descriptor)=>{
2008
+ const assets = descriptor.presentation.assets ?? [];
2009
+ if (assets.length > MAX_PACKAGE_PRESENTATION_ASSETS) throw new Error(`TAP package presentation may declare at most ${MAX_PACKAGE_PRESENTATION_ASSETS} assets.`);
2010
+ const assetsByPath = new Map();
2011
+ for (const asset of assets){
2012
+ if (assetsByPath.has(asset.path)) throw new Error(`TAP presentation asset path ${asset.path} is declared more than once.`);
2013
+ assetsByPath.set(asset.path, asset);
2014
+ }
2015
+ const declaredPackageIcons = descriptor.presentation.iconAssets ?? [];
2016
+ const packageIcons = 0 === declaredPackageIcons.length ? assets.filter((asset)=>'app-icon' === asset.role).map((asset)=>asset.path) : declaredPackageIcons;
2017
+ if (packageIcons.length > MAX_PACKAGE_ICON_VARIANTS) throw new Error(`TAP package presentation.iconAssets may select at most ${MAX_PACKAGE_ICON_VARIANTS} parent-package icon variants.`);
2018
+ const selectedPackageIcons = new Set();
2019
+ for (const assetPath of packageIcons){
2020
+ if (selectedPackageIcons.has(assetPath)) throw new Error(`TAP package presentation.iconAssets selects icon asset ${assetPath} more than once.`);
2021
+ selectedPackageIcons.add(assetPath);
2022
+ const asset = assetsByPath.get(assetPath);
2023
+ if (!asset) throw new Error(`TAP package presentation.iconAssets selects undeclared icon asset ${assetPath}.`);
2024
+ if ('app-icon' !== asset.role) throw new Error(`TAP package presentation.iconAssets asset ${assetPath} must have role app-icon.`);
2025
+ }
2026
+ for (const contribution of descriptor.contributions ?? []){
2027
+ if ('ui.surface' !== contribution.kind) continue;
2028
+ const iconAssets = contribution.options?.iconAssets ?? [];
2029
+ if (iconAssets.length > MAX_PACKAGE_ICON_VARIANTS) throw new Error(`TAP UI surface ${contribution.id ?? '<unknown>'} may select at most ${MAX_PACKAGE_ICON_VARIANTS} icon variants.`);
2030
+ const selected = new Set();
2031
+ for (const assetPath of iconAssets){
2032
+ if (selected.has(assetPath)) throw new Error(`TAP UI surface ${contribution.id ?? '<unknown>'} selects icon asset ${assetPath} more than once.`);
2033
+ selected.add(assetPath);
2034
+ const asset = assetsByPath.get(assetPath);
2035
+ if (!asset) throw new Error(`TAP UI surface ${contribution.id ?? '<unknown>'} selects undeclared icon asset ${assetPath}.`);
2036
+ if ('app-icon' !== asset.role) throw new Error(`TAP UI surface ${contribution.id ?? '<unknown>'} icon asset ${assetPath} must have role app-icon.`);
2037
+ }
2038
+ }
2039
+ };
2040
+ const flattenFederationAssetPaths = (value)=>{
2041
+ if ('string' == typeof value) return [
2042
+ value
2043
+ ];
2044
+ if (Array.isArray(value)) return value.flatMap(flattenFederationAssetPaths);
2045
+ if (!isRecord(value)) return [];
2046
+ return Object.values(value).flatMap(flattenFederationAssetPaths);
2047
+ };
2048
+ const federationExposeAssetPaths = (manifest, exposeName)=>{
2049
+ if (!isRecord(manifest) || !Array.isArray(manifest.exposes)) throw new Error('Module Federation manifest has no exposes array.');
2050
+ const normalizedName = exposeName.replace(/^\.\//, '');
2051
+ const matches = manifest.exposes.filter((candidate)=>{
2052
+ if (!isRecord(candidate)) return false;
2053
+ const candidateName = 'string' == typeof candidate.name ? candidate.name : void 0;
2054
+ const candidateId = 'string' == typeof candidate.id ? candidate.id : '';
2055
+ return candidateName === normalizedName || candidateName === exposeName || candidateId.endsWith(`:${normalizedName}`);
2056
+ });
2057
+ if (1 !== matches.length || !isRecord(matches[0])) throw new Error(`Module Federation manifest must declare expose "${exposeName}" exactly once.`);
2058
+ const assets = [
2059
+ ...new Set(flattenFederationAssetPaths(matches[0].assets))
2060
+ ];
2061
+ if (0 === assets.length) throw new Error(`Module Federation expose "${exposeName}" resolved to an empty asset graph.`);
2062
+ return assets;
2063
+ };
2064
+ const integrityForAssetGraph = (assetNames, lock)=>{
2065
+ const graph = [
2066
+ ...new Set(assetNames)
2067
+ ].sort().flatMap((assetName)=>{
2068
+ const asset = lockedPackageAsset(lock, assetName);
2069
+ return asset ? [
2070
+ `${assetName}\0${asset.integrity}`
2071
+ ] : [];
2072
+ }).join('\n');
2073
+ if (0 === graph.length) throw new Error('TAP package expose resolved to an empty asset graph.');
2074
+ return sha256Integrity(graph);
2075
+ };
2076
+ const federationExposeKeys = (options)=>{
2077
+ if (!isRecord(options.exposes)) return [];
2078
+ return Object.keys(options.exposes).sort();
2079
+ };
2080
+ const packageBuildProfile = (packageTarget)=>{
2081
+ switch(packageTarget){
2082
+ case 'quickjs':
2083
+ return {
2084
+ rslibTarget: 'web',
2085
+ rspackTarget: 'webworker',
2086
+ federationTarget: 'web',
2087
+ conditionNames: [
2088
+ 'worker',
2089
+ 'import',
2090
+ 'module',
2091
+ 'default'
2092
+ ],
2093
+ aliases: {},
2094
+ quickJsConformance: true
2095
+ };
2096
+ case 'worker':
2097
+ return {
2098
+ rslibTarget: 'web',
2099
+ rspackTarget: 'webworker',
2100
+ federationTarget: 'web',
2101
+ conditionNames: [
2102
+ 'worker',
2103
+ 'browser',
2104
+ 'import',
2105
+ 'module',
2106
+ 'default'
2107
+ ],
2108
+ aliases: {},
2109
+ quickJsConformance: false
2110
+ };
2111
+ case 'node':
2112
+ case 'workflow-host':
2113
+ return {
2114
+ rslibTarget: 'node',
2115
+ federationTarget: 'node',
2116
+ conditionNames: [
2117
+ 'node',
2118
+ 'import',
2119
+ 'module',
2120
+ 'default'
2121
+ ],
2122
+ aliases: {},
2123
+ quickJsConformance: false
2124
+ };
2125
+ case 'desktop':
2126
+ case 'mobile':
2127
+ return {
2128
+ rslibTarget: 'web',
2129
+ federationTarget: 'web',
2130
+ conditionNames: MINIAPP_BROWSER_CONDITION_NAMES,
2131
+ aliases: MINIAPP_CLIENT_ALIASES,
2132
+ quickJsConformance: false
2133
+ };
2134
+ }
2135
+ };
2136
+ const expectedRuntimeForDedicatedTarget = (packageTarget)=>{
2137
+ switch(packageTarget){
2138
+ case 'quickjs':
2139
+ return 'quickjs';
2140
+ case 'worker':
2141
+ return 'worker';
2142
+ case 'node':
2143
+ return 'node';
2144
+ case 'workflow-host':
2145
+ return 'workflow-host';
2146
+ case 'desktop':
2147
+ case 'mobile':
2148
+ return;
2149
+ }
2150
+ };
2151
+ const stripJavaScriptStringsAndComments = (source)=>{
2152
+ let output = '';
2153
+ let index = 0;
2154
+ while(index < source.length){
2155
+ const character = source[index];
2156
+ const next = source[index + 1];
2157
+ if ('/' === character && '/' === next) {
2158
+ index += 2;
2159
+ while(index < source.length && '\n' !== source[index])index += 1;
2160
+ output += '\n';
2161
+ continue;
2162
+ }
2163
+ if ('/' === character && '*' === next) {
2164
+ index += 2;
2165
+ while(index < source.length && !('*' === source[index] && '/' === source[index + 1])){
2166
+ output += '\n' === source[index] ? '\n' : ' ';
2167
+ index += 1;
2168
+ }
2169
+ index += 2;
2170
+ continue;
2171
+ }
2172
+ if ('"' === character || "'" === character || '`' === character) {
2173
+ const quote = character;
2174
+ output += ' ';
2175
+ index += 1;
2176
+ while(index < source.length){
2177
+ if ('\\' === source[index]) {
2178
+ index += 2;
2179
+ continue;
2180
+ }
2181
+ if (source[index] === quote) {
2182
+ index += 1;
2183
+ break;
2184
+ }
2185
+ output += '\n' === source[index] ? '\n' : ' ';
2186
+ index += 1;
2187
+ }
2188
+ continue;
2189
+ }
2190
+ output += character;
2191
+ index += 1;
2192
+ }
2193
+ return output;
2194
+ };
2195
+ const validateQuickJsCompilation = (compilation, exposeAssetNames)=>{
2196
+ for (const [assetName, asset] of Object.entries(compilation.assets)){
2197
+ if (!exposeAssetNames.has(assetName) || !/\.(?:m?js)$/.test(assetName) || assetName.endsWith('.js.map')) continue;
2198
+ const source = asset.source().toString();
2199
+ const executableSource = stripJavaScriptStringsAndComments(source);
2200
+ const forbiddenGlobal = QUICKJS_FORBIDDEN_GLOBALS.find((name)=>{
2201
+ const withoutFeatureDetection = executableSource.replace(new RegExp(`\\btypeof\\s+${name.replaceAll('$', '\\$&')}\\b`, 'g'), '');
2202
+ return new RegExp(`(^|[^A-Za-z0-9_$])${name.replaceAll('$', '\\$&')}([^A-Za-z0-9_$]|$)`).test(withoutFeatureDetection);
2203
+ });
2204
+ if (forbiddenGlobal) {
2205
+ const matchIndex = executableSource.search(new RegExp(`\\b${forbiddenGlobal.replaceAll('$', '\\$&')}\\b`));
2206
+ const context = executableSource.slice(Math.max(0, matchIndex - 80), matchIndex + 120).replaceAll(/\s+/g, ' ').trim();
2207
+ throw new Error(`QuickJS package asset ${assetName} references forbidden ambient global "${forbiddenGlobal}" near "${context}". Use the TAP SDK or a target-specific expose instead.`);
2208
+ }
2209
+ if (/(?:\bfrom\s*|\bimport\s*\()\s*["'](?:node:|https?:|file:|\/)/.test(executableSource)) throw new Error(`QuickJS package asset ${assetName} contains an ambient module import. All imports must resolve inside the locked package graph.`);
2210
+ }
2211
+ };
2212
+ const validateFederationDescriptorTarget = (descriptor, packageTarget, federation)=>{
2213
+ const target = descriptor.targets[packageTarget];
2214
+ if (!target) throw new Error(`TAP package descriptor does not declare the ${packageTarget} target.`);
2215
+ if (target.remoteName !== federation.name) throw new Error(`TAP package target remoteName "${target.remoteName}" does not match Module Federation name "${String(federation.name)}".`);
2216
+ const configuredLibraryType = 'object' == typeof federation.library && null !== federation.library ? String(federation.library.type) : 'module';
2217
+ if (target.libraryType !== configuredLibraryType) throw new Error(`TAP package target libraryType "${target.libraryType}" does not match Module Federation library type "${configuredLibraryType}".`);
2218
+ const expectedRuntime = expectedRuntimeForDedicatedTarget(packageTarget);
2219
+ if (expectedRuntime) {
2220
+ for (const [exposeName, expose] of Object.entries(target.exposes))if (expose.runtime !== expectedRuntime) throw new Error(`TAP package ${packageTarget} expose "${exposeName}" must declare runtime "${expectedRuntime}", received "${expose.runtime}".`);
2221
+ }
2222
+ const configuredExposes = federationExposeKeys(federation);
2223
+ const descriptorExposes = Object.keys(target.exposes).sort();
2224
+ if (0 === configuredExposes.length || configuredExposes.join('\0') !== descriptorExposes.join('\0')) throw new Error(`TAP package ${packageTarget} exposes must exactly match the Module Federation exposes. Descriptor: ${descriptorExposes.join(', ')}; build: ${configuredExposes.join(', ')}.`);
2225
+ return target;
2226
+ };
2227
+ const assertFederationRemoteEntryType = (value, libraryType, assetPath)=>{
2228
+ if (!isRecord(value)) throw new Error(`${assetPath} must contain a JSON object.`);
2229
+ const metadata = value.metaData;
2230
+ if (!isRecord(metadata)) throw new Error(`${assetPath} is missing Module Federation metadata.`);
2231
+ const remoteEntry = metadata.remoteEntry;
2232
+ if (!isRecord(remoteEntry)) throw new Error(`${assetPath} is missing remote entry metadata.`);
2233
+ if (remoteEntry.type !== libraryType) throw new Error(`${assetPath} reports remote entry type "${String(remoteEntry.type)}" but the package target requires "${libraryType}". Use a Module Federation release that preserves the configured library type.`);
2234
+ };
2235
+ const setupFederatedTapPackage = (api, options, manifestPath)=>{
2236
+ const packageTarget = options.packageTarget ?? DEFAULT_PACKAGE_TARGET;
2237
+ const targetPaths = packageTargetOutputPaths(packageTarget);
2238
+ const packageLockPath = targetPaths.lock;
2239
+ api.modifyRsbuildConfig(async (config)=>{
2240
+ const descriptor = await readPackageManifest(manifestPath);
2241
+ validateFederationDescriptorTarget(descriptor, packageTarget, options.federation);
2242
+ config.dev ??= {};
2243
+ config.dev.writeToDisk = true;
2244
+ config.output ??= {};
2245
+ config.output.distPath ??= {};
2246
+ if ('object' == typeof config.output.distPath) config.output.distPath.root ??= 'dist';
2247
+ });
2248
+ api.processAssets({
2249
+ stage: 'additional'
2250
+ }, async ({ compilation, sources })=>{
2251
+ const descriptor = await readPackageManifest(manifestPath);
2252
+ const target = validateFederationDescriptorTarget(descriptor, packageTarget, options.federation);
2253
+ if (Object.values(target.exposes).some((expose)=>'webview' === expose.runtime)) for (const [assetPath, contents] of [
2254
+ [
2255
+ TAP_FEDERATED_SURFACE_HTML_PATH,
2256
+ TAP_FEDERATED_SURFACE_HTML
2257
+ ],
2258
+ [
2259
+ TAP_FEDERATED_SURFACE_RUNTIME_PATH,
2260
+ TAP_FEDERATED_SURFACE_RUNTIME
2261
+ ]
2262
+ ]){
2263
+ if (compilation.getAsset(assetPath)) throw new Error(`TAP package output path ${assetPath} is reserved for the isolated Federation surface host.`);
2264
+ compilation.emitAsset(assetPath, new sources.RawSource(contents));
2265
+ }
2266
+ validatePackagePresentationGraph(descriptor);
2267
+ for (const asset of descriptor.presentation.assets ?? []){
2268
+ if (!isSafePackageAssetPath(asset.path)) throw new Error(`TAP presentation asset path "${asset.path}" must be package-relative and cannot traverse directories.`);
2269
+ const sourcePath = __rspack_external_node_path_806ed179["default"].resolve(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), asset.path);
2270
+ const contents = await __rspack_external_node_fs_promises_3b710708["default"].readFile(sourcePath);
2271
+ validatePackagePresentationAsset(asset, contents);
2272
+ compilation.fileDependencies.add(sourcePath);
2273
+ if (compilation.getAsset(asset.path)) compilation.updateAsset(asset.path, new sources.RawSource(contents));
2274
+ else compilation.emitAsset(asset.path, new sources.RawSource(contents));
2275
+ }
2276
+ });
2277
+ api.processAssets({
2278
+ stage: 'report'
2279
+ }, async ({ compilation, sources })=>{
2280
+ const descriptor = await readPackageManifest(manifestPath);
2281
+ const target = validateFederationDescriptorTarget(descriptor, packageTarget, options.federation);
2282
+ const descriptorOutputPath = __rspack_external_node_path_806ed179["default"].basename(manifestPath);
2283
+ const remoteEntryPath = 'string' == typeof options.federation.filename ? options.federation.filename : targetPaths.remoteEntry;
2284
+ const federationManifestPath = targetPaths.manifest;
2285
+ if (!isSafePackageAssetPath(remoteEntryPath)) throw new Error(`Module Federation remote entry "${remoteEntryPath}" must be a safe relative output path.`);
2286
+ if (!isSafePackageAssetPath(federationManifestPath)) throw new Error(`Module Federation manifest "${federationManifestPath}" must be a safe relative output path.`);
2287
+ const remoteEntry = compilation.getAsset(remoteEntryPath)?.source;
2288
+ const federationManifestAsset = compilation.getAsset(federationManifestPath)?.source;
2289
+ if (!remoteEntry) throw new Error(`Module Federation did not emit the configured remote entry ${remoteEntryPath}.`);
2290
+ if (!federationManifestAsset) throw new Error(`Module Federation did not emit ${federationManifestPath}; TAP packages require an MF manifest.`);
2291
+ const remoteEntryContents = toBuffer(remoteEntry.source());
2292
+ if ('module' === target.libraryType && !/\bexport\s*\{/.test(remoteEntryContents.toString('utf8'))) throw new Error(`Module Federation emitted ${remoteEntryPath} without an ESM export for a module target.`);
2293
+ const federationManifest = JSON.parse(toBuffer(federationManifestAsset.source()).toString('utf8'));
2294
+ assertFederationRemoteEntryType(federationManifest, target.libraryType, federationManifestPath);
2295
+ const federationStatsAsset = compilation.getAsset(targetPaths.stats)?.source;
2296
+ if (federationStatsAsset) {
2297
+ const federationStats = JSON.parse(toBuffer(federationStatsAsset.source()).toString('utf8'));
2298
+ assertFederationRemoteEntryType(federationStats, target.libraryType, targetPaths.stats);
2299
+ }
2300
+ if ('quickjs' === packageTarget) {
2301
+ const exposeAssetNames = new Set(Object.keys(target.exposes).flatMap((exposeName)=>federationExposeAssetPaths(federationManifest, exposeName)));
2302
+ validateQuickJsCompilation(compilation, exposeAssetNames);
2303
+ }
2304
+ const lockAssetEntries = [];
2305
+ for (const assetName of Object.keys(compilation.assets).sort()){
2306
+ if (assetName === descriptorOutputPath || assetName === packageLockPath) continue;
2307
+ const compilationAsset = compilation.getAsset(assetName)?.source;
2308
+ if (!compilationAsset) throw new Error(`TAP package output asset ${assetName} disappeared during lock generation.`);
2309
+ const contents = toBuffer(compilationAsset.source());
2310
+ lockAssetEntries.push([
2311
+ assetName,
2312
+ {
2313
+ bytes: contents.byteLength,
2314
+ integrity: sha256Integrity(contents)
2315
+ }
2316
+ ]);
2317
+ }
2318
+ const lock = {
2319
+ lockVersion: 1,
2320
+ packageId: descriptor.package.packageId,
2321
+ releaseId: descriptor.release.releaseId,
2322
+ target: packageTarget,
2323
+ assets: Object.fromEntries(lockAssetEntries)
2324
+ };
2325
+ const lockContents = `${JSON.stringify(lock, null, 2)}\n`;
2326
+ const lockIntegrity = sha256Integrity(lockContents);
2327
+ target.remoteEntry = remoteEntryPath;
2328
+ const lockedRemoteEntry = lockedPackageAsset(lock, remoteEntryPath);
2329
+ const lockedFederationManifest = lockedPackageAsset(lock, federationManifestPath);
2330
+ if (!lockedRemoteEntry || !lockedFederationManifest) throw new Error('TAP package lock is missing required Federation assets.');
2331
+ target.remoteEntryIntegrity = lockedRemoteEntry.integrity;
2332
+ target.manifest = federationManifestPath;
2333
+ target.manifestIntegrity = lockedFederationManifest.integrity;
2334
+ target.assetLock = packageLockPath;
2335
+ target.assetLockIntegrity = lockIntegrity;
2336
+ for (const [exposeName, expose] of Object.entries(target.exposes))expose.integrity = integrityForAssetGraph([
2337
+ remoteEntryPath,
2338
+ federationManifestPath,
2339
+ ...federationExposeAssetPaths(federationManifest, exposeName)
2340
+ ], lock);
2341
+ for (const asset of descriptor.presentation.assets ?? []){
2342
+ const lockedAsset = lockedPackageAsset(lock, asset.path);
2343
+ if (!lockedAsset) throw new Error(`TAP presentation asset ${asset.path} was not emitted into the package graph.`);
2344
+ asset.integrity = lockedAsset.integrity;
2345
+ }
2346
+ descriptor.release.contentDigest = lockIntegrity;
2347
+ const descriptorContents = `${JSON.stringify(descriptor, null, 2)}\n`;
2348
+ if (compilation.getAsset(packageLockPath)) compilation.updateAsset(packageLockPath, new sources.RawSource(lockContents));
2349
+ else compilation.emitAsset(packageLockPath, new sources.RawSource(lockContents));
2350
+ if (compilation.getAsset(descriptorOutputPath)) compilation.updateAsset(descriptorOutputPath, new sources.RawSource(descriptorContents));
2351
+ else compilation.emitAsset(descriptorOutputPath, new sources.RawSource(descriptorContents));
2352
+ });
2353
+ };
2354
+ const pluginTap = (options = {})=>({
2355
+ name: PLUGIN_NAME,
2356
+ setup (api) {
2357
+ const manifestPath = __rspack_external_node_path_806ed179["default"].resolve(api.context.rootPath, options.manifest ?? DEFAULT_MANIFEST_PATH);
2358
+ if (options.federation) return void setupFederatedTapPackage(api, options, manifestPath);
2359
+ const entryName = options.entryName ?? DEFAULT_ENTRY_NAME;
2360
+ const outputPath = options.output ?? `${entryName}.js`;
2361
+ let isRemoteManifestEntry = false;
2362
+ let htmlEntrypoints = [];
2363
+ let emittedManifestEntry;
2364
+ let includeReactGlobal = false;
2365
+ const jsEntryOutputPaths = new Map([
2366
+ [
2367
+ entryName,
2368
+ toVersionedJsFilename(outputPath)
2369
+ ]
2370
+ ]);
2371
+ const cssEntryOutputPaths = new Map();
2372
+ api.modifyEnvironmentConfig((config)=>{
2373
+ config.source.define = {
2374
+ ...MINIAPP_BROWSER_DEFINES,
2375
+ ...config.source.define
2376
+ };
2377
+ });
2378
+ api.modifyRsbuildConfig(async (config)=>{
2379
+ const manifest = await readBundleManifest(manifestPath);
2380
+ includeReactGlobal = packageDeclaresDependency(await readPackageJson(api.context.rootPath), 'react');
2381
+ isRemoteManifestEntry = sourceIsUrl(manifest.entry);
2382
+ const bundlerEntry = resolveBundlerEntry(manifestPath, manifest.entry);
2383
+ htmlEntrypoints = await discoverHtmlEntrypoints(manifestPath, bundlerEntry);
2384
+ for (const htmlEntrypoint of htmlEntrypoints){
2385
+ for (const script of htmlEntrypoint.scripts){
2386
+ const relativeScript = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), script.source));
2387
+ jsEntryOutputPaths.set(toHtmlScriptEntryName(relativeScript), toVersionedJsFilename(script.output));
2388
+ }
2389
+ for (const stylesheet of htmlEntrypoint.stylesheets){
2390
+ const relativeStylesheet = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), stylesheet.source));
2391
+ cssEntryOutputPaths.set(toHtmlStylesheetEntryName(relativeStylesheet), toVersionedJsFilename(stylesheet.output));
2392
+ }
2393
+ }
2394
+ config.dev ??= {};
2395
+ config.dev.hmr = false;
2396
+ config.dev.liveReload = false;
2397
+ config.dev.writeToDisk = true;
2398
+ config.source ??= {};
2399
+ config.source.define ??= {};
2400
+ config.source.define['process.env.NODE_ENV'] ??= JSON.stringify('production');
2401
+ config.source.entry ??= {};
2402
+ config.source.entry[entryName] = {
2403
+ import: includeReactGlobal ? [
2404
+ REACT_GLOBAL_ENTRY,
2405
+ bundlerEntry
2406
+ ] : bundlerEntry,
2407
+ html: false
2408
+ };
2409
+ for (const htmlEntrypoint of htmlEntrypoints){
2410
+ for (const script of htmlEntrypoint.scripts){
2411
+ const relativeScript = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), script.source));
2412
+ config.source.entry[toHtmlScriptEntryName(relativeScript)] = {
2413
+ import: includeReactGlobal ? [
2414
+ REACT_GLOBAL_ENTRY,
2415
+ script.source
2416
+ ] : script.source,
2417
+ html: false
2418
+ };
2419
+ }
2420
+ for (const stylesheet of htmlEntrypoint.stylesheets){
2421
+ const relativeStylesheet = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), stylesheet.source));
2422
+ config.source.entry[toHtmlStylesheetEntryName(relativeStylesheet)] = {
2423
+ import: toCssEntryLoaderRequest(stylesheet.source),
2424
+ html: false
2425
+ };
2426
+ }
2427
+ }
2428
+ config.output ??= {};
2429
+ config.output.filenameHash ??= 'contenthash:8';
2430
+ config.output.minify ??= {
2431
+ js: true,
2432
+ css: true
2433
+ };
2434
+ config.output.sourceMap ??= true;
2435
+ config.output.filename ??= {};
2436
+ config.output.filename.js = ({ chunk })=>chunk?.name && jsEntryOutputPaths.has(chunk.name) ? jsEntryOutputPaths.get(chunk.name) ?? '[name].js' : '[name].js';
2437
+ config.output.filename.css = ({ chunk })=>chunk?.name && cssEntryOutputPaths.has(chunk.name) ? cssEntryOutputPaths.get(chunk.name) ?? '[name].css' : '[name].css';
2438
+ config.output.distPath ??= {};
2439
+ if ('object' == typeof config.output.distPath) {
2440
+ config.output.distPath.root ??= 'dist';
2441
+ config.output.distPath.js = './';
2442
+ config.output.distPath.css = './';
2443
+ }
2444
+ config.performance ??= {};
2445
+ config.performance.chunkSplit = {
2446
+ strategy: 'all-in-one'
2447
+ };
2448
+ });
2449
+ api.modifyRspackConfig((config)=>{
2450
+ configureMiniappRspack(config);
2451
+ });
2452
+ api.processAssets({
2453
+ stage: 'optimize-hash'
2454
+ }, async ({ assets, compilation, sources })=>{
2455
+ const entryFile = getEntrypointJsFile(compilation, entryName, outputPath);
2456
+ const manifest = await readBundleManifest(manifestPath);
2457
+ const manifestEntry = isRemoteManifestEntry ? manifest.entry : entryFile ?? outputPath;
2458
+ emittedManifestEntry = isRemoteManifestEntry || 'string' != typeof manifestEntry ? void 0 : manifestEntry;
2459
+ const nextManifest = {
2460
+ ...manifest,
2461
+ entry: manifestEntry
2462
+ };
2463
+ const manifestOutputPath = __rspack_external_node_path_806ed179["default"].basename(manifestPath);
2464
+ const manifestContents = `${JSON.stringify(nextManifest, null, 2)}\n`;
2465
+ if (assets[manifestOutputPath]) compilation.updateAsset(manifestOutputPath, new sources.RawSource(manifestContents));
2466
+ else compilation.emitAsset(manifestOutputPath, new sources.RawSource(manifestContents));
2467
+ const htmlAssetRenames = new Map();
2468
+ const stylesheetAssets = new Map();
2469
+ await Promise.all(htmlEntrypoints.flatMap((htmlEntrypoint)=>htmlEntrypoint.stylesheets.map(async (stylesheet)=>{
2470
+ const relativeStylesheet = toPosixPath(__rspack_external_node_path_806ed179["default"].relative(__rspack_external_node_path_806ed179["default"].dirname(manifestPath), stylesheet.source));
2471
+ const entry = toHtmlStylesheetEntryName(relativeStylesheet);
2472
+ const outputPath = cssEntryOutputPaths.get(entry) ?? `${entry}.css`;
2473
+ if (getEntrypointCssFile(compilation, entry, outputPath)) return;
2474
+ const css = await processCssFile(api.context.rootPath, stylesheet.source);
2475
+ const fileName = toVersionedAssetPath(stylesheet.output, css);
2476
+ compilation.emitAsset(fileName, new sources.RawSource(css));
2477
+ stylesheetAssets.set(entry, fileName);
2478
+ })));
2479
+ for (const [fileName, asset] of Object.entries(assets)){
2480
+ if (!fileName.endsWith('.html')) continue;
2481
+ const source = asset.source().toString();
2482
+ const withVersionedScripts = source.replace(HTML_SCRIPT_TOKEN_PATTERN, (token, scriptEntryName)=>{
2483
+ const scriptOutputPath = jsEntryOutputPaths.get(scriptEntryName) ?? `${scriptEntryName}.js`;
2484
+ return getEntrypointJsFile(compilation, scriptEntryName, scriptOutputPath) ?? token;
2485
+ });
2486
+ const withVersionedAssets = withVersionedScripts.replace(HTML_STYLESHEET_TOKEN_PATTERN, (token, stylesheetEntryName)=>{
2487
+ const stylesheetOutputPath = cssEntryOutputPaths.get(stylesheetEntryName) ?? `${stylesheetEntryName}.css`;
2488
+ return getEntrypointCssFile(compilation, stylesheetEntryName, stylesheetOutputPath) ?? stylesheetAssets.get(stylesheetEntryName) ?? token;
2489
+ });
2490
+ const minifiedHtml = minifyHtml(withVersionedAssets);
2491
+ const nextFileName = toVersionedAssetPath(fileName, minifiedHtml);
2492
+ if (nextFileName !== fileName) {
2493
+ compilation.deleteAsset(fileName);
2494
+ compilation.emitAsset(nextFileName, new sources.RawSource(minifiedHtml));
2495
+ htmlAssetRenames.set(fileName, nextFileName);
2496
+ } else compilation.updateAsset(fileName, new sources.RawSource(minifiedHtml));
2497
+ }
2498
+ if (0 === htmlAssetRenames.size) {
2499
+ if (!isRemoteManifestEntry) inlineEntrypointImports(compilation, sources, jsEntryOutputPaths);
2500
+ return;
2501
+ }
2502
+ for (const [fileName, asset] of Object.entries(compilation.assets)){
2503
+ if (!fileName.endsWith('.js')) continue;
2504
+ let source = asset.source().toString();
2505
+ let changed = false;
2506
+ for (const [previousFileName, nextFileName] of htmlAssetRenames)if (source.includes(previousFileName)) {
2507
+ source = source.split(previousFileName).join(nextFileName);
2508
+ changed = true;
2509
+ }
2510
+ if (changed) compilation.updateAsset(fileName, new sources.RawSource(source));
2511
+ }
2512
+ if (!isRemoteManifestEntry) inlineEntrypointImports(compilation, sources, jsEntryOutputPaths);
2513
+ });
2514
+ api.modifyBundlerChain((chain)=>{
2515
+ chain.module.rule(`${PLUGIN_NAME}-html-entrypoint`).test(/\.html$/).type("javascript/auto").use(`${PLUGIN_NAME}-html-loader`).loader(toHtmlLoaderRequest(manifestPath));
2516
+ chain.optimization.runtimeChunk('single');
2517
+ chain.optimization.splitChunks(false);
2518
+ chain.optimization.usedExports(false);
2519
+ chain.optimization.concatenateModules(false);
2520
+ chain.plugin(`${PLUGIN_NAME}-browser-defines`).use(__rspack_external__rsbuild_core_3f0eaefe.rspack.DefinePlugin, [
2521
+ MINIAPP_BROWSER_DEFINES
2522
+ ]);
2523
+ chain.output.module(true).library({
2524
+ type: 'module'
2525
+ }).chunkFormat('module').chunkLoading('import');
2526
+ chain.output.set('asyncChunks', true);
2527
+ chain.resolve.conditionNames.clear().merge(MINIAPP_BROWSER_CONDITION_NAMES);
2528
+ for (const [request, replacement] of Object.entries(MINIAPP_CLIENT_ALIASES))chain.resolve.alias.set(request, replacement);
2529
+ chain.module.parser.merge({
2530
+ asset: {
2531
+ dataUrlCondition: {
2532
+ maxSize: 1 / 0
2533
+ }
2534
+ }
2535
+ });
2536
+ chain.experiments({
2537
+ ...chain.get('experiments'),
2538
+ outputModule: true
2539
+ });
2540
+ chain.plugin(`${PLUGIN_NAME}-write-to-disk`).use(class {
2541
+ apply(compiler) {
2542
+ let previousAssets = new Map();
2543
+ const snapshotOutput = async ()=>{
2544
+ previousAssets = await snapshotOutputAssets(compiler.outputPath);
2545
+ };
2546
+ compiler.hooks.beforeRun.tapPromise(`${PLUGIN_NAME}-snapshot`, snapshotOutput);
2547
+ compiler.hooks.watchRun.tapPromise(`${PLUGIN_NAME}-snapshot`, snapshotOutput);
2548
+ compiler.hooks.assetEmitted.tapPromise(`${PLUGIN_NAME}-write-to-disk`, async (file, info)=>{
2549
+ const filePath = __rspack_external_node_path_806ed179["default"].join(compiler.outputPath, file);
2550
+ await writeFileIfChanged(filePath, info.content);
2551
+ const previous = previousAssets.get(file);
2552
+ if (previous?.contents.equals(toBuffer(info.content))) await __rspack_external_node_fs_promises_3b710708["default"].utimes(filePath, previous.mtimeMs / 1000, previous.mtimeMs / 1000);
2553
+ });
2554
+ compiler.hooks.done.tapPromise(`${PLUGIN_NAME}-restore-mtime`, async ()=>{
2555
+ await Promise.all([
2556
+ ...previousAssets
2557
+ ].map(async ([file, previous])=>{
2558
+ const filePath = __rspack_external_node_path_806ed179["default"].join(compiler.outputPath, file);
2559
+ try {
2560
+ if ((await __rspack_external_node_fs_promises_3b710708["default"].readFile(filePath)).equals(previous.contents)) await __rspack_external_node_fs_promises_3b710708["default"].utimes(filePath, previous.mtimeMs / 1000, previous.mtimeMs / 1000);
2561
+ } catch (error) {
2562
+ if ('ENOENT' !== error.code) throw error;
2563
+ }
2564
+ }));
2565
+ if (emittedManifestEntry) await inlineQuickJsEntrypointOnDisk(compiler.outputPath, emittedManifestEntry);
2566
+ await rewriteChunkRuntimeIdsOnDisk(compiler.outputPath);
2567
+ });
2568
+ }
2569
+ });
2570
+ });
2571
+ }
2572
+ });
2573
+ const tapLib = (options = {})=>{
2574
+ const packageTarget = options.packageTarget ?? DEFAULT_PACKAGE_TARGET;
2575
+ const profile = packageBuildProfile(packageTarget);
2576
+ const targetDirectory = packageTargetDirectory(packageTarget);
2577
+ const federation = options.federation ? normalizeFederationOptions(packageTarget, options.federation) : void 0;
2578
+ const normalizedOptions = federation ? {
2579
+ ...options,
2580
+ federation
2581
+ } : options;
2582
+ return {
2583
+ format: federation ? 'mf' : 'esm',
2584
+ bundle: true,
2585
+ autoExternal: false,
2586
+ dts: false,
2587
+ output: {
2588
+ target: profile.rslibTarget,
2589
+ ...federation ? {
2590
+ distPath: {
2591
+ ...options.packageOutputRoot ? {
2592
+ root: options.packageOutputRoot
2593
+ } : {},
2594
+ js: targetDirectory,
2595
+ jsAsync: targetDirectory,
2596
+ css: targetDirectory,
2597
+ cssAsync: targetDirectory,
2598
+ svg: `${targetDirectory}/assets`,
2599
+ font: `${targetDirectory}/assets`,
2600
+ wasm: `${targetDirectory}/assets`,
2601
+ image: `${targetDirectory}/assets`,
2602
+ media: `${targetDirectory}/assets`,
2603
+ assets: `${targetDirectory}/assets`
2604
+ }
2605
+ } : {}
2606
+ },
2607
+ tools: {
2608
+ rspack: {
2609
+ ...profile.rspackTarget ? {
2610
+ target: profile.rspackTarget
2611
+ } : {},
2612
+ optimization: {
2613
+ runtimeChunk: 'single',
2614
+ splitChunks: false,
2615
+ usedExports: false,
2616
+ concatenateModules: false
2617
+ },
2618
+ plugins: [
2619
+ new __rspack_external__rsbuild_core_3f0eaefe.rspack.DefinePlugin(MINIAPP_BROWSER_DEFINES)
2620
+ ],
2621
+ resolve: {
2622
+ alias: profile.aliases,
2623
+ conditionNames: profile.conditionNames
2624
+ },
2625
+ output: {
2626
+ asyncChunks: true,
2627
+ ...profile.quickJsConformance ? {
2628
+ chunkFormat: 'module',
2629
+ chunkLoading: 'import',
2630
+ globalObject: 'globalThis',
2631
+ module: true
2632
+ } : {}
2633
+ },
2634
+ module: {
2635
+ parser: {
2636
+ asset: {
2637
+ dataUrlCondition: {
2638
+ maxSize: 1 / 0
2639
+ }
2640
+ }
2641
+ }
2642
+ }
2643
+ }
2644
+ },
2645
+ plugins: [
2646
+ pluginTap(normalizedOptions),
2647
+ ...federation ? [
2648
+ (0, __rspack_external__module_federation_rsbuild_plugin_99e96cf9.pluginModuleFederation)(federation, {
2649
+ target: profile.federationTarget
2650
+ })
2651
+ ] : []
2652
+ ]
2653
+ };
2654
+ };
2655
+ export { assembleTapPackage, assertPortableTapPackageArtifacts, pluginTap, tapLib };