@coasys/ad4m-connect 0.12.1-dev → 0.13.0-postmessage-ws-proxy.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.
Files changed (61) hide show
  1. package/dist/PostMessageWebSocket.d.ts +26 -0
  2. package/dist/components/icons/CheckCircleIcon.d.ts +1 -0
  3. package/dist/components/icons/MapPinIcon.d.ts +1 -0
  4. package/dist/components/icons/TickIcon.d.ts +1 -0
  5. package/dist/components/icons/index.d.ts +1 -0
  6. package/dist/components/shared/Ad4mLogo.d.ts +1 -0
  7. package/dist/components/shared/AppLogo.d.ts +1 -0
  8. package/dist/components/shared/Header.d.ts +1 -0
  9. package/dist/components/shared/Logo.d.ts +1 -0
  10. package/dist/components/states/ErrorState.d.ts +6 -0
  11. package/dist/components/views/ConnectionOverview.d.ts +22 -0
  12. package/dist/components/views/HostBrowser.d.ts +0 -1
  13. package/dist/components/views/HostDetail.d.ts +2 -1
  14. package/dist/components/views/Hosting.d.ts +22 -0
  15. package/dist/components/views/LocalAuthentication.d.ts +2 -1
  16. package/dist/components/views/LoggedInDashboard.d.ts +20 -2
  17. package/dist/components/views/MultiUserAuth.d.ts +26 -0
  18. package/dist/components/views/RemoteAuthentication.d.ts +3 -1
  19. package/dist/components/views/RemoteConnection.d.ts +19 -0
  20. package/dist/components/views/RequestCapability.d.ts +16 -0
  21. package/dist/components/views/ScanQRCode.d.ts +14 -0
  22. package/dist/components/views/Settings.d.ts +19 -0
  23. package/dist/components/views/Start.d.ts +19 -0
  24. package/dist/components/views/old/Hosting.d.ts +22 -0
  25. package/dist/components/views/old/MultiUserAuth.d.ts +26 -0
  26. package/dist/components/views/old/RemoteConnection.d.ts +19 -0
  27. package/dist/components/views/old/RequestCapability.d.ts +16 -0
  28. package/dist/components/views/old/ScanQRCode.d.ts +14 -0
  29. package/dist/components/views/old/Settings.d.ts +19 -0
  30. package/dist/components/views/old/Start.d.ts +19 -0
  31. package/dist/core.d.ts +10 -6
  32. package/dist/core.js +11323 -1582
  33. package/dist/core.js.map +7 -0
  34. package/dist/index.js +14040 -1931
  35. package/dist/index.js.map +7 -0
  36. package/dist/old/components/InvalidToken.d.ts +0 -0
  37. package/dist/old/components/VerifyCode.d.ts +0 -0
  38. package/dist/old/core.d.ts +0 -0
  39. package/dist/old/electron.d.ts +0 -0
  40. package/dist/old/state/ConnectState.d.ts +0 -0
  41. package/dist/old/state/index.d.ts +0 -0
  42. package/dist/old/utils.d.ts +0 -0
  43. package/dist/old/views/Hosting.d.ts +0 -0
  44. package/dist/old/views/MultiUserAuth.d.ts +0 -0
  45. package/dist/old/views/RemoteConnection.d.ts +0 -0
  46. package/dist/old/views/RequestCapability.d.ts +0 -0
  47. package/dist/old/views/ScanQRCode.d.ts +0 -0
  48. package/dist/old/views/Settings.d.ts +0 -0
  49. package/dist/old/views/Start.d.ts +0 -0
  50. package/dist/old/web.d.ts +0 -0
  51. package/dist/services/hostIndex.d.ts +2 -2
  52. package/dist/state/ConnectState.d.ts +101 -0
  53. package/dist/state/index.d.ts +2 -0
  54. package/dist/types.d.ts +13 -0
  55. package/dist/utils.d.ts +4 -1
  56. package/dist/utils.js +99 -1
  57. package/dist/utils.js.map +7 -0
  58. package/dist/web.d.ts +4 -0
  59. package/dist/web.js +12736 -1864
  60. package/dist/web.js.map +7 -0
  61. package/package.json +9 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/utils.ts", "../src/PostMessageWebSocket.ts", "../../core/lib/index.js", "../../node_modules/.pnpm/auto-bind@5.0.1/node_modules/auto-bind/index.js", "../src/services/hostIndex.ts", "../src/core.ts"],
4
+ "sourcesContent": ["//@ts-ignore\nimport { version } from \"../../package.json\";\n\nexport function isEmbedded(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top;\n}\n\nfunction localStorageSupported(): boolean {\n try {\n localStorage.setItem(\"test\", \"\");\n localStorage.removeItem(\"test\");\n } catch (e) {\n return false;\n }\n return true;\n}\n\nexport function setLocal(key: string, value: string): void {\n if (localStorageSupported()) localStorage.setItem(`${version}/${key}`, value);\n}\n\nexport function getLocal(key: string): string | null {\n if (localStorageSupported()) return localStorage.getItem(`${version}/${key}`);\n return null;\n}\n\nexport function removeLocal(key: string): void {\n if (localStorageSupported()) localStorage.removeItem(`${version}/${key}`);\n}\n\n/** Convert a WebSocket URL to an HTTP base URL. */\nexport function wsUrlToHttpBase(wsUrl: string): string {\n return wsUrl.replace(/^ws(s?):\\/\\//, (_, s) => `http${s}://`);\n}\n\n/** Check that the AD4M executor is reachable at the given HTTP base URL. */\nexport async function checkConnection(baseUrl: string, timeout = 10000): Promise<void> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await fetch(`${baseUrl}/health`, { signal: controller.signal });\n if (!res.ok) throw new Error(`Health check returned ${res.status}`);\n const body = await res.json();\n if (body?.status !== 'ok') throw new Error('Not an AD4M executor');\n } catch (e: any) {\n if (e.name === 'AbortError') throw new Error('Connection timed out');\n throw e;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Extract up to 2 initials from a name (first letter of first two words) */\nexport function getInitials(name: string): string {\n const clean = name.trim();\n if (!clean) return \"\";\n const words = clean.split(/\\s+/);\n if (words.length >= 2) return (words[0][0] + words[1][0]).toUpperCase();\n return clean.slice(0, 2).toUpperCase();\n}\n\n/** Deterministic hue (0-359) from a string \u2014 same input always yields same color */\nexport function getHue(str: string): number {\n let hash = 0;\n for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);\n return ((hash % 360) + 360) % 360;\n}\n\n", "/**\n * A WebSocket-compatible class that proxies all communication through\n * window.parent via postMessage instead of opening a real WebSocket.\n *\n * Used in embedded mode when the host/parent application sends AD4M_CONFIG\n * with proxy: true. The host opens a real WebSocket to the AD4M daemon and\n * forwards raw frames bidirectionally via the AD4M_PROXY_WS_* protocol.\n *\n * The constructor URL is intentionally ignored \u2014 the connection target is\n * determined by the host, not the embedded app.\n */\nexport class PostMessageWebSocket {\n static readonly CONNECTING = 0\n static readonly OPEN = 1\n static readonly CLOSING = 2\n static readonly CLOSED = 3\n\n readyState: number = 0 // CONNECTING\n\n onopen: ((e: Event) => void) | null = null\n onmessage: ((e: MessageEvent) => void) | null = null\n onerror: ((e: Event) => void) | null = null\n onclose: ((e: CloseEvent) => void) | null = null\n\n private readonly _messageHandler: (e: MessageEvent) => void\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n constructor(_url: string) {\n this._messageHandler = (e: MessageEvent) => {\n if (e.source !== window.parent) return\n\n const msg = e.data\n if (!msg || typeof msg.type !== 'string') return\n\n if (msg.type === 'AD4M_PROXY_WS_OPEN') {\n this.readyState = 1\n this.onopen?.(new Event('open'))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_MESSAGE') {\n this.onmessage?.(new MessageEvent('message', { data: msg.data }))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_ERROR') {\n this.onerror?.(new Event('error'))\n return\n }\n if (msg.type === 'AD4M_PROXY_WS_CLOSED') {\n this.readyState = 3\n this.onclose?.(\n new CloseEvent('close', {\n code: typeof msg.code === 'number' ? msg.code : 1000,\n reason: typeof msg.reason === 'string' ? msg.reason : '',\n wasClean: true,\n })\n )\n window.removeEventListener('message', this._messageHandler)\n }\n }\n\n window.addEventListener('message', this._messageHandler)\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_CONNECT' }, '*')\n }\n\n send(data: string): void {\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_SEND', data }, '*')\n }\n\n close(code?: number, reason?: string): void {\n this.readyState = 2 // CLOSING\n window.parent.postMessage({ type: 'AD4M_PROXY_WS_CLOSE', code, reason }, '*')\n window.removeEventListener('message', this._messageHandler)\n }\n}\n", "/** Error thrown by ApiClient when an RPC call fails. */\nclass RpcError extends Error {\n constructor(status, body) {\n super(`RPC error ${status}: ${body}`);\n this.name = \"RpcError\";\n this.status = status;\n this.body = body;\n }\n}\n/** Default RPC call timeout in milliseconds (30 seconds). */\nconst DEFAULT_TIMEOUT_MS = 30000;\n/** Maximum reconnect delay in ms. */\nconst MAX_RECONNECT_DELAY_MS = 30000;\n/** Initial reconnect delay in ms. */\nconst INITIAL_RECONNECT_DELAY_MS = 500;\n/** Counter for generating unique request IDs. */\nlet _idCounter = 0;\nfunction nextId() {\n return String(++_idCounter);\n}\nclass ApiClient {\n constructor(baseUrl, token, webSocketImpl) {\n // \u2500\u2500 WebSocket RPC core \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n this._ws = null;\n this._wsCallbacks = new Set();\n this._pendingCalls = new Map();\n this._wsReady = null;\n this._wsReadyResolve = null;\n this._wsReconnectTimer = null;\n this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n this._wsClosed = false;\n this._wsPingTimer = null;\n this.baseUrl = baseUrl;\n this.token = token;\n this._webSocketImpl = webSocketImpl;\n }\n getBaseUrl() { return this.baseUrl; }\n getToken() { return this.token; }\n setToken(token) {\n this.token = token;\n }\n _getWsUrl() {\n const wsBase = this.baseUrl\n .replace(/^http:\\/\\//, 'ws://')\n .replace(/^https:\\/\\//, 'wss://');\n const tokenParam = this.token ? `token=${encodeURIComponent(this.token)}` : '';\n const path = '/api/v1/ws';\n return tokenParam ? `${wsBase}${path}?${tokenParam}` : `${wsBase}${path}`;\n }\n _ensureWs() {\n if (this._ws && (this._ws.readyState === 1 /* OPEN */ || this._ws.readyState === 0 /* CONNECTING */)) {\n return;\n }\n // Prevent duplicate connections from concurrent callers\n if (this._wsReady)\n return;\n this._wsClosed = false;\n this._wsReady = new Promise((resolve) => {\n this._wsReadyResolve = resolve;\n });\n const url = this._getWsUrl();\n const WsImpl = this._webSocketImpl ?? WebSocket;\n const ws = new WsImpl(url);\n this._ws = ws;\n ws.onopen = () => {\n this._wsReconnectDelay = INITIAL_RECONNECT_DELAY_MS;\n if (this._wsReadyResolve) {\n this._wsReadyResolve();\n this._wsReadyResolve = null;\n }\n this._startPing();\n };\n ws.onmessage = (event) => {\n let parsed;\n try {\n parsed = JSON.parse(event.data);\n }\n catch (e) {\n console.error('Error parsing WebSocket data:', e);\n return;\n }\n // Ignore pong messages\n if (parsed.type === 'pong')\n return;\n // Check if this is a response to a pending RPC call (has an id field)\n const id = parsed.id;\n if (id && this._pendingCalls.has(id)) {\n const pending = this._pendingCalls.get(id);\n this._pendingCalls.delete(id);\n clearTimeout(pending.timer);\n if (parsed.error) {\n const err = parsed.error;\n pending.reject(new RpcError(err.code ?? 500, err.message ?? 'Unknown error'));\n }\n else {\n pending.resolve(parsed.result);\n }\n return;\n }\n // Server-push event (no id, or id not in pending) \u2192 route to subscribers\n for (const cb of this._wsCallbacks)\n cb(parsed);\n };\n ws.onerror = (e) => {\n console.error('WebSocket error:', e);\n };\n ws.onclose = () => {\n this._stopPing();\n this._ws = null;\n // Reset the readiness promise so future calls reconnect\n this._wsReady = null;\n // Reject all pending calls\n const hadPendingCalls = this._pendingCalls.size > 0;\n for (const [id, pending] of this._pendingCalls) {\n clearTimeout(pending.timer);\n pending.reject(new RpcError(503, 'WebSocket connection closed'));\n }\n this._pendingCalls.clear();\n if (!this._wsClosed && (this._wsCallbacks.size > 0 || hadPendingCalls)) {\n this._scheduleReconnect();\n }\n };\n }\n _startPing() {\n this._stopPing();\n this._wsPingTimer = setInterval(() => {\n if (this._ws && this._ws.readyState === 1 /* OPEN */) {\n this._ws.send(JSON.stringify({ type: 'ping' }));\n }\n }, 30000);\n }\n _stopPing() {\n if (this._wsPingTimer) {\n clearInterval(this._wsPingTimer);\n this._wsPingTimer = null;\n }\n }\n _scheduleReconnect() {\n if (this._wsReconnectTimer)\n return;\n const delay = this._wsReconnectDelay;\n this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS);\n this._wsReconnectTimer = setTimeout(() => {\n this._wsReconnectTimer = null;\n if (!this._wsClosed) {\n this._ensureWs();\n }\n }, delay);\n }\n /** Ensure WS is connected and ready. Lazy \u2014 connects on first use. */\n async _ready() {\n this._ensureWs();\n if (this._wsReady)\n await this._wsReady;\n }\n // \u2500\u2500 RPC call method \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * Send an RPC call over the WebSocket connection.\n * @param type - The operation type (e.g. 'agent.get', 'perspective.all')\n * @param params - Optional parameters to include in the message\n * @returns Promise that resolves with the result from the server\n */\n async call(type, params) {\n await this._ready();\n const id = nextId();\n // Put params under a \"params\" key to avoid collision with\n // protocol fields \"id\" and \"type\" (e.g. params might contain\n // { id: modelId } or { type: \"db\" }).\n const message = { id, type, params: params || {} };\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingCalls.delete(id);\n reject(new RpcError(408, `RPC call '${type}' timed out after ${DEFAULT_TIMEOUT_MS}ms`));\n }, DEFAULT_TIMEOUT_MS);\n this._pendingCalls.set(id, {\n resolve: resolve,\n reject,\n timer,\n });\n if (this._ws && this._ws.readyState === 1 /* OPEN */) {\n this._ws.send(JSON.stringify(message));\n }\n else {\n this._pendingCalls.delete(id);\n clearTimeout(timer);\n reject(new RpcError(503, 'WebSocket not connected'));\n }\n });\n }\n // \u2500\u2500 Event subscriptions (same interface as before) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n subscribe(callback) {\n this._wsCallbacks.add(callback);\n this._ensureWs();\n return () => {\n this._wsCallbacks.delete(callback);\n if (this._wsCallbacks.size === 0 && this._pendingCalls.size === 0) {\n this._closeWs();\n }\n };\n }\n /** Wait until the WebSocket connection is established. */\n async waitForSubscription() {\n await this._ready();\n }\n // \u2500\u2500 Explicit connection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Explicitly connect the WebSocket (optional \u2014 connection is lazy). */\n connect() {\n this._ensureWs();\n }\n _closeWs() {\n this._stopPing();\n if (this._wsReconnectTimer) {\n clearTimeout(this._wsReconnectTimer);\n this._wsReconnectTimer = null;\n }\n if (this._ws) {\n this._wsClosed = true;\n this._ws.close();\n this._ws = null;\n this._wsReady = null;\n }\n }\n /** Close all open WebSocket connections and reject pending calls. */\n closeAll() {\n // Reject pending calls\n for (const [id, pending] of this._pendingCalls) {\n clearTimeout(pending.timer);\n pending.reject(new RpcError(503, 'Client closed'));\n }\n this._pendingCalls.clear();\n this._closeWs();\n this._wsCallbacks.clear();\n }\n}\n\nclass ExpressionProof {\n constructor(sig, k) {\n this.key = k;\n this.signature = sig;\n }\n}\nclass ExpressionProofInput {\n}\n//Note having any as return type here fixes compilation errors but we lose the ExpressionClass type in resulting .d.ts files\nfunction ExpressionGeneric(DataTypeClass) {\n class ExpressionClass {\n constructor(author, timestamp, data, proof) {\n this.author = author;\n this.timestamp = timestamp;\n this.data = data;\n this.proof = proof;\n }\n }\n return ExpressionClass;\n}\nfunction ExpressionGenericInput(DataTypeClass) {\n class ExpressionClass {\n }\n return ExpressionClass;\n}\nclass Expression extends ExpressionGeneric() {\n}\nclass ExpressionRendered extends ExpressionGeneric() {\n}\nfunction isExpression(e) {\n return e && e.author && e.timestamp && e.data;\n}\n\n/** A Perspective represents subjective meaning, encoded through\n* associations between expressions, a.k.a. Links, that is a graph\n* over the objective Expressions of any subset of Languages.\n*\n* This type represents the clean onotological concept of a Perspective.\n* An instance of this class can be regarded as an immutable snapshot of\n* a mutable perspective.\n*\n* The types PerspectiveProxy and PerspectiveHandle are used when dealing\n* with an instantiated mutable perspective as is done through most of\n* the AD4M API.\n*/\nclass Perspective {\n constructor(links) {\n if (links) {\n this.links = links;\n }\n else {\n this.links = [];\n }\n }\n /** Convenience function for filtering links just like with PerspectiveProxy */\n get(query) {\n if (!query || !query.source && !query.predicate && !query.target) {\n return this.links;\n }\n if (query.source) {\n let result = JSON.parse(JSON.stringify(this.links));\n // @ts-ignore\n if (query.target)\n result = result.filter(l => l.data.target === query.target);\n // @ts-ignore\n if (query.predicate)\n result = result.filter(l => l.data.predicate === query.predicate);\n //@ts-ignore\n if (query.fromDate)\n result = result.filter(l => new Date(l.timestamp) >= query.fromDate);\n //@ts-ignore\n if (query.untilDate)\n result = result.filter(l => new Date(l.timestamp) <= query.untilDate);\n // console.debug(\"result\", result)\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n // console.debug(\"getLinks 3\")\n if (query.target) {\n //@ts-ignore\n let result = JSON.parse(JSON.stringify(this.links));\n // @ts-ignore\n if (query.predicate)\n result = result.filter(l => l.data.predicate === query.predicate);\n //@ts-ignore\n if (query.fromDate)\n result = result.filter(l => new Date(l.timestamp) >= query.fromDate);\n //@ts-ignore\n if (query.untilDate)\n result = result.filter(l => new Date(l.timestamp) <= query.untilDate);\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n // console.debug(\"getLinks 4\")\n //@ts-ignore\n let result = JSON.parse(JSON.stringify(this.links));\n result = result.filter(link => link.data.predicate === query.predicate);\n if (query.limit)\n result = result.slice(0, query.limit);\n return result;\n }\n /** Convenience function to get the target of the first link that matches the given query\n * This makes sense when the query is expected to return only one link\n * and the target of that link is what you are looking for.\n */\n getSingleTarget(query) {\n delete query.target;\n const foundLinks = this.get(query);\n if (foundLinks.length)\n return foundLinks[0].data.target;\n else\n return null;\n }\n}\nclass PerspectiveInput {\n}\nclass PerspectiveUnsignedInput {\n constructor(links) {\n if (links)\n this.links = links;\n else\n this.links = [];\n }\n static fromLink(link) {\n let obj = new PerspectiveUnsignedInput();\n obj.links.push(link);\n return obj;\n }\n}\nclass PerspectiveExpression extends ExpressionGeneric() {\n}\n\n/** AD4M's representation of an Agent\n *\n * AD4M Agents are build around DIDs, which are used to identify and authenticate the Agent.\n * Conceptually, an Agent is regarded as something that can speak and that can listen.\n *\n * Agents speak by creating Expressions in AD4M Languages which are signed by the Agent's DID key,\n * And they also speak (broadcast) by putting semantic statements into their public \"Agent Perspective\".\n * They listen (can receive messages) through their \"direct message Language\".\n *\n * These three aspects are represented by the three fields of this class.\n *\n * This class is used as format for the Expressions in the Agent language.\n * Since AD4M treats DID URIs as addresses for the Agent Language,\n * DIDs are resolved to Expressions that are objects of this class.\n * Thus, this is how agents see (other) agents.\n */\nclass Agent {\n constructor(did, perspective) {\n this.did = did;\n if (perspective) {\n this.perspective = perspective;\n }\n else {\n this.perspective = new Perspective();\n }\n }\n}\nclass AgentExpression extends ExpressionGeneric() {\n}\nclass EntanglementProof {\n constructor(did, didSigningKeyId, deviceKeyType, deviceKey, deviceKeySignedByDid, didSignedByDeviceKey) {\n this.did = did;\n this.didSigningKeyId = didSigningKeyId;\n this.deviceKeyType = deviceKeyType;\n this.deviceKey = deviceKey;\n this.deviceKeySignedByDid = deviceKeySignedByDid;\n this.didSignedByDeviceKey = didSignedByDeviceKey;\n }\n}\nclass EntanglementProofInput {\n constructor(did, didSigningKeyId, deviceKeyType, deviceKey, deviceKeySignedByDid, didSignedByDeviceKey) {\n this.did = did;\n this.didSigningKeyId = didSigningKeyId;\n this.deviceKeyType = deviceKeyType;\n this.deviceKey = deviceKey;\n this.deviceKeySignedByDid = deviceKeySignedByDid;\n this.didSignedByDeviceKey = didSignedByDeviceKey;\n }\n}\nclass AgentSignature {\n constructor(signature, publicKey) {\n this.signature = signature;\n this.publicKey = publicKey;\n }\n}\nclass Resource {\n constructor(domain, pointers) {\n this.domain = domain;\n this.pointers = pointers;\n }\n}\nclass Capability {\n constructor(withF, can) {\n this.with = withF;\n this.can = can;\n }\n}\nclass AuthInfo {\n constructor(appName, appDesc, appUrl, capabilities, appIconPath) {\n this.appName = appName;\n this.appDesc = appDesc;\n this.appIconPath = appIconPath;\n this.appUrl = appUrl;\n this.capabilities = capabilities;\n }\n}\nclass Apps {\n constructor(requestId, auth, token, revoked) {\n this.requestId = requestId;\n this.auth = auth;\n this.token = token;\n this.revoked = revoked;\n }\n}\nclass ResourceInput {\n constructor(domain, pointers) {\n this.domain = domain;\n this.pointers = pointers;\n }\n}\nclass CapabilityInput {\n constructor(withF, can) {\n this.with = withF;\n this.can = can;\n }\n}\nclass AuthInfoInput {\n constructor(appName, appDesc, appDomain, appUrl, appIconPath, capabilities) {\n this.appName = appName;\n this.appDesc = appDesc;\n this.appUrl = appUrl;\n this.appDomain = appDomain;\n this.capabilities = capabilities;\n this.appIconPath = appIconPath;\n }\n}\nclass UserCreationResult {\n constructor(did, success, error) {\n this.did = did;\n this.success = success;\n this.error = error;\n }\n}\n\nclass SentMessage {\n}\nclass RuntimeInfo {\n}\nclass ExceptionInfo {\n}\nclass NotificationInput {\n}\nclass Notification {\n}\nclass TriggeredNotification {\n}\nclass ImportStats {\n}\nclass ImportResult {\n}\nclass UserStatistics {\n}\nclass VerificationRequestResult {\n}\nclass HostingUserInfo {\n constructor(email, remainingCredits, hotWalletAddress, freeAccess = false) {\n this.email = email;\n this.remainingCredits = remainingCredits;\n this.hotWalletAddress = hotWalletAddress;\n this.freeAccess = freeAccess;\n }\n}\nclass PaymentRequestResult {\n constructor(success, message) {\n this.success = success;\n this.message = message;\n }\n}\nclass ComputeLogEntry {\n constructor(id, userEmail, timestamp, operation, cost, creditsAfter, summary) {\n this.id = id;\n this.userEmail = userEmail;\n this.timestamp = timestamp;\n this.operation = operation;\n this.cost = cost;\n this.creditsAfter = creditsAfter;\n this.summary = summary;\n }\n}\n\nclass AgentStatus {\n constructor(obj) {\n if (obj) {\n //@ts-ignore\n this.isInitialized = obj.isInitialized;\n if (!this.isInitialized) {\n this.isInitialized = false;\n }\n //@ts-ignore\n this.isUnlocked = obj.isUnlocked;\n if (!this.isUnlocked) {\n this.isUnlocked = false;\n }\n //@ts-ignore\n this.did = obj.did;\n //@ts-ignore\n this.didDocument = obj.didDocument;\n //@ts-ignore\n this.error = obj.error;\n }\n else {\n this.isInitialized = false;\n this.isUnlocked = false;\n }\n }\n}\n\nvar __classPrivateFieldSet$c = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$c = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _NeighbourhoodProxy_client, _NeighbourhoodProxy_pID;\nclass NeighbourhoodProxy {\n constructor(client, pID) {\n _NeighbourhoodProxy_client.set(this, void 0);\n _NeighbourhoodProxy_pID.set(this, void 0);\n __classPrivateFieldSet$c(this, _NeighbourhoodProxy_client, client, \"f\");\n __classPrivateFieldSet$c(this, _NeighbourhoodProxy_pID, pID, \"f\");\n }\n async otherAgents() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").otherAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async hasTelepresenceAdapter() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").hasTelepresenceAdapter(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async onlineAgents() {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").onlineAgents(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"));\n }\n async setOnlineStatus(status) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").setOnlineStatus(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), status);\n }\n async setOnlineStatusU(status) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").setOnlineStatusU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), status);\n }\n async sendSignal(remoteAgentDid, payload) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendSignal(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), remoteAgentDid, payload);\n }\n async sendSignalU(remoteAgentDid, payload) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendSignalU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), remoteAgentDid, payload);\n }\n async sendBroadcast(payload, loopback = false) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendBroadcast(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), payload, loopback);\n }\n async sendBroadcastU(payload, loopback = false) {\n return await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").sendBroadcastU(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), payload, loopback);\n }\n async addSignalHandler(handler) {\n await __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").addSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), handler);\n }\n removeSignalHandler(handler) {\n __classPrivateFieldGet$c(this, _NeighbourhoodProxy_client, \"f\").removeSignalHandler(__classPrivateFieldGet$c(this, _NeighbourhoodProxy_pID, \"f\"), handler);\n }\n}\n_NeighbourhoodProxy_client = new WeakMap(), _NeighbourhoodProxy_pID = new WeakMap();\n\nclass Link {\n constructor(obj) {\n this.source = obj.source ? obj.source : '';\n this.target = obj.target ? obj.target : '';\n this.predicate = obj.predicate ? obj.predicate : '';\n }\n}\nclass LinkMutations {\n}\nclass LinkExpressionMutations {\n constructor(additions, removals) {\n this.additions = additions;\n this.removals = removals;\n }\n}\nclass LinkInput {\n}\nclass LinkExpression extends ExpressionGeneric() {\n hash() {\n const mash = JSON.stringify(this.data, Object.keys(this.data).sort()) +\n JSON.stringify(this.author) + this.timestamp;\n let hash = 0, i, chr;\n for (i = 0; i < mash.length; i++) {\n chr = mash.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n }\n}\nclass LinkExpressionInput extends ExpressionGenericInput() {\n}\nfunction linkEqual(l1, l2) {\n return l1.author == l2.author &&\n l1.timestamp == l2.timestamp &&\n l1.data.source == l2.data.source &&\n l1.data.predicate == l2.data.predicate &&\n l1.data.target == l2.data.target;\n}\nfunction isLink(l) {\n return l && l.source && l.target;\n}\nclass LinkExpressionUpdated {\n constructor(oldLink, newLink) {\n this.oldLink = oldLink;\n this.newLink = newLink;\n }\n}\n\nclass LinkQuery {\n constructor(obj) {\n if (obj) {\n // @ts-ignore\n this.source = obj.source;\n // @ts-ignore\n this.predicate = obj.predicate;\n // @ts-ignore\n this.target = obj.target;\n // @ts-ignore\n if (obj.fromDate) {\n // @ts-ignore\n this.fromDate = obj.fromDate;\n }\n // @ts-ignore\n if (obj.untilDate) {\n // @ts-ignore\n this.untilDate = obj.untilDate;\n }\n // @ts-ignore\n if (obj.limit) {\n // @ts-ignore\n this.limit = obj.limit;\n }\n }\n }\n isMatch(l) {\n if (this.source)\n if (this.source !== l.source)\n return false;\n if (this.predicate)\n if (this.predicate !== l.predicate)\n return false;\n if (this.target)\n if (this.target !== l.target)\n return false;\n return true;\n }\n}\n\nvar __classPrivateFieldSet$b = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$b = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Literal_literal, _Literal_url;\nfunction encodeRFC3986URIComponent(str) {\n return encodeURIComponent(str)\n .replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n}\nclass Literal {\n constructor() {\n _Literal_literal.set(this, void 0);\n _Literal_url.set(this, void 0);\n }\n static fromUrl(url) {\n if (!url || !url.startsWith(\"literal:\"))\n throw new Error(\"Can't create Literal from non-literal URL\");\n if (url.startsWith(\"literal://\"))\n throw new Error(\"literal:// format is no longer supported. Use literal: instead.\");\n const l = new Literal();\n __classPrivateFieldSet$b(l, _Literal_url, url, \"f\");\n return l;\n }\n static from(literal) {\n const l = new Literal();\n __classPrivateFieldSet$b(l, _Literal_literal, literal, \"f\");\n return l;\n }\n toUrl() {\n if (__classPrivateFieldGet$b(this, _Literal_url, \"f\") && !__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))\n return __classPrivateFieldGet$b(this, _Literal_url, \"f\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\") && (__classPrivateFieldGet$b(this, _Literal_literal, \"f\") === undefined || __classPrivateFieldGet$b(this, _Literal_literal, \"f\") === \"\" || __classPrivateFieldGet$b(this, _Literal_literal, \"f\") === null))\n throw new Error(\"Can't turn empty Literal into URL\");\n let encoded;\n switch (typeof __classPrivateFieldGet$b(this, _Literal_literal, \"f\")) {\n case 'string':\n encoded = `string:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'number':\n encoded = `number:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'boolean':\n encoded = `boolean:${encodeRFC3986URIComponent(__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))}`;\n break;\n case 'object':\n encoded = `json:${encodeRFC3986URIComponent(JSON.stringify(__classPrivateFieldGet$b(this, _Literal_literal, \"f\")))}`;\n break;\n }\n return `literal:${encoded}`;\n }\n get() {\n if (__classPrivateFieldGet$b(this, _Literal_literal, \"f\"))\n return __classPrivateFieldGet$b(this, _Literal_literal, \"f\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\"))\n throw new Error(\"Can't render empty Literal\");\n if (!__classPrivateFieldGet$b(this, _Literal_url, \"f\").startsWith(\"literal:\"))\n throw new Error(\"Can't render Literal from non-literal URL\");\n const body = __classPrivateFieldGet$b(this, _Literal_url, \"f\").substring(8);\n if (body.startsWith(\"string:\")) {\n return decodeURIComponent(body.substring(7));\n }\n if (body.startsWith(\"number:\")) {\n const numberString = body.substring(7);\n return parseFloat(numberString);\n }\n if (body.startsWith(\"json:\")) {\n const json = body.substring(5);\n return JSON.parse(decodeURIComponent(json));\n }\n throw new Error(`Can't parse unknown literal: ${body}`);\n }\n}\n_Literal_literal = new WeakMap(), _Literal_url = new WeakMap();\n\nfunction capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n// e.g. \"name\" -> \"setName\"\nfunction propertyNameToSetterName(property) {\n return `set${capitalize(property)}`;\n}\n/**\n * Generate a random identifier string of the given length (lowercase alpha).\n */\nfunction makeRandomId(length) {\n let result = '';\n const characters = 'abcdefghijklmnopqrstuvwxyz';\n const charactersLength = characters.length;\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nfunction stringifyObjectLiteral(obj) {\n if (Array.isArray(obj)) {\n //@ts-ignore\n return `[${obj.map(stringifyObjectLiteral).join(\", \")}]`;\n }\n const keys = Object.keys(obj);\n const stringifiedPairs = [];\n for (const key of keys) {\n const valueString = JSON.stringify(obj[key]);\n const keyValuePairString = `${key}: ${valueString}`;\n stringifiedPairs.push(keyValuePairString);\n }\n return `{${stringifiedPairs.join(', ')}}`;\n}\n\n/**\n * SDNA (Social DNA) Prolog code generation.\n *\n * Builds subject-class Prolog facts from a model's property and relation\n * metadata. The heavy lifting used to live inside the `@Model` decorator\n * closure \u2014 it is extracted here so decorators.ts stays focused on\n * decorator registration logic.\n */\n/**\n * Build SDNA (Social DNA) Prolog code for a model class.\n *\n * @param subjectName - The model's registered name (from `@Model({ name })`)\n * @param obj - `target.prototype` \u2014 used to inspect prototype methods\n * (e.g. setter stubs, `subjectConstructor`, `isSubjectInstance`)\n * @param properties - Merged property metadata (from `getPropertiesMetadata`)\n * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)\n */\nfunction buildSDNA(subjectName, obj, properties, allRelationsMeta) {\n let sdna = \"\";\n let uuid = makeRandomId(8);\n sdna += `subject_class(\"${subjectName}\", ${uuid}).\\n`;\n let classRemoverActions = [];\n let constructorActions = [];\n if (obj.subjectConstructor && obj.subjectConstructor.length) {\n constructorActions = constructorActions.concat(obj.subjectConstructor);\n }\n let instanceConditions = [];\n if (obj.isSubjectInstance && obj.isSubjectInstance.length) {\n instanceConditions = instanceConditions.concat(obj.isSubjectInstance);\n }\n let propertiesCode = [];\n for (let property in properties) {\n let propertyCode = `property(${uuid}, \"${property}\").\\n`;\n let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];\n if (resolveLanguage) {\n propertyCode += `property_resolve(${uuid}, \"${property}\").\\n`;\n propertyCode += `property_resolve_language(${uuid}, \"${property}\", \"${resolveLanguage}\").\\n`;\n }\n if (prologGetter) {\n propertyCode += `property_getter(${uuid}, Base, \"${property}\", Value) :- ${prologGetter}.\\n`;\n }\n else if (through) {\n propertyCode += `property_getter(${uuid}, Base, \"${property}\", Value) :- triple(Base, \"${through}\", Value).\\n`;\n if (required) {\n if (flag) {\n instanceConditions.push(`triple(Base, \"${through}\", \"${initial}\")`);\n }\n else {\n instanceConditions.push(`triple(Base, \"${through}\", _)`);\n }\n }\n }\n if (prologSetter) {\n propertyCode += `property_setter(${uuid}, \"${property}\", Actions) :- ${prologSetter}.\\n`;\n }\n else if (writable && through) {\n let setter = obj[propertyNameToSetterName(property)];\n if (typeof setter === \"function\") {\n let action = [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n propertyCode += `property_setter(${uuid}, \"${property}\", '${stringifyObjectLiteral(action)}').\\n`;\n }\n }\n propertiesCode.push(propertyCode);\n // Auto-derive effectiveInitial for required, writable, non-flag properties\n // so constructor/destructor always handle the property link.\n // Optional properties (required: false) are excluded \u2014 they should\n // remain unset (undefined) until explicitly assigned.\n const effectiveInitial = initial\n ?? (required && writable && !flag && through ? \"literal:string:\" : undefined);\n if (effectiveInitial) {\n constructorActions.push({\n action: \"addLink\",\n source: \"this\",\n predicate: through,\n target: effectiveInitial,\n });\n classRemoverActions.push({\n action: \"removeLink\",\n source: \"this\",\n predicate: through,\n target: \"*\",\n });\n }\n }\n let relationsCode = [];\n const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));\n for (let relation in relations) {\n let relationCode = `collection(${uuid}, \"${relation}\").\\n`;\n let { predicate: through, local } = relations[relation];\n if (through) {\n relationCode += `collection_getter(${uuid}, Base, \"${relation}\", List) :- findall(C, triple(Base, \"${through}\", C), List).\\n`;\n let relationAdderAction = [{\n action: \"addLink\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n let relationRemoverAction = [{\n action: \"removeLink\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n }];\n let relationSetterAction = [{\n action: \"collectionSetter\",\n source: \"this\",\n predicate: through,\n target: \"value\",\n ...(local && { local: true })\n }];\n relationCode += `collection_adder(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationAdderAction)}').\\n`;\n relationCode += `collection_remover(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationRemoverAction)}').\\n`;\n relationCode += `collection_setter(${uuid}, \"${relation}\", '${stringifyObjectLiteral(relationSetterAction)}').\\n`;\n }\n relationsCode.push(relationCode);\n }\n let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);\n sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\\n`;\n if (instanceConditions.length > 0) {\n let instanceConditionProlog = instanceConditions.join(\", \");\n sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\\n`;\n sdna += \"\\n\";\n }\n sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\\n`;\n sdna += \"\\n\";\n sdna += propertiesCode.join(\"\\n\");\n sdna += \"\\n\";\n sdna += relationsCode.join(\"\\n\");\n return {\n sdna,\n name: subjectName\n };\n}\n\n/**\n * Extract namespace from a URI\n * Examples:\n * - \"recipe://name\" -> \"recipe://\"\n * - \"https://example.com/vocab#term\" -> \"https://example.com/vocab#\"\n * - \"https://example.com/vocab/term\" -> \"https://example.com/vocab/\"\n * - \"recipe:Recipe\" -> \"recipe:\"\n */\nfunction extractNamespace(uri) {\n // Handle hash fragments first (highest priority)\n const hashIndex = uri.lastIndexOf('#');\n if (hashIndex !== -1) {\n return uri.substring(0, hashIndex + 1);\n }\n // Handle protocol-style URIs with paths\n const protocolMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\\/\\/)(.*)$/);\n if (protocolMatch) {\n const afterScheme = protocolMatch[2];\n const lastSlash = afterScheme.lastIndexOf('/');\n if (lastSlash !== -1) {\n // Has path segments - namespace includes up to last slash\n return protocolMatch[1] + afterScheme.substring(0, lastSlash + 1);\n }\n // Simple protocol URI without path (e.g., \"recipe://name\")\n return protocolMatch[1];\n }\n // Handle colon-separated (namespace:localName)\n const colonMatch = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)/);\n if (colonMatch) {\n return colonMatch[1];\n }\n // Fallback: no clear namespace\n return '';\n}\n/**\n * Escape special characters for Turtle string literals\n * Handles backslashes, quotes, newlines, and other control characters\n */\nfunction escapeTurtleString(value) {\n return value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash must be first\n .replace(/\"/g, '\\\\\"') // Double quotes\n .replace(/\\n/g, '\\\\n') // Newlines\n .replace(/\\r/g, '\\\\r') // Carriage returns\n .replace(/\\t/g, '\\\\t') // Tabs\n .replace(/\\b/g, '\\\\b') // Backspace\n .replace(/\\f/g, '\\\\f'); // Form feed\n}\n/**\n * Extract local name from a URI\n * Examples:\n * - \"recipe://name\" -> \"name\"\n * - \"https://example.com/vocab#term\" -> \"term\"\n * - \"https://example.com/vocab/term\" -> \"term\"\n * - \"recipe:Recipe\" -> \"Recipe\"\n */\nfunction extractLocalName(uri) {\n // Handle hash fragments\n const hashIndex = uri.lastIndexOf('#');\n if (hashIndex !== -1) {\n return uri.substring(hashIndex + 1);\n }\n // Handle slash-based namespaces\n const lastSlash = uri.lastIndexOf('/');\n if (lastSlash !== -1 && lastSlash < uri.length - 1) {\n return uri.substring(lastSlash + 1);\n }\n // Handle colon-separated\n const colonMatch = uri.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:(.+)$/);\n if (colonMatch) {\n return colonMatch[1];\n }\n // Fallback: entire URI\n return uri;\n}\n/**\n * SHACL Node Shape\n * Defines constraints for instances of a class\n */\nclass SHACLShape {\n /**\n * Create a new SHACL Shape\n * @param targetClassOrShapeUri - If one argument: the target class (shape URI auto-derived as {class}Shape)\n * If two arguments: first is shape URI, second is target class\n * @param targetClass - Optional target class when first arg is shape URI\n */\n constructor(targetClassOrShapeUri, targetClass) {\n if (targetClass !== undefined) {\n // Two arguments: explicit shape URI and target class\n this.nodeShapeUri = targetClassOrShapeUri;\n this.targetClass = targetClass;\n }\n else {\n // One argument: derive shape URI from target class\n this.targetClass = targetClassOrShapeUri;\n // Derive shape URI by appending \"Shape\" to the local name\n const namespace = extractNamespace(targetClassOrShapeUri);\n const localName = extractLocalName(targetClassOrShapeUri);\n this.nodeShapeUri = `${namespace}${localName}Shape`;\n }\n this.properties = [];\n this.parentShapes = [];\n }\n /**\n * Add a parent shape reference (sh:node) for model inheritance.\n * When a @Model class extends another @Model, the child shape\n * references the parent shape so SHACL validators can walk the\n * class hierarchy.\n */\n addParentShape(parentShapeUri) {\n if (!this.parentShapes.includes(parentShapeUri)) {\n this.parentShapes.push(parentShapeUri);\n }\n }\n /**\n * Add a property constraint to this shape\n */\n addProperty(prop) {\n this.properties.push(prop);\n }\n /**\n * Set constructor actions for this shape\n */\n setConstructorActions(actions) {\n this.constructor_actions = actions;\n }\n /**\n * Set destructor actions for this shape\n */\n setDestructorActions(actions) {\n this.destructor_actions = actions;\n }\n /**\n * Serialize shape to Turtle (RDF) format\n */\n toTurtle() {\n let turtle = `@prefix sh: <http://www.w3.org/ns/shacl#> .\\n`;\n turtle += `@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\\n`;\n turtle += `@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n`;\n turtle += `@prefix ad4m: <ad4m://> .\\n\\n`;\n turtle += `<${this.nodeShapeUri}>\\n`;\n turtle += ` a sh:NodeShape ;\\n`;\n if (this.targetClass) {\n turtle += ` sh:targetClass <${this.targetClass}> ;\\n`;\n }\n // Emit sh:node references for parent shapes (model inheritance)\n for (const parentUri of this.parentShapes) {\n turtle += ` sh:node <${parentUri}> ;\\n`;\n }\n // Add property shapes\n for (let i = 0; i < this.properties.length; i++) {\n const prop = this.properties[i];\n const isLast = i === this.properties.length - 1;\n turtle += ` sh:property [\\n`;\n turtle += ` sh:path <${prop.path}> ;\\n`;\n if (prop.datatype) {\n turtle += ` sh:datatype <${prop.datatype}> ;\\n`;\n }\n if (prop.nodeKind) {\n turtle += ` sh:nodeKind sh:${prop.nodeKind} ;\\n`;\n }\n if (prop.minCount !== undefined) {\n turtle += ` sh:minCount ${prop.minCount} ;\\n`;\n }\n if (prop.maxCount !== undefined) {\n turtle += ` sh:maxCount ${prop.maxCount} ;\\n`;\n }\n if (prop.pattern) {\n turtle += ` sh:pattern \"${escapeTurtleString(prop.pattern)}\" ;\\n`;\n }\n if (prop.minInclusive !== undefined) {\n turtle += ` sh:minInclusive ${prop.minInclusive} ;\\n`;\n }\n if (prop.maxInclusive !== undefined) {\n turtle += ` sh:maxInclusive ${prop.maxInclusive} ;\\n`;\n }\n if (prop.hasValue) {\n turtle += ` sh:hasValue \"${escapeTurtleString(prop.hasValue)}\" ;\\n`;\n }\n // AD4M-specific metadata\n if (prop.local !== undefined) {\n turtle += ` ad4m:local ${prop.local} ;\\n`;\n }\n if (prop.writable !== undefined) {\n turtle += ` ad4m:writable ${prop.writable} ;\\n`;\n }\n // Remove trailing semicolon and close bracket\n turtle = turtle.slice(0, -2) + '\\n';\n turtle += isLast ? ` ] .\\n` : ` ] ;\\n`;\n }\n return turtle;\n }\n /**\n * Serialize shape to AD4M Links (RDF triples)\n * Stores the shape as a graph of links in a Perspective\n */\n toLinks() {\n const links = [];\n // Shape type declaration\n links.push({\n source: this.nodeShapeUri,\n predicate: \"rdf://type\",\n target: \"sh://NodeShape\"\n });\n // Target class\n if (this.targetClass) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"sh://targetClass\",\n target: this.targetClass\n });\n }\n // Constructor actions \u2014 always emit, even for an empty array.\n // An empty `[]` tells the executor the shape is valid but has no\n // required initial links (all-optional model with no @Flag).\n if (this.constructor_actions) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"ad4m://constructor\",\n target: `literal:string:${JSON.stringify(this.constructor_actions)}`\n });\n }\n // Destructor actions \u2014 same rationale as constructor.\n if (this.destructor_actions) {\n links.push({\n source: this.nodeShapeUri,\n predicate: \"ad4m://destructor\",\n target: `literal:string:${JSON.stringify(this.destructor_actions)}`\n });\n }\n // Property shapes (each gets a named URI: {namespace}/{ClassName}.{propertyName})\n for (let i = 0; i < this.properties.length; i++) {\n const prop = this.properties[i];\n // Generate named property shape URI\n let propShapeId;\n if (prop.name && this.targetClass) {\n // Extract namespace from targetClass\n const namespace = extractNamespace(this.targetClass);\n const className = extractLocalName(this.targetClass);\n // Use format: {namespace}{ClassName}.{propertyName}\n propShapeId = `${namespace}${className}.${prop.name}`;\n }\n else {\n // Fallback to blank node if name is missing\n propShapeId = `_:propShape${i}`;\n }\n // Link shape to property shape\n links.push({\n source: this.nodeShapeUri,\n predicate: \"sh://property\",\n target: propShapeId\n });\n // Property path\n links.push({\n source: propShapeId,\n predicate: \"sh://path\",\n target: prop.path\n });\n // Constraints\n if (prop.datatype) {\n links.push({\n source: propShapeId,\n predicate: \"sh://datatype\",\n target: prop.datatype\n });\n }\n if (prop.nodeKind) {\n links.push({\n source: propShapeId,\n predicate: \"sh://nodeKind\",\n target: `sh://${prop.nodeKind}`\n });\n }\n if (prop.minCount !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://minCount\",\n target: `literal:${prop.minCount}^^xsd:integer`\n });\n }\n if (prop.maxCount !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://maxCount\",\n target: `literal:${prop.maxCount}^^xsd:integer`\n });\n }\n if (prop.pattern) {\n links.push({\n source: propShapeId,\n predicate: \"sh://pattern\",\n target: `literal:${prop.pattern}`\n });\n }\n if (prop.minInclusive !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://minInclusive\",\n target: `literal:${prop.minInclusive}`\n });\n }\n if (prop.maxInclusive !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"sh://maxInclusive\",\n target: `literal:${prop.maxInclusive}`\n });\n }\n if (prop.hasValue) {\n links.push({\n source: propShapeId,\n predicate: \"sh://hasValue\",\n target: `literal:${prop.hasValue}`\n });\n }\n // AD4M-specific metadata\n if (prop.local !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://local\",\n target: `literal:${prop.local}`\n });\n }\n if (prop.writable !== undefined) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://writable\",\n target: `literal:${prop.writable}`\n });\n }\n if (prop.resolveLanguage) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://resolveLanguage\",\n target: `literal:string:${prop.resolveLanguage}`\n });\n }\n // AD4M-specific actions\n if (prop.setter && prop.setter.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://setter\",\n target: `literal:string:${JSON.stringify(prop.setter)}`\n });\n }\n if (prop.adder && prop.adder.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://adder\",\n target: `literal:string:${JSON.stringify(prop.adder)}`\n });\n }\n if (prop.remover && prop.remover.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://remover\",\n target: `literal:string:${JSON.stringify(prop.remover)}`\n });\n }\n if (prop.getter) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://getter\",\n target: `literal:string:${prop.getter}`\n });\n }\n if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"ad4m://conformanceConditions\",\n target: `literal:string:${JSON.stringify(prop.conformanceConditions)}`\n });\n }\n if (prop.class) {\n links.push({\n source: propShapeId,\n predicate: \"sh://class\",\n target: prop.class\n });\n }\n if (prop.in && prop.in.length > 0) {\n links.push({\n source: propShapeId,\n predicate: \"sh://in\",\n target: `literal:string:${JSON.stringify(prop.in)}`\n });\n }\n }\n return links;\n }\n /**\n * Reconstruct shape from AD4M Links\n */\n static fromLinks(links, shapeUri) {\n // Find target class\n const targetClassLink = links.find(l => l.source === shapeUri && l.predicate === \"sh://targetClass\");\n const shape = new SHACLShape(shapeUri, targetClassLink?.target);\n // Find constructor actions\n const constructorLink = links.find(l => l.source === shapeUri && l.predicate === \"ad4m://constructor\");\n if (constructorLink) {\n try {\n const jsonStr = constructorLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n shape.constructor_actions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n // Find destructor actions\n const destructorLink = links.find(l => l.source === shapeUri && l.predicate === \"ad4m://destructor\");\n if (destructorLink) {\n try {\n const jsonStr = destructorLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n shape.destructor_actions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n // Find all property shapes\n const propShapeLinks = links.filter(l => l.source === shapeUri && l.predicate === \"sh://property\");\n for (const propLink of propShapeLinks) {\n const propShapeId = propLink.target;\n // Reconstruct property from its links\n const pathLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://path\");\n if (!pathLink)\n continue;\n // Extract property name from propShapeId if it's a named URI\n // Format: {namespace}{ClassName}.{propertyName}\n let propertyName;\n if (!propShapeId.startsWith('_:')) {\n const lastDotIndex = propShapeId.lastIndexOf('.');\n if (lastDotIndex !== -1) {\n propertyName = propShapeId.substring(lastDotIndex + 1);\n }\n }\n const prop = {\n name: propertyName,\n path: pathLink.target\n };\n // Extract constraints\n const datatypeLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://datatype\");\n if (datatypeLink)\n prop.datatype = datatypeLink.target;\n const nodeKindLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://nodeKind\");\n if (nodeKindLink) {\n prop.nodeKind = nodeKindLink.target.replace('sh://', '');\n }\n const minCountLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://minCount\");\n if (minCountLink) {\n // Handle both formats: literal:5^^xsd:integer and literal:number:5\n let val = minCountLink.target.replace(/^literal:\\/\\/|^literal:/, '').replace(/\\^\\^.*$/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.minCount = parseInt(val);\n }\n const maxCountLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://maxCount\");\n if (maxCountLink) {\n // Handle both formats: literal:5^^xsd:integer and literal:number:5\n let val = maxCountLink.target.replace(/^literal:\\/\\/|^literal:/, '').replace(/\\^\\^.*$/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.maxCount = parseInt(val);\n }\n const patternLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://pattern\");\n if (patternLink) {\n prop.pattern = patternLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n }\n const minInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://minInclusive\");\n if (minInclusiveLink) {\n // Handle both formats: literal:5 and literal:number:5\n let val = minInclusiveLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.minInclusive = parseFloat(val);\n }\n const maxInclusiveLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://maxInclusive\");\n if (maxInclusiveLink) {\n // Handle both formats: literal:5 and literal:number:5\n let val = maxInclusiveLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('number:'))\n val = val.substring(7);\n prop.maxInclusive = parseFloat(val);\n }\n const hasValueLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://hasValue\");\n if (hasValueLink) {\n prop.hasValue = hasValueLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n }\n // AD4M-specific\n const localLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://local\");\n if (localLink) {\n // Handle both formats: literal:true and literal:boolean:true\n let val = localLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('boolean:'))\n val = val.substring(8);\n prop.local = val === 'true';\n }\n const writableLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://writable\");\n if (writableLink) {\n // Handle both formats: literal:true and literal:boolean:true\n let val = writableLink.target.replace(/^literal:\\/\\/|^literal:/, '');\n if (val.startsWith('boolean:'))\n val = val.substring(8);\n prop.writable = val === 'true';\n }\n const resolveLangLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://resolveLanguage\");\n if (resolveLangLink) {\n prop.resolveLanguage = resolveLangLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n }\n // Parse action arrays\n const setterLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://setter\");\n if (setterLink) {\n try {\n const jsonStr = setterLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.setter = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const adderLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://adder\");\n if (adderLink) {\n try {\n const jsonStr = adderLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.adder = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const removerLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://remover\");\n if (removerLink) {\n try {\n const jsonStr = removerLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.remover = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const getterLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://getter\");\n if (getterLink) {\n prop.getter = getterLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n }\n const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === \"ad4m://conformanceConditions\");\n if (conditionsLink) {\n try {\n const jsonStr = conditionsLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.conformanceConditions = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n const classLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://class\");\n if (classLink) {\n prop.class = classLink.target;\n }\n const inLink = links.find(l => l.source === propShapeId && l.predicate === \"sh://in\");\n if (inLink) {\n try {\n const jsonStr = inLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n prop.in = JSON.parse(jsonStr);\n }\n catch (e) {\n // Ignore parse errors\n }\n }\n shape.addProperty(prop);\n }\n return shape;\n }\n /**\n * Convert the shape to a JSON-serializable object.\n * Useful for passing to addSdna() as shaclJson parameter.\n *\n * @returns JSON-serializable object representing the shape\n */\n toJSON() {\n return {\n node_shape_uri: this.nodeShapeUri,\n target_class: this.targetClass,\n parent_shapes: this.parentShapes.length > 0 ? this.parentShapes : undefined,\n properties: this.properties.map(p => ({\n path: p.path,\n name: p.name,\n datatype: p.datatype,\n node_kind: p.nodeKind,\n min_count: p.minCount,\n max_count: p.maxCount,\n min_inclusive: p.minInclusive,\n max_inclusive: p.maxInclusive,\n pattern: p.pattern,\n has_value: p.hasValue,\n local: p.local,\n writable: p.writable,\n resolve_language: p.resolveLanguage,\n setter: p.setter,\n adder: p.adder,\n remover: p.remover,\n getter: p.getter,\n conformance_conditions: p.conformanceConditions,\n class: p.class,\n in: p.in,\n })),\n constructor_actions: this.constructor_actions,\n destructor_actions: this.destructor_actions,\n };\n }\n /**\n * Create a shape from a JSON object (inverse of toJSON)\n */\n static fromJSON(json) {\n const shape = json.node_shape_uri\n ? new SHACLShape(json.node_shape_uri, json.target_class)\n : new SHACLShape(json.target_class);\n for (const p of json.properties || []) {\n shape.addProperty({\n path: p.path,\n name: p.name,\n datatype: p.datatype,\n nodeKind: p.node_kind,\n minCount: p.min_count,\n maxCount: p.max_count,\n minInclusive: p.min_inclusive,\n maxInclusive: p.max_inclusive,\n pattern: p.pattern,\n hasValue: p.has_value,\n local: p.local,\n writable: p.writable,\n resolveLanguage: p.resolve_language,\n setter: p.setter,\n adder: p.adder,\n remover: p.remover,\n getter: p.getter,\n conformanceConditions: p.conformance_conditions,\n class: p.class,\n in: p.in,\n });\n }\n if (json.constructor_actions) {\n shape.constructor_actions = json.constructor_actions;\n }\n if (json.destructor_actions) {\n shape.destructor_actions = json.destructor_actions;\n }\n if (json.parent_shapes) {\n for (const ps of json.parent_shapes) {\n shape.addParentShape(ps);\n }\n }\n return shape;\n }\n}\n\nfunction formatList(list) {\n if (!list?.length) {\n return \"\";\n }\n if (list.length === 1) {\n return list.toString();\n }\n if (list.length === 2) {\n return list.join(' and ');\n }\n return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);\n}\nfunction capSentence(cap) {\n const can = cap.can.includes(\"*\") ? [\"READ\", \"WRITE\", \"UPDATE\"] : cap.can;\n const domain = cap.with.domain === \"*\" ? \"\" : cap.with.domain;\n const pointers = cap.with.pointers.includes(\"*\")\n ? [\"all AD4M data\"]\n : cap.with.pointers;\n return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;\n}\n/**\n * Escapes a string value for safe use in query strings.\n *\n * @description\n * Prevents SQL injection by properly escaping special characters in string values\n * that will be interpolated into query strings. This handles the most common\n * special characters that could break SQL queries or enable injection attacks.\n *\n * Single quotes, backslashes, and other special characters are escaped using\n * backslash notation, which is the standard escaping mechanism for query.\n *\n * @param value - The string value to escape\n * @returns The escaped string safe for query interpolation (without surrounding quotes)\n *\n * @example\n * ```typescript\n * const userInput = \"user's input with 'quotes'\";\n * const escaped = escapeQueryString(userInput);\n * const query = `SELECT * FROM link WHERE uri = '${escaped}'`;\n * // Results in: SELECT * FROM link WHERE uri = 'user\\'s input with \\'quotes\\''\n * ```\n */\nfunction escapeQueryString(value) {\n return value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash -> \\\\\n .replace(/'/g, \"\\\\'\") // Single quote -> \\'\n .replace(/\"/g, '\\\\\"') // Double quote -> \\\"\n .replace(/\\n/g, '\\\\n') // Newline -> \\n\n .replace(/\\r/g, '\\\\r') // Carriage return -> \\r\n .replace(/\\t/g, '\\\\t'); // Tab -> \\t\n}\n\n/**\n * Shared query compilation utilities.\n *\n * These functions are used by both the runtime query builder (`Ad4mModel`) and\n * the compile-time SHACL generator (`decorators.ts`).\n *\n * All output uses native SPARQL syntax.\n */\n/**\n * Format a JavaScript value for embedding in a query expression.\n *\n * - Strings are single-quoted with backslash / quote / newline escaping\n * - Numbers and booleans are passed through as-is\n * - Arrays are recursed\n */\nfunction formatQueryValue(value) {\n if (typeof value === 'string') {\n // Escape backslashes first, then single quotes and other special characters\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\') // Backslash -> \\\\\n .replace(/'/g, \"\\\\'\") // Single quote -> \\'\n .replace(/\"/g, '\\\\\"') // Double quote -> \\\"\n .replace(/\\n/g, '\\\\n') // Newline -> \\n\n .replace(/\\r/g, '\\\\r') // Carriage return -> \\r\n .replace(/\\t/g, '\\\\t'); // Tab -> \\t\n return `'${escaped}'`;\n }\n else if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n else if (Array.isArray(value)) {\n return `[${value.map(v => formatQueryValue(v)).join(', ')}]`;\n }\n else {\n return String(value);\n }\n}\n/**\n * Compile a single Where condition for a property into a SPARQL triple pattern\n * that can be embedded in a getter's WHERE clause.\n *\n * The generated pattern operates on `?target` \u2014 e.g.:\n * `?target <pred> <value> .`\n * `FILTER EXISTS { ?target <pred> ?_v0 }`\n *\n * @param predicate - The predicate URI for the property\n * @param condition - The Where condition value\n * @param opts - Optional settings (e.g. `resolveLanguage`)\n * @returns A single SPARQL condition string\n */\nfunction buildWhereCondition(predicate, condition, opts) {\n const escapedPredicate = escapeQueryString(predicate);\n // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)\n // For language-resolved properties, we match against the plain URI\n // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>\n // For language-resolved properties, values are plain URIs\n const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';\n const varSuffix = opts?.varIndex ?? 0;\n function formatValue(v) {\n if (typeof v === 'string') {\n return isLiteral\n ? `<literal:string:${escapeQueryString(v)}>`\n : `<${escapeQueryString(v)}>`;\n }\n // Numbers/booleans \u2014 also stored as literal:string: in AD4M\n return `<literal:string:${v}>`;\n }\n /**\n * For literal properties, generate a FILTER-based match that handles both\n * the raw value and the literal-encoded value. This mirrors the Rust\n * `build_projection_where_patterns` approach which uses:\n * FILTER(STR(?var) = \"value\" || STR(?var) = \"literal:string:encodedValue\")\n * This is more robust than exact IRI matching because it handles edge cases\n * where the stored format might vary.\n */\n function formatLiteralFilter(varName, v) {\n const raw = escapeQueryString(String(v));\n const encoded = encodeURIComponent(String(v))\n .replace(/!/g, '%21')\n .replace(/'/g, '%27')\n .replace(/\\(/g, '%28')\n .replace(/\\)/g, '%29')\n .replace(/\\*/g, '%2A');\n if (typeof v === 'string') {\n return `FILTER(STR(${varName}) = \"${raw}\" || STR(${varName}) = \"literal:string:${encoded}\")`;\n }\n else if (typeof v === 'number') {\n return `FILTER(STR(${varName}) = \"${v}\" || STR(${varName}) = \"literal:number:${v}\")`;\n }\n else if (typeof v === 'boolean') {\n return `FILTER(STR(${varName}) = \"${v}\" || STR(${varName}) = \"literal:boolean:${v}\")`;\n }\n return `FILTER(STR(${varName}) = \"${raw}\")`;\n }\n if (Array.isArray(condition)) {\n // Array values \u2192 FILTER IN\n if (isLiteral) {\n const varName = `?_wc${varSuffix}`;\n const inValues = condition.flatMap(v => {\n const raw = escapeQueryString(String(v));\n const encoded = encodeURIComponent(String(v))\n .replace(/!/g, '%21').replace(/'/g, '%27')\n .replace(/\\(/g, '%28').replace(/\\)/g, '%29').replace(/\\*/g, '%2A');\n return [`\"${raw}\"`, `\"literal:string:${encoded}\"`];\n }).join(', ');\n return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;\n }\n const formattedValues = condition.map(formatValue).join(', ');\n return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;\n }\n else if (typeof condition === 'object' && condition !== null) {\n // Operator object\n const ops = condition;\n const parts = [];\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formattedValues = ops.not.map((v) => formatValue(v)).join(', ');\n // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,\n // so O(N\u00B2) behavior is bounded by the number of values for this property.\n parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ?_nval . FILTER(?_nval IN (${formattedValues})) }`);\n }\n else {\n // FILTER NOT EXISTS here is scoped to a specific predicate, not a global scan,\n // so O(N\u00B2) behavior is bounded by the number of values for this property.\n parts.push(`FILTER NOT EXISTS { ?target <${escapedPredicate}> ${formatValue(ops.not)} }`);\n }\n }\n // Comparison operators \u2014 ensure property exists\n const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasComparisonOps) {\n parts.push(`FILTER EXISTS { ?target <${escapedPredicate}> ?_cmp }`);\n }\n return parts.join(' ');\n }\n else {\n // Simple equality\n if (isLiteral) {\n // Use FILTER matching (mirrors Rust build_projection_where_patterns)\n // to handle both raw values and literal-encoded IRIs robustly.\n const varName = `?_wc${varSuffix}`;\n return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;\n }\n return `?target <${escapedPredicate}> ${formatValue(condition)} .`;\n }\n}\n/**\n * Compile a full `Where` clause to an array of SPARQL condition strings.\n *\n * When `metadata` is provided, property names are resolved to predicates\n * using the model's property metadata. When `metadata` is `null`, property\n * names are treated as raw predicate URIs.\n *\n * Only handles **regular properties** \u2014 special fields (`id`, `author`,\n * `timestamp`) and relation fields are skipped (they are only relevant at\n * runtime query time, not for compile-time getter generation).\n */\nfunction compileWhereClause(where, metadata) {\n const conditions = [];\n for (const [propertyName, condition] of Object.entries(where)) {\n // Skip special fields that don't apply at compile time\n if (['id', 'author', 'timestamp'].includes(propertyName))\n continue;\n let predicate;\n let resolveLanguage;\n if (metadata) {\n const propMeta = metadata.properties[propertyName];\n if (propMeta) {\n predicate = propMeta.predicate;\n resolveLanguage = propMeta.resolveLanguage;\n }\n else {\n // Property not found in metadata \u2014 treat name as raw predicate URI\n predicate = propertyName;\n }\n }\n else {\n // No metadata \u2014 treat name as raw predicate URI\n predicate = propertyName;\n }\n const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });\n if (cond) {\n conditions.push(cond);\n }\n }\n return conditions;\n}\n\n/**\n * SHACL shape generation for AD4M model classes.\n *\n * Builds a W3C SHACL `SHACLShape` (with AD4M-specific action extensions)\n * from a model's property and relation metadata. The heavy lifting used\n * to live inside the `@Model` decorator closure \u2014 it is extracted here so\n * decorators.ts stays focused on decorator registration logic.\n */\n/**\n * Build a SHACL shape for a model class.\n *\n * @param subjectName - The model's registered name (from `@Model({ name })`)\n * @param target - The class constructor (used for prototype access,\n * inheritance chain, and relation target resolution)\n * @param properties - Merged property metadata (from `getPropertiesMetadata`)\n * @param allRelationsMeta - Merged relation metadata (from `getRelationsMetadata`)\n * @param conformanceFilterFn - Injected conformance-filter builder\n * (avoids circular dependency back into decorators.ts)\n */\nfunction buildSHACL(subjectName, target, properties, allRelationsMeta, conformanceFilterFn) {\n const obj = target.prototype;\n // \u2500\u2500 Determine namespace from first property or relation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let namespace = \"ad4m://\";\n const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));\n // Try properties first\n if (Object.keys(properties).length > 0) {\n const firstProp = properties[Object.keys(properties)[0]];\n if (firstProp.through) {\n const match = firstProp.through.match(/^([^:]+:\\/\\/)/);\n if (match) {\n namespace = match[1];\n }\n }\n }\n // Fall back to relations if no properties\n else if (Object.keys(relations).length > 0) {\n const firstRel = relations[Object.keys(relations)[0]];\n if (firstRel.predicate) {\n const match = firstRel.predicate.match(/^([^:]+:\\/\\/)/);\n if (match) {\n namespace = match[1];\n }\n }\n }\n // \u2500\u2500 Create SHACL shape \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const shapeUri = `${namespace}${subjectName}Shape`;\n const targetClass = `${namespace}${subjectName}`;\n const shape = new SHACLShape(shapeUri, targetClass);\n // Detect @Model inheritance \u2014 if the parent class also has\n // generateSHACL it is itself a @Model and we reference its shape\n // via sh:node so SHACL validators can walk the hierarchy.\n const parentCtor = Object.getPrototypeOf(target);\n if (parentCtor && typeof parentCtor.generateSHACL === 'function') {\n const parentSHACL = parentCtor.generateSHACL();\n if (parentSHACL?.shape?.nodeShapeUri) {\n shape.addParentShape(parentSHACL.shape.nodeShapeUri);\n }\n }\n // \u2500\u2500 Constructor / Destructor actions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n let constructorActions = [];\n if (obj.subjectConstructor && obj.subjectConstructor.length) {\n constructorActions = constructorActions.concat(obj.subjectConstructor);\n }\n let destructorActions = [];\n // \u2500\u2500 Convert properties to SHACL property shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const propName in properties) {\n const propMeta = properties[propName];\n if (!propMeta.through)\n continue; // Skip properties without predicates\n const propShape = {\n name: propName,\n path: propMeta.through,\n };\n // Determine datatype from initial value or resolveLanguage\n if (propMeta.resolveLanguage === \"literal\") {\n propShape.datatype = \"xsd://string\";\n }\n else if (propMeta.initial) {\n const initialType = typeof obj[propName];\n if (initialType === \"number\") {\n propShape.datatype = \"xsd://integer\";\n }\n else if (initialType === \"boolean\") {\n propShape.datatype = \"xsd://boolean\";\n }\n else if (initialType === \"string\") {\n propShape.datatype = \"xsd://string\";\n }\n }\n // Cardinality constraints\n if (propMeta.required) {\n propShape.minCount = 1;\n }\n // Single-valued properties get maxCount 1\n propShape.maxCount = 1;\n // Flag properties have fixed value\n if (propMeta.flag && propMeta.initial) {\n propShape.hasValue = propMeta.initial;\n }\n // sh:in \u2014 allowed values (enum constraint)\n if (propMeta.options && propMeta.options.length > 0) {\n propShape.in = propMeta.options;\n }\n // AD4M-specific metadata\n if (propMeta.local !== undefined) {\n propShape.local = propMeta.local;\n }\n if (propMeta.writable !== undefined) {\n propShape.writable = propMeta.writable;\n }\n if (propMeta.resolveLanguage) {\n propShape.resolveLanguage = propMeta.resolveLanguage;\n }\n // \u2500\u2500 Setter actions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (propMeta.prologSetter) {\n console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +\n `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);\n }\n else if (propMeta.writable && propMeta.through) {\n let setter = obj[propertyNameToSetterName(propName)];\n if (typeof setter === \"function\") {\n propShape.setter = [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: propMeta.through,\n target: \"value\",\n ...(propMeta.local && { local: true })\n }];\n }\n }\n // \u2500\u2500 Constructor / Destructor entries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const effectiveInitial = propMeta.initial\n ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through\n ? \"literal:string:\" : undefined);\n if (effectiveInitial) {\n constructorActions.push({\n action: \"addLink\",\n source: \"this\",\n predicate: propMeta.through,\n target: effectiveInitial,\n });\n destructorActions.push({\n action: \"removeLink\",\n source: \"this\",\n predicate: propMeta.through,\n target: \"*\",\n });\n }\n shape.addProperty(propShape);\n }\n // \u2500\u2500 Convert relations to SHACL property shapes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n for (const relName in relations) {\n const relMeta = relations[relName];\n if (!relMeta.predicate)\n continue;\n const relShape = {\n name: relName,\n path: relMeta.predicate,\n };\n // Relations typically contain IRIs\n relShape.nodeKind = 'IRI';\n // AD4M-specific metadata\n if (relMeta.local !== undefined) {\n relShape.local = relMeta.local;\n }\n // Adder action\n relShape.adder = [{\n action: \"addLink\",\n source: \"this\",\n predicate: relMeta.predicate,\n target: \"value\",\n ...(relMeta.local && { local: true })\n }];\n // Remover action\n relShape.remover = [{\n action: \"removeLink\",\n source: \"this\",\n predicate: relMeta.predicate,\n target: \"value\",\n ...(relMeta.local && { local: true })\n }];\n // \u2500\u2500 Build Getter (conformance filter) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Priority chain:\n // 1. Explicit getter string \u2192 use verbatim\n // 2. `where` clause \u2192 compile DSL to SPARQL getter\n // 3. target + filter !== false \u2192 auto-derive from shape\n if (relMeta.getter) {\n relShape.getter = relMeta.getter;\n }\n else if (relMeta.where) {\n try {\n const TargetClass = relMeta.target?.();\n const targetMetadata = TargetClass\n ? TargetClass.getModelMetadata?.() ?? null\n : null;\n const conditions = compileWhereClause(relMeta.where, targetMetadata);\n if (conditions.length > 0) {\n const escapedPredicate = escapeQueryString(relMeta.predicate);\n relShape.getter = `SELECT ?target WHERE { <Base> <${escapedPredicate}> ?target . ${conditions.join(' ')} }`;\n }\n }\n catch (e) {\n // Target metadata may not be available yet\n }\n }\n else if (relMeta.target && relMeta.filter !== false) {\n // Lazy conformance filter: store deferred reference,\n // resolve on first access via a getter on relShape\n const targetThunk = relMeta.target;\n const predicate = relMeta.predicate;\n let resolved = false;\n let cachedGetter;\n let cachedConditions;\n const resolveFilter = () => {\n if (resolved)\n return;\n resolved = true;\n try {\n const TargetClass = targetThunk();\n const filter = conformanceFilterFn(predicate, TargetClass);\n if (filter) {\n cachedGetter = filter.getter;\n cachedConditions = filter.conformanceConditions;\n }\n }\n catch (e) {\n // Target class may not be available yet\n }\n };\n // Define lazy getters that resolve on first access\n Object.defineProperty(relShape, 'getter', {\n get() { resolveFilter(); return cachedGetter; },\n set(v) { resolved = true; cachedGetter = v; },\n enumerable: true,\n configurable: true,\n });\n Object.defineProperty(relShape, 'conformanceConditions', {\n get() { resolveFilter(); return cachedConditions; },\n set(v) { resolved = true; cachedConditions = v; },\n enumerable: true,\n configurable: true,\n });\n }\n // \u2500\u2500 sh:class \u2014 target shape reference \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (relMeta.target) {\n try {\n const TargetClass = relMeta.target();\n const targetSHACL = TargetClass.generateSHACL?.();\n if (targetSHACL?.shape?.nodeShapeUri) {\n relShape.class = targetSHACL.shape.nodeShapeUri;\n }\n }\n catch (e) {\n // Target class may not be available yet\n }\n }\n shape.addProperty(relShape);\n }\n // Always set constructor and destructor actions on the shape, even\n // when empty. An empty array serialises to `literal:string:[]`\n // which the Rust executor parses as a valid (no-op) command list,\n // avoiding \"No SHACL constructor found\" errors for models whose\n // properties are all optional and have no @Flag.\n shape.setConstructorActions(constructorActions);\n shape.setDestructorActions(destructorActions);\n return {\n shape,\n name: subjectName\n };\n}\n\n/** Registry of property metadata keyed by constructor \u2192 { propName \u2192 metadata } */\nconst propertyRegistry = new WeakMap();\n/** Registry of relation metadata keyed by constructor \u2192 { propName \u2192 metadata } */\nconst relationRegistry = new WeakMap();\n/** Memoisation cache for getPropertiesMetadata \u2014 avoids repeated prototype-chain walks */\nconst propertiesMetadataCache = new WeakMap();\n/** Memoisation cache for getRelationsMetadata \u2014 avoids repeated prototype-chain walks */\nconst relationsMetadataCache = new WeakMap();\n/** Memoisation cache for generateSHACL \u2014 avoids recomputing SHACL shapes */\nconst shaclCache = new WeakMap();\n/**\n * Retrieve property metadata for a given class constructor.\n * Walks the prototype chain so subclass decorators compose with parent decorators.\n * Results are memoised per class constructor.\n */\nfunction getPropertiesMetadata(ctor) {\n const cached = propertiesMetadataCache.get(ctor);\n if (cached)\n return cached;\n const result = {};\n const chain = [];\n let current = ctor;\n while (current && current !== Object) {\n chain.unshift(current); // parent-first order\n current = Object.getPrototypeOf(current);\n }\n for (const c of chain) {\n const meta = propertyRegistry.get(c);\n if (meta)\n Object.assign(result, meta);\n }\n propertiesMetadataCache.set(ctor, result);\n return result;\n}\n/**\n * Retrieve relation metadata for a given class constructor.\n * Walks the prototype chain so subclass decorators compose with parent decorators.\n * Results are memoised per class constructor.\n */\nfunction getRelationsMetadata(ctor) {\n const cached = relationsMetadataCache.get(ctor);\n if (cached)\n return cached;\n const result = {};\n const chain = [];\n let current = ctor;\n while (current && current !== Object) {\n chain.unshift(current);\n current = Object.getPrototypeOf(current);\n }\n for (const c of chain) {\n const meta = relationRegistry.get(c);\n if (meta)\n Object.assign(result, meta);\n }\n relationsMetadataCache.set(ctor, result);\n return result;\n}\n/**\n * Get or compute memoised SHACL for a class. Used by @Model decorator.\n */\nfunction getMemoizedSHACL(target, compute) {\n const cached = shaclCache.get(target);\n if (cached)\n return cached;\n const result = compute();\n shaclCache.set(target, result);\n return result;\n}\n/**\n * Programmatically register property metadata for a given constructor.\n * Used by `fromJSONSchema()` and other dynamic model builders.\n */\nfunction setPropertyRegistryEntry(ctor, propName, meta) {\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[propName] = meta;\n}\n/**\n * Programmatically register relation metadata for a given constructor.\n * Used by `fromJSONSchema()` and other dynamic model builders.\n */\nfunction setRelationRegistryEntry(ctor, relName, meta) {\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n relationRegistry.get(ctor)[relName] = meta;\n}\n/**\n * Build a conformance filter for a relation whose target model is known.\n *\n * Inspects the target class's property metadata to derive:\n * - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)\n * - `getter`: Pre-computed graph traversal expression that traverses outgoing links and filters\n * target nodes to only those conforming to the target shape.\n *\n * @param relationPredicate - The relation's predicate URI (e.g. \"flux://entry_type\")\n * @param targetClass - The target model class (resolved from the target() thunk)\n * @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived\n */\nfunction buildConformanceFilter(relationPredicate, targetClass) {\n try {\n const targetProps = getPropertiesMetadata(targetClass);\n const conditions = [];\n const sparqlConditions = [];\n let varIdx = 0;\n // 1. Flags \u2014 check predicate + value\n for (const [_propName, propMeta] of Object.entries(targetProps)) {\n if (propMeta.flag && propMeta.initial && propMeta.through) {\n conditions.push({\n type: 'flag',\n predicate: propMeta.through,\n value: propMeta.initial,\n });\n sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> <${escapeQueryString(propMeta.initial)}> .`);\n }\n }\n // 2. Required (non-flag) properties \u2014 check predicate exists\n // Skip properties with custom getters (they don't follow the standard link pattern)\n for (const [_propName, propMeta] of Object.entries(targetProps)) {\n if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {\n conditions.push({\n type: 'required',\n predicate: propMeta.through,\n });\n sparqlConditions.push(`?target <${escapeQueryString(propMeta.through)}> ?_v${varIdx++} .`);\n }\n }\n if (conditions.length === 0) {\n return undefined;\n }\n const getter = `SELECT ?target WHERE { <Base> <${escapeQueryString(relationPredicate)}> ?target . ${sparqlConditions.join(' ')} }`;\n return { getter, conformanceConditions: conditions };\n }\n catch (e) {\n // Target class may not have property metadata\n return undefined;\n }\n}\n/**\n * Internal core implementation for registering property metadata on the prototype.\n * All property decorators (@Property, @Optional, @ReadOnly) and relation decorators\n * that create properties delegate to this function.\n * @internal\n */\nfunction applyPropertyMetadata(opts) {\n return function (target, key) {\n // Map readOnly \u2192 internal writable for SDNA/SHACL compatibility\n const writable = opts.readOnly ? false : (opts.through ? true : false);\n if (opts.required && !opts.initial) {\n throw new Error(\"SubjectProperty requires an 'initial' option if 'required' is true\");\n }\n if (!opts.through && !opts.prologGetter && !opts.getter) {\n throw new Error(\"SubjectProperty requires either 'through' or 'prologGetter' or 'getter' option\");\n }\n // Write to WeakMap registry (keyed by constructor)\n const ctor = target.constructor;\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[key] = { ...opts, writable };\n if (writable) {\n const value = key;\n target[`set${capitalize(value)}`] = () => { };\n }\n Object.defineProperty(target, key, { configurable: true, writable: true });\n };\n}\n/**\n * Convenience decorator for defining optional (not required) properties.\n *\n * @category Decorators\n *\n * @description\n * Equivalent to `@Property` but defaults `required` to `false` and does not\n * apply `resolveLanguage` or `initial` defaults. Use this when a property\n * may or may not have a value, and you want full control over its configuration.\n *\n * @example\n * ```typescript\n * class Recipe extends Ad4mModel {\n * @Optional({ through: \"recipe://description\" })\n * description?: string;\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration (same options as @Property)\n */\nfunction Optional(opts) {\n return applyPropertyMetadata({\n ...opts,\n required: opts.required ?? false,\n readOnly: opts.readOnly ?? false,\n });\n}\n/**\n * Decorator for defining flags on model classes.\n *\n * @category Decorators\n *\n * @description\n * A specialized property decorator for defining immutable type flags or markers on model instances.\n * Flags are always required properties with a fixed value that cannot be changed after creation.\n *\n * Common uses for flags:\n * - Type discrimination between different kinds of models\n * - Marking models with specific capabilities or features\n * - Versioning or compatibility markers\n *\n * Note: Use of Flag is discouraged unless you specifically need type-based filtering or\n * discrimination between different kinds of models. For most cases, regular properties\n * with @Property or @Optional are more appropriate.\n *\n * @example\n * ```typescript\n * class Message extends Ad4mModel {\n * // Type flag to identify message models\n * @Flag({\n * through: \"ad4m://type\",\n * value: \"ad4m://message\"\n * })\n * type: string = \"\";\n *\n * // Version flag for compatibility\n * @Flag({\n * through: \"ad4m://version\",\n * value: \"1.0.0\"\n * })\n * version: string = \"\";\n *\n * // Feature flag\n * @Flag({\n * through: \"message://feature\",\n * value: \"message://encrypted\"\n * })\n * feature: string = \"\";\n * }\n *\n * // Later you can query for specific types:\n * const messages = await Message.query(perspective)\n * .where({ type: \"ad4m://message\" })\n * .run();\n * ```\n *\n * @param {FlagOptions} opts - Flag configuration\n * @param {string} opts.through - The predicate URI for the flag\n * @param {string} opts.value - The fixed value for the flag\n */\nfunction Flag(opts) {\n return function (target, key) {\n if (!opts.through && !opts.value) {\n throw new Error(\"SubjectFlag requires a 'through' and 'value' option\");\n }\n if (!opts.through) {\n throw new Error(\"SubjectFlag requires a 'through' option\");\n }\n if (!opts.value) {\n throw new Error(\"SubjectFlag requires a 'value' option\");\n }\n const entry = {\n through: opts.through,\n required: true,\n initial: opts.value,\n flag: true,\n readOnly: true,\n writable: false,\n };\n // Write to WeakMap registry\n const ctor = target.constructor;\n if (!propertyRegistry.has(ctor))\n propertyRegistry.set(ctor, {});\n propertyRegistry.get(ctor)[key] = entry;\n // @ts-ignore\n target[key] = opts.value;\n Object.defineProperty(target, key, { configurable: true, writable: true });\n };\n}\n/**\n * Decorator for defining model classes in AD4M.\n *\n * @category Decorators\n *\n * @description\n * The root decorator that must be applied to any class that represents a model in AD4M.\n * It registers the class as a Social DNA (SDNA) subject class and provides the infrastructure\n * for storing and retrieving instances.\n *\n * This decorator:\n * - Registers the class with a unique name in the AD4M system\n * - Generates the necessary SDNA code for the model's properties and relations\n * - Enables the use of other model decorators (@Property, @HasMany, etc.)\n * - Provides static query methods through the Ad4mModel base class\n *\n * @example\n * ```typescript\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * @Property({\n * through: \"recipe://name\",\n * resolveLanguage: \"literal\"\n * })\n * name: string = \"\";\n *\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n *\n * // Static query methods from Ad4mModel:\n * static async findByName(perspective: PerspectiveProxy, name: string) {\n * return Recipe.query(perspective)\n * .where({ name })\n * .run();\n * }\n * }\n *\n * // Using the model:\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Chocolate Cake\";\n * await recipe.save();\n *\n * // Querying instances:\n * const recipes = await Recipe.query(perspective)\n * .where({ name: \"Chocolate Cake\" })\n * .run();\n *\n * // Using with PerspectiveProxy:\n * await perspective.ensureSDNASubjectClass(Recipe);\n * ```\n *\n * @param {ModelConfig} opts - Model configuration\n * @param {string} opts.name - Unique name for the model class in AD4M\n */\nfunction Model$1(opts) {\n return function (target) {\n target.prototype.className = opts.name;\n target.className = opts.name;\n target.generateSDNA = function () {\n return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));\n };\n target.generateSHACL = function () {\n return getMemoizedSHACL(target, () => buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter));\n };\n Object.defineProperty(target, 'type', { configurable: true });\n };\n}\n/**\n * The primary property decorator for AD4M model classes.\n *\n * @category Decorators\n *\n * @description\n * The core property decorator with smart defaults. All other property decorators\n * (@Optional, @ReadOnly) are thin wrappers that adjust these defaults.\n *\n * Smart defaults (all overridable):\n * - `required` \u2192 `false`\n * - `readOnly` \u2192 `false`\n * - `resolveLanguage` \u2192 `\"literal\"`\n * - `initial` \u2192 `undefined` (no link created until a value is explicitly set)\n *\n * Properties are optional by default. When a model instance is created without\n * providing a value for an optional property, no link is added to the graph.\n * Set `required: true` explicitly when a property must always be present (this\n * also adds a `\"literal:string:uninitialized\"` sentinel as the initial value\n * so that the SDNA constructor creates a placeholder link).\n *\n * @example\n * ```typescript\n * class User extends Ad4mModel {\n * // Optional property (default) \u2014 no link created until a value is set\n * @Property({\n * through: \"user://name\"\n * })\n * name: string = \"\";\n *\n * // Explicitly required property with sentinel initial value\n * @Property({\n * through: \"user://status\",\n * required: true\n * })\n * status: string = \"\";\n *\n * // Required property with custom initial value\n * @Property({\n * through: \"user://role\",\n * required: true,\n * initial: \"user://member\"\n * })\n * role: string = \"\";\n *\n * // Optional property with literal resolution\n * @Property({\n * through: \"user://bio\",\n * resolveLanguage: \"literal\"\n * })\n * bio: string = \"\";\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration\n * @param {string} opts.through - The predicate URI for the property\n * @param {boolean} [opts.required=false] - Whether the property is required (adds query filters and sentinel initial value)\n * @param {string} [opts.initial] - Initial value (defaults to \"literal:string:uninitialized\" when required)\n * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. \"literal\")\n * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value\n * @param {string} [opts.prologSetter] - Custom Prolog code for setting the property value\n * @param {boolean} [opts.local] - Whether the property should only be stored locally\n */\nfunction Property(opts) {\n const required = opts.required ?? false;\n return applyPropertyMetadata({\n ...opts,\n required,\n readOnly: opts.readOnly ?? false,\n resolveLanguage: opts.resolveLanguage ?? \"literal\",\n initial: opts.initial ?? (required ? \"literal:string:uninitialized\" : undefined),\n });\n}\n/**\n * Decorator for defining read-only properties on model classes.\n *\n * @category Decorators\n *\n * @description\n * A convenience decorator that defines a read-only property.\n * Equivalent to `@Property` with `readOnly: true`.\n *\n * Read-only properties are ideal for:\n * - Computed or derived values\n * - Properties that should never change after creation\n * - Properties that are set by the system\n * - Properties that represent immutable data\n *\n * @example\n * ```typescript\n * class Post extends Ad4mModel {\n * // Read-only property with custom getter for computed value\n * @ReadOnly({\n * through: \"post://likes\",\n * getter: `findall(User, triple(Base, \"post://liked_by\", User), Users), length(Users, Value)`\n * })\n * likeCount: number = 0;\n *\n * // Read-only property for creation timestamp\n * @ReadOnly({\n * through: \"post://created_at\",\n * initial: new Date().toISOString()\n * })\n * createdAt: string = \"\";\n *\n * // Read-only property that resolves to a Literal\n * @ReadOnly({\n * through: \"post://author\",\n * resolveLanguage: \"literal\"\n * })\n * author: string = \"\";\n *\n * // Read-only property for system-managed data\n * @ReadOnly({\n * through: \"post://version\",\n * initial: \"1.0.0\"\n * })\n * version: string = \"\";\n * }\n * ```\n *\n * @param {PropertyOptions} opts - Property configuration\n * @param {string} opts.through - The predicate URI for the property\n * @param {string} [opts.initial] - Initial value (if property should have one)\n * @param {string} [opts.resolveLanguage] - Language to use for value resolution (e.g. \"literal\")\n * @param {string} [opts.prologGetter] - Custom Prolog code for getting the property value\n * @param {boolean} [opts.local] - Whether the property should only be stored locally\n */\nfunction ReadOnly(opts) {\n return Property({\n ...opts,\n readOnly: true,\n });\n}\n/**\n * Resolve overloaded relation decorator arguments.\n * Supports two calling conventions:\n * @HasMany({ through: \"...\", target: () => X }) \u2014 single options object\n * @HasMany(() => X, { through: \"...\" }) \u2014 target thunk + options\n * @internal\n */\nfunction resolveRelationArgs(first, second) {\n const opts = typeof first === 'function'\n ? { ...(second || {}), target: first }\n : first;\n // getter is mutually exclusive with through, target, and where\n if (opts.getter) {\n if (opts.through) {\n throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +\n 'Use `getter` alone for custom read-only relations, or `through` ' +\n '(with optional `target`) for standard link-based relations.');\n }\n if (opts.target) {\n throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +\n '`target` auto-generates a conformance getter from the model shape; ' +\n 'providing both is contradictory.');\n }\n if (opts.where) {\n throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +\n 'Use `where` for DSL-based filtering, or `getter` for raw getter expression.');\n }\n return opts;\n }\n // Default predicate when not provided\n if (!opts.through) {\n opts.through = 'ad4m://has_child';\n }\n // where validation\n if (opts.where) {\n if (opts.filter === false) {\n throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +\n '`where` adds filtering constraints; `filter: false` disables filtering.');\n }\n }\n return opts;\n}\nfunction HasMany(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n // --- relation registry ---\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'hasMany',\n local: opts.local,\n ...(opts.getter && { getter: opts.getter }),\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n const relKey = key;\n // Only add mutation methods when a predicate is available\n // (getter-only relations are read-only)\n if (opts.through) {\n target[`add${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.addRelationValue(relKey, arg, batchId);\n };\n target[`remove${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.removeRelationValue(relKey, arg, batchId);\n };\n target[`set${capitalize(relKey)}`] = async function (arg, batchId) {\n return this.setRelationValues(relKey, arg, batchId);\n };\n }\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n };\n}\nfunction HasOne(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'hasOne',\n maxCount: 1,\n local: opts.local,\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n const relKey = key;\n if (opts.through) {\n // Register as a writable property\n applyPropertyMetadata({\n through: opts.through,\n readOnly: false,\n local: opts.local,\n })(target, key);\n // Add prototype methods for add/remove/set (mirroring @HasMany)\n target[`add${capitalize(relKey)}`] = async function (arg) {\n return this.addRelationValue(relKey, arg);\n };\n target[`remove${capitalize(relKey)}`] = async function (arg) {\n return this.removeRelationValue(relKey, arg);\n };\n target[`set${capitalize(relKey)}`] = async function (arg) {\n return this.setRelationValues(relKey, arg);\n };\n }\n else {\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n }\n };\n}\nfunction BelongsToOne(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'belongsToOne',\n maxCount: 1,\n local: opts.local,\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n if (opts.through) {\n // Read-only property (the owning side manages the link)\n applyPropertyMetadata({\n through: opts.through,\n readOnly: true,\n local: opts.local,\n })(target, key);\n }\n else {\n Object.defineProperty(target, key, { configurable: true, writable: true });\n }\n };\n}\nfunction BelongsToMany(first, second) {\n const opts = resolveRelationArgs(first, second);\n return function (target, key) {\n const ctor = target.constructor;\n if (!relationRegistry.has(ctor))\n relationRegistry.set(ctor, {});\n const map = relationRegistry.get(ctor);\n map[key] = {\n predicate: opts.through,\n target: opts.target,\n kind: 'belongsToMany',\n local: opts.local,\n ...(opts.getter && { getter: opts.getter }),\n ...(opts.filter !== undefined && { filter: opts.filter }),\n ...(opts.where && { where: opts.where }),\n };\n // @BelongsToMany is the inverse/read-only side \u2014 do NOT generate add*/remove*/set*\n // prototype methods. Mutation must go through the owning side's @HasMany decorator.\n const relKey = key;\n Object.defineProperty(target, relKey, { configurable: true, writable: true });\n };\n}\n\n/**\n * Query Result TTL Cache\n *\n * Short-lived cache (200ms TTL) for SPARQL query results.\n * Prevents redundant queries during rapid render cycles where\n * multiple components issue the same query within milliseconds.\n *\n * Key: `perspectiveUUID + queryText`\n */\nconst cache = new Map();\nconst DEFAULT_TTL_MS = 200;\nfunction makeKey(perspectiveUUID, queryText) {\n return `${perspectiveUUID}:${queryText}`;\n}\n/**\n * Get a cached query result if it exists and hasn't expired.\n */\nfunction getCachedResult(perspectiveUUID, queryText) {\n const key = makeKey(perspectiveUUID, queryText);\n const entry = cache.get(key);\n if (!entry)\n return undefined;\n if (Date.now() > entry.expiry) {\n cache.delete(key);\n return undefined;\n }\n return entry.result;\n}\n/**\n * Store a query result in the cache with TTL.\n */\nfunction setCachedResult(perspectiveUUID, queryText, result, ttlMs = DEFAULT_TTL_MS) {\n // Lazy eviction of expired entries\n const now = Date.now();\n for (const [key, entry] of cache) {\n if (now > entry.expiry) {\n cache.delete(key);\n }\n }\n const cacheKey = makeKey(perspectiveUUID, queryText);\n cache.set(cacheKey, { result, expiry: now + ttlMs });\n}\n/**\n * Invalidate all cache entries for a given perspective.\n * Called after write operations to ensure stale data isn't served.\n */\nfunction invalidatePerspectiveCache(perspectiveUUID) {\n const prefix = perspectiveUUID + ':';\n for (const [key] of cache) {\n if (key.startsWith(prefix)) {\n cache.delete(key);\n }\n }\n}\n/**\n * Clear all cache entries (useful for testing).\n */\nfunction clearQueryCache() {\n cache.clear();\n}\n/**\n * Get the current size of the cache (useful for testing).\n */\nfunction queryCacheSize() {\n return cache.size;\n}\n\n/**\n * SHACL Flow - represents a state machine for AD4M expressions\n *\n * Flows define:\n * - Which expressions can enter the flow (flowable condition)\n * - What states exist and how to detect them (via link patterns)\n * - How to transition between states (via actions)\n *\n * @example\n * ```typescript\n * const todoFlow = new SHACLFlow('todo://TODO', 'todo://');\n *\n * // Any expression can become a TODO\n * todoFlow.flowable = 'any';\n *\n * // Define states\n * todoFlow.addState({\n * name: 'ready',\n * value: 0,\n * stateCheck: { predicate: 'todo://state', target: 'todo://ready' }\n * });\n * todoFlow.addState({\n * name: 'doing',\n * value: 0.5,\n * stateCheck: { predicate: 'todo://state', target: 'todo://doing' }\n * });\n * todoFlow.addState({\n * name: 'done',\n * value: 1,\n * stateCheck: { predicate: 'todo://state', target: 'todo://done' }\n * });\n *\n * // Define start action\n * todoFlow.startAction = [{\n * action: 'addLink',\n * source: 'this',\n * predicate: 'todo://state',\n * target: 'todo://ready'\n * }];\n *\n * // Define transitions\n * todoFlow.addTransition({\n * actionName: 'Start',\n * fromState: 'ready',\n * toState: 'doing',\n * actions: [\n * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://doing' },\n * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }\n * ]\n * });\n *\n * // Store in perspective\n * await perspective.addFlow('TODO', todoFlow);\n * ```\n */\nclass SHACLFlow {\n /**\n * Create a new SHACL Flow\n * @param name - Flow name (e.g., \"TODO\")\n * @param namespace - Namespace for URIs (e.g., \"todo://\")\n */\n constructor(name, namespace) {\n /** Condition for which expressions can start this flow */\n this.flowable = \"any\";\n /** Actions to execute when starting the flow */\n this.startAction = [];\n /** States in this flow */\n this._states = [];\n /** Transitions between states */\n this._transitions = [];\n this.name = name;\n this.namespace = namespace;\n }\n /** Get all states */\n get states() {\n return [...this._states];\n }\n /** Get all transitions */\n get transitions() {\n return [...this._transitions];\n }\n /**\n * Add a state to the flow\n * @param state - State definition\n */\n addState(state) {\n this._states.push(state);\n }\n /**\n * Add a transition to the flow\n * @param transition - Transition definition\n */\n addTransition(transition) {\n this._transitions.push(transition);\n }\n /**\n * Get the flow shape URI\n */\n get flowUri() {\n return `${this.namespace}${this.name}Flow`;\n }\n /**\n * Get a state URI\n */\n stateUri(stateName) {\n return `${this.namespace}${this.name}.${stateName}`;\n }\n /**\n * Get a transition URI\n */\n transitionUri(fromState, toState) {\n return `${this.namespace}${this.name}.${fromState}To${toState}`;\n }\n /**\n * Serialize the flow to AD4M links\n * These links can be stored in a perspective and queried via SPARQL\n *\n * @returns Array of Link objects representing the flow\n */\n toLinks() {\n const links = [];\n const flowUri = this.flowUri;\n // Flow type\n links.push({\n source: flowUri,\n predicate: \"rdf://type\",\n target: \"ad4m://Flow\"\n });\n // Flow name\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowName\",\n target: Literal.from(this.name).toUrl()\n });\n // Flowable condition\n if (this.flowable === \"any\") {\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowable\",\n target: \"ad4m://any\"\n });\n }\n else {\n links.push({\n source: flowUri,\n predicate: \"ad4m://flowable\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(this.flowable))}`\n });\n }\n // Start action\n if (this.startAction.length > 0) {\n links.push({\n source: flowUri,\n predicate: \"ad4m://startAction\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(this.startAction))}`\n });\n }\n // States\n for (const state of this._states) {\n const stateUri = this.stateUri(state.name);\n // Link flow to state\n links.push({\n source: flowUri,\n predicate: \"ad4m://hasState\",\n target: stateUri\n });\n // State type\n links.push({\n source: stateUri,\n predicate: \"rdf://type\",\n target: \"ad4m://FlowState\"\n });\n // State name\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateName\",\n target: Literal.from(state.name).toUrl()\n });\n // State value\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateValue\",\n target: Literal.from(state.value).toUrl()\n });\n // State check pattern\n links.push({\n source: stateUri,\n predicate: \"ad4m://stateCheck\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(state.stateCheck))}`\n });\n }\n // Transitions\n for (const transition of this._transitions) {\n const transitionUri = this.transitionUri(transition.fromState, transition.toState);\n const fromStateUri = this.stateUri(transition.fromState);\n const toStateUri = this.stateUri(transition.toState);\n // Link flow to transition\n links.push({\n source: flowUri,\n predicate: \"ad4m://hasTransition\",\n target: transitionUri\n });\n // Transition type\n links.push({\n source: transitionUri,\n predicate: \"rdf://type\",\n target: \"ad4m://FlowTransition\"\n });\n // Action name\n links.push({\n source: transitionUri,\n predicate: \"ad4m://actionName\",\n target: Literal.from(transition.actionName).toUrl()\n });\n // From state\n links.push({\n source: transitionUri,\n predicate: \"ad4m://fromState\",\n target: fromStateUri\n });\n // To state\n links.push({\n source: transitionUri,\n predicate: \"ad4m://toState\",\n target: toStateUri\n });\n // Transition actions\n links.push({\n source: transitionUri,\n predicate: \"ad4m://transitionActions\",\n target: `literal:string:${encodeURIComponent(JSON.stringify(transition.actions))}`\n });\n }\n return links;\n }\n /**\n * Reconstruct a SHACLFlow from links\n *\n * @param links - Array of links containing the flow definition\n * @param flowUri - The URI of the flow to reconstruct\n * @returns Reconstructed SHACLFlow\n */\n static fromLinks(links, flowUri) {\n // Extract namespace and name from flowUri\n // Format: {namespace}{Name}Flow\n const flowSuffix = \"Flow\";\n if (!flowUri.endsWith(flowSuffix)) {\n throw new Error(`Invalid flow URI: ${flowUri} (must end with 'Flow')`);\n }\n const withoutSuffix = flowUri.slice(0, -flowSuffix.length);\n const lastSlashOrColon = Math.max(withoutSuffix.lastIndexOf('/'), withoutSuffix.lastIndexOf(':'));\n const namespace = withoutSuffix.slice(0, lastSlashOrColon + 1);\n const name = withoutSuffix.slice(lastSlashOrColon + 1);\n const flow = new SHACLFlow(name, namespace);\n // Find flowable condition\n const flowableLink = links.find(l => l.source === flowUri && l.predicate === \"ad4m://flowable\");\n if (flowableLink) {\n if (flowableLink.target === \"ad4m://any\") {\n flow.flowable = \"any\";\n }\n else {\n try {\n const jsonStr = flowableLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n flow.flowable = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n flow.flowable = \"any\";\n }\n }\n }\n // Find start action\n const startActionLink = links.find(l => l.source === flowUri && l.predicate === \"ad4m://startAction\");\n if (startActionLink) {\n try {\n const jsonStr = startActionLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n flow.startAction = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n // Find states\n const stateLinks = links.filter(l => l.source === flowUri && l.predicate === \"ad4m://hasState\");\n // Build a map from state URI to state name for later lookup\n const stateUriToName = new Map();\n for (const stateLink of stateLinks) {\n const stateUri = stateLink.target;\n // Get state name\n const nameLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateName\");\n const stateName = nameLink ? Literal.fromUrl(nameLink.target).get() : \"\";\n // Store mapping for transition lookup\n stateUriToName.set(stateUri, stateName);\n // Get state value\n const valueLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateValue\");\n const stateValue = valueLink ? Literal.fromUrl(valueLink.target).get() : 0;\n // Get state check\n const checkLink = links.find(l => l.source === stateUri && l.predicate === \"ad4m://stateCheck\");\n let stateCheck = { predicate: \"\", target: \"\" };\n if (checkLink) {\n try {\n const jsonStr = checkLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n stateCheck = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n flow.addState({ name: stateName, value: stateValue, stateCheck });\n }\n // Find transitions\n const transitionLinks = links.filter(l => l.source === flowUri && l.predicate === \"ad4m://hasTransition\");\n for (const transitionLink of transitionLinks) {\n const transitionUri = transitionLink.target;\n // Get action name\n const actionNameLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://actionName\");\n const actionName = actionNameLink ? Literal.fromUrl(actionNameLink.target).get() : \"\";\n // Get from state\n const fromStateLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://fromState\");\n const fromStateUri = fromStateLink?.target || \"\";\n const fromState = stateUriToName.get(fromStateUri) || \"\";\n // Get to state\n const toStateLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://toState\");\n const toStateUri = toStateLink?.target || \"\";\n const toState = stateUriToName.get(toStateUri) || \"\";\n // Get actions\n const actionsLink = links.find(l => l.source === transitionUri && l.predicate === \"ad4m://transitionActions\");\n let actions = [];\n if (actionsLink) {\n try {\n const jsonStr = actionsLink.target.replace(/^literal:\\/\\/string:|^literal:string:/, '');\n actions = JSON.parse(decodeURIComponent(jsonStr));\n }\n catch {\n // Ignore parse errors\n }\n }\n flow.addTransition({ actionName, fromState, toState, actions });\n }\n return flow;\n }\n /**\n * Convert to JSON representation\n */\n toJSON() {\n return {\n name: this.name,\n namespace: this.namespace,\n flowable: this.flowable,\n startAction: this.startAction,\n states: this._states,\n transitions: this._transitions\n };\n }\n /**\n * Create from JSON representation\n */\n static fromJSON(json) {\n const flow = new SHACLFlow(json.name, json.namespace);\n flow.flowable = json.flowable || \"any\";\n flow.startAction = json.startAction || [];\n for (const state of json.states || []) {\n flow.addState(state);\n }\n for (const transition of json.transitions || []) {\n flow.addTransition(transition);\n }\n return flow;\n }\n}\n\nvar __classPrivateFieldSet$a = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$a = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _QuerySubscriptionProxy_instances, _QuerySubscriptionProxy_uuid, _QuerySubscriptionProxy_subscriptionId, _QuerySubscriptionProxy_client, _QuerySubscriptionProxy_callbacks, _QuerySubscriptionProxy_keepaliveTimer, _QuerySubscriptionProxy_unsubscribe, _QuerySubscriptionProxy_latestResult, _QuerySubscriptionProxy_disposed, _QuerySubscriptionProxy_initialized, _QuerySubscriptionProxy_initResolve, _QuerySubscriptionProxy_initReject, _QuerySubscriptionProxy_initTimeoutId, _QuerySubscriptionProxy_query, _QuerySubscriptionProxy_notifyCallbacks, _PerspectiveProxy_handle, _PerspectiveProxy_client, _PerspectiveProxy_perspectiveLinkAddedCallbacks, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, _PerspectiveProxy_ensuredSubjectClasses;\n/** Extract namespace prefix from a URI (everything up to and including the last / or #) */\nfunction extractNamespaceFromUri(uri) {\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(0, hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(0, slashIdx + 1);\n const colonIdx = uri.lastIndexOf(':');\n if (colonIdx >= 0)\n return uri.substring(0, colonIdx + 1);\n return uri;\n}\n/** Proxy object for a subscribed Prolog query that provides real-time updates\n *\n * This class handles:\n * - Keeping the subscription alive by sending periodic keepalive signals\n * - Managing callbacks for result updates\n * - Subscribing to query updates via WebSocket subscriptions\n * - Maintaining the latest query result\n * - Ensuring subscription is fully initialized before allowing access\n * - Cleaning up resources when disposed\n *\n * The subscription will remain active as long as keepalive signals are sent.\n * Make sure to call dispose() when you're done with the subscription to clean up\n * resources, stop keepalive signals, and notify the backend to remove the subscription.\n *\n * The subscription goes through an initialization process where it waits for the first\n * result to come through the subscription channel. You can await the `initialized`\n * promise to ensure the subscription is ready. The initialization will timeout after\n * 30 seconds if no result is received.\n *\n * Example usage:\n * ```typescript\n * const subscription = await perspective.subscribeInfer(\"my_query(X)\");\n * // At this point the subscription is already initialized since subscribeInfer waits\n *\n * // Set up callback for future updates\n * const removeCallback = subscription.onResult(result => {\n * console.log(\"New result:\", result);\n * });\n *\n * // Later: clean up subscription and notify backend\n * subscription.dispose();\n * ```\n */\nclass QuerySubscriptionProxy {\n /** Creates a new query subscription\n * @param uuid - The UUID of the perspective\n * @param query - The Prolog query to subscribe to\n * @param client - The PerspectiveClient instance to use for communication\n */\n constructor(uuid, query, client) {\n _QuerySubscriptionProxy_instances.add(this);\n _QuerySubscriptionProxy_uuid.set(this, void 0);\n _QuerySubscriptionProxy_subscriptionId.set(this, void 0);\n _QuerySubscriptionProxy_client.set(this, void 0);\n _QuerySubscriptionProxy_callbacks.set(this, void 0);\n _QuerySubscriptionProxy_keepaliveTimer.set(this, void 0);\n _QuerySubscriptionProxy_unsubscribe.set(this, void 0);\n _QuerySubscriptionProxy_latestResult.set(this, void 0);\n _QuerySubscriptionProxy_disposed.set(this, false);\n _QuerySubscriptionProxy_initialized.set(this, void 0);\n _QuerySubscriptionProxy_initResolve.set(this, void 0);\n _QuerySubscriptionProxy_initReject.set(this, void 0);\n _QuerySubscriptionProxy_initTimeoutId.set(this, void 0);\n _QuerySubscriptionProxy_query.set(this, void 0);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_uuid, uuid, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_query, query, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_client, client, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_callbacks, new Set(), \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, null, \"f\");\n // Create the promise once and store its resolve/reject\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initialized, new Promise((resolve, reject) => {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, resolve, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, reject, \"f\");\n }), \"f\");\n }\n async subscribe() {\n // Clean up previous subscription attempt if retrying\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\").call(this);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, undefined, \"f\");\n }\n // Clear any existing timeout\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Clear any existing keepalive timer to prevent accumulation\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, undefined, \"f\");\n }\n try {\n // Initialize the query subscription\n let initialResult;\n initialResult = await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").subscribeQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_subscriptionId, initialResult.subscriptionId, \"f\");\n // Process the initial result immediately for fast UX.\n // The subscribeQuery() RPC call already returns the initial result,\n // so treat that as successful initialization instead of waiting for a\n // follow-up WebSocket update that may never arrive until the query changes.\n if (initialResult.result !== undefined) {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, initialResult.result, \"f\");\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, \"m\", _QuerySubscriptionProxy_notifyCallbacks).call(this, initialResult.result);\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\").call(this, true);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n }\n else {\n console.warn('\u26A0\uFE0F No initial result returned from subscribeQuery!');\n // Only keep the initialization timeout when the backend did not\n // provide an initial result up front.\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, setTimeout(() => {\n console.error('Subscription initialization timed out after 30 seconds. Resubscribing...');\n // Recursively retry subscription, catching any errors\n this.subscribe().catch(error => {\n console.error('Error during subscription retry after timeout:', error);\n });\n }, 30000), \"f\");\n }\n // Subscribe to query updates\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_unsubscribe, __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").subscribeToQueryUpdates(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"), (updateResult) => {\n // Clear timeout on first message\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Resolve the initialization promise (only resolves once)\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initResolve, \"f\").call(this, true);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\"); // Prevent double-resolve\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_latestResult, updateResult, \"f\");\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_instances, \"m\", _QuerySubscriptionProxy_notifyCallbacks).call(this, updateResult);\n }), \"f\");\n }\n catch (error) {\n console.error('Error setting up subscription:', error);\n // Reject the promise if this is the first attempt\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initReject, \"f\").call(this, error);\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initResolve, undefined, \"f\");\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initReject, undefined, \"f\");\n }\n throw error; // Re-throw so caller knows it failed\n }\n // Start keepalive loop using platform-agnostic setTimeout\n const keepaliveLoop = async () => {\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, \"f\"))\n return;\n try {\n await __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").keepAliveQuery(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"));\n }\n catch (e) {\n console.error('Error in keepalive:', e);\n // try to reinitialize the subscription\n console.log('Reinitializing subscription for query:', __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_query, \"f\"));\n try {\n await this.subscribe();\n console.log('Subscription reinitialized');\n }\n catch (resubscribeError) {\n console.error('Error during resubscription from keepalive:', resubscribeError);\n // Don't schedule another keepalive on resubscribe failure\n return;\n }\n }\n // Schedule next keepalive if not disposed\n if (!__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_disposed, \"f\")) {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), \"f\");\n }\n };\n // Start the first keepalive loop\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_keepaliveTimer, setTimeout(keepaliveLoop, 30000), \"f\");\n }\n /** Get the subscription ID for this query subscription\n *\n * This is a unique identifier assigned when the subscription was created.\n * It can be used to reference this specific subscription, for example when\n * sending keepalive signals.\n *\n * @returns The subscription ID string\n */\n get id() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\");\n }\n /** Promise that resolves when the subscription has received its first result\n * through the subscription channel. This ensures the subscription is fully\n * set up before allowing access to results or updates.\n *\n * If no result is received within 30 seconds, the subscription will automatically\n * retry. The promise will remain pending until a subscription message successfully\n * arrives, or until a fatal error occurs during subscription setup.\n *\n * Note: You typically don't need to await this directly since the subscription\n * creation methods (like subscribeInfer) already wait for initialization.\n */\n get initialized() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initialized, \"f\");\n }\n /** Get the latest query result\n *\n * This returns the most recent result from the query, which could be either:\n * - The initial result from when the subscription was created\n * - The latest update received through the subscription\n *\n * @returns The latest query result as a string (usually a JSON array of bindings)\n */\n get result() {\n return __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_latestResult, \"f\");\n }\n /** Add a callback that will be called whenever new results arrive\n *\n * The callback will be called immediately with the current result,\n * and then again each time the query results change.\n *\n * @param callback - Function that takes a result string and processes it\n * @returns A function that can be called to remove this callback\n *\n * Example:\n * ```typescript\n * const removeCallback = subscription.onResult(result => {\n * const bindings = JSON.parse(result);\n * console.log(\"New bindings:\", bindings);\n * });\n *\n * // Later: stop receiving updates\n * removeCallback();\n * ```\n */\n onResult(callback) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").add(callback);\n return () => __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").delete(callback);\n }\n /** Clean up the subscription and stop keepalive signals\n *\n * This method:\n * 1. Stops the keepalive timer\n * 2. Unsubscribes from subscription updates\n * 3. Clears all registered callbacks\n * 4. Cleans up any pending initialization timeout\n *\n * After calling this method, the subscription is no longer active and\n * will not receive any more updates. The instance should be discarded.\n */\n dispose() {\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_disposed, true, \"f\");\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_keepaliveTimer, \"f\"));\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_unsubscribe, \"f\").call(this);\n }\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\").clear();\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\")) {\n clearTimeout(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_initTimeoutId, \"f\"));\n __classPrivateFieldSet$a(this, _QuerySubscriptionProxy_initTimeoutId, undefined, \"f\");\n }\n // Tell the backend to dispose of the subscription\n if (__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\")) {\n __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_client, \"f\").disposeQuerySubscription(__classPrivateFieldGet$a(this, _QuerySubscriptionProxy_uuid, \"f\"), __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_subscriptionId, \"f\"))\n .catch(e => console.error('Error disposing query subscription:', e));\n }\n }\n}\n_QuerySubscriptionProxy_uuid = new WeakMap(), _QuerySubscriptionProxy_subscriptionId = new WeakMap(), _QuerySubscriptionProxy_client = new WeakMap(), _QuerySubscriptionProxy_callbacks = new WeakMap(), _QuerySubscriptionProxy_keepaliveTimer = new WeakMap(), _QuerySubscriptionProxy_unsubscribe = new WeakMap(), _QuerySubscriptionProxy_latestResult = new WeakMap(), _QuerySubscriptionProxy_disposed = new WeakMap(), _QuerySubscriptionProxy_initialized = new WeakMap(), _QuerySubscriptionProxy_initResolve = new WeakMap(), _QuerySubscriptionProxy_initReject = new WeakMap(), _QuerySubscriptionProxy_initTimeoutId = new WeakMap(), _QuerySubscriptionProxy_query = new WeakMap(), _QuerySubscriptionProxy_instances = new WeakSet(), _QuerySubscriptionProxy_notifyCallbacks = function _QuerySubscriptionProxy_notifyCallbacks(result) {\n for (const callback of __classPrivateFieldGet$a(this, _QuerySubscriptionProxy_callbacks, \"f\")) {\n try {\n callback(result);\n }\n catch (e) {\n console.error('Error in query subscription callback:', e);\n }\n }\n};\n/**\n * PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs\n * that store and organize links between expressions.\n *\n * A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view\n * of their digital world. Through PerspectiveProxy, you can:\n * - Add, remove, and query links\n * - Work with Social DNA (subject classes and flows)\n * - Subscribe to real-time updates\n * - Share perspectives as Neighbourhoods\n * - Execute Prolog queries for complex graph patterns\n *\n *\n * @example\n * ```typescript\n * // Create and work with links\n * const perspective = await ad4m.perspective.add(\"My Space\");\n * await perspective.add({\n * source: \"did:key:alice\",\n * predicate: \"knows\",\n * target: \"did:key:bob\"\n * });\n *\n * // Query links\n * const friends = await perspective.get({\n * source: \"did:key:alice\",\n * predicate: \"knows\"\n * });\n *\n * // Use Social DNA\n * await perspective.addSdna(todoClass, \"subject_class\");\n * const todo = await perspective.createSubject(\"Todo\", \"expression://123\");\n *\n * // Subscribe to changes\n * perspective.addListener(\"link-added\", (link) => {\n * console.log(\"New link added:\", link);\n * });\n * ```\n */\nclass PerspectiveProxy {\n /** @internal Exposed for ModelQueryBuilder subscription management */\n get client() { return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"); }\n /**\n * Creates a new PerspectiveProxy instance.\n * Note: Don't create this directly, use ad4m.perspective.add() instead.\n */\n constructor(handle, ad4m) {\n _PerspectiveProxy_handle.set(this, void 0);\n _PerspectiveProxy_client.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkAddedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkRemovedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveLinkUpdatedCallbacks.set(this, void 0);\n _PerspectiveProxy_perspectiveSyncStateChangeCallbacks.set(this, void 0);\n _PerspectiveProxy_ensuredSubjectClasses.set(this, new Set()\n /**\n * Creates a new PerspectiveProxy instance.\n * Note: Don't create this directly, use ad4m.perspective.add() instead.\n */\n );\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, [], \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, \"f\");\n __classPrivateFieldSet$a(this, _PerspectiveProxy_client, ad4m, \"f\");\n this.uuid = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid;\n this.name = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").name;\n this.owners = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").owners;\n this.sharedUrl = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").sharedUrl;\n this.neighbourhood = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").neighbourhood;\n this.state = __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").state;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkAddedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkRemovedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveLinkUpdatedListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\"));\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addPerspectiveSyncStateChangeListener(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\"));\n }\n /** Update the proxy's internal handle and public fields in-place.\n * Keeps the same object reference so all holders see the update. */\n updateHandle(handle) {\n if (handle.uuid !== __classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid) {\n throw new Error(`PerspectiveProxy.updateHandle: UUID mismatch \u2014 proxy is bound to \"${__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid}\" but received handle with UUID \"${handle.uuid}\". ` +\n `This would silently diverge from listeners registered under the original UUID.`);\n }\n __classPrivateFieldSet$a(this, _PerspectiveProxy_handle, handle, \"f\");\n this.uuid = handle.uuid;\n this.name = handle.name;\n this.owners = handle.owners;\n this.sharedUrl = handle.sharedUrl;\n this.neighbourhood = handle.neighbourhood;\n this.state = handle.state;\n }\n /**\n * Escapes special regex characters in a string to prevent ReDoS attacks\n * and regex injection when building dynamic regular expressions.\n *\n * @param str - The string to escape\n * @returns The escaped string safe for use in RegExp constructor\n *\n * @private\n */\n escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n /**\n * Executes a set of actions on an expression with optional parameters.\n * Used internally by Social DNA flows and subject class operations.\n *\n * Actions are specified as an array of commands that modify links in the perspective.\n * Each action is an object with the following format:\n * ```typescript\n * {\n * action: \"addLink\" | \"removeLink\" | \"setSingleTarget\" | \"collectionSetter\",\n * source: string, // Usually \"this\" to reference the current expression\n * predicate: string, // The predicate URI\n * target: string // The target value or \"value\" for parameters\n * }\n * ```\n *\n * Available commands:\n * - `addLink`: Creates a new link\n * - `removeLink`: Removes an existing link\n * - `setSingleTarget`: Removes all existing links with the same source/predicate and adds a new one\n * - `collectionSetter`: Special command for setting relation properties\n *\n * When used with parameters, the special value \"value\" in the target field will be\n * replaced with the actual parameter value.\n *\n * @example\n * ```typescript\n * // Add a state link and remove an old one\n * await perspective.executeAction([\n * {\n * action: \"addLink\",\n * source: \"this\",\n * predicate: \"todo://state\",\n * target: \"todo://doing\"\n * },\n * {\n * action: \"removeLink\",\n * source: \"this\",\n * predicate: \"todo://state\",\n * target: \"todo://ready\"\n * }\n * ], \"expression://123\");\n *\n * // Set a property using a parameter\n * await perspective.executeAction([\n * {\n * action: \"setSingleTarget\",\n * source: \"this\",\n * predicate: \"todo://title\",\n * target: \"value\"\n * }\n * ], \"expression://123\", [\n * { name: \"title\", value: \"New Title\" }\n * ]);\n * ```\n *\n * @param actions - Array of action objects to execute\n * @param expression - Target expression address (replaces \"this\" in actions)\n * @param parameters - Optional parameters that replace \"value\" in actions\n * @param batchId - Optional batch ID to group this operation with others\n */\n async executeAction(actions, expression, parameters, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").executeCommands(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify(actions), expression, JSON.stringify(parameters), batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Retrieves links from the perspective that match the given query.\n *\n * @param query - Query parameters to filter links\n * @returns Array of matching LinkExpressions\n *\n * @example\n * ```typescript\n * // Get all links where Alice knows someone\n * const links = await perspective.get({\n * source: \"did:key:alice\",\n * predicate: \"knows\"\n * });\n *\n * // Get all comments on a post\n * const comments = await perspective.get({\n * source: \"post://123\",\n * predicate: \"comment\"\n * });\n * ```\n */\n async get(query) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").queryLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n }\n /**\n * Executes a Prolog query against the perspective's knowledge base.\n * This is a powerful way to find complex patterns in the graph.\n *\n * @param query - Prolog query string\n * @returns Query results or false if no results\n *\n * @example\n * ```typescript\n * // Find friends of friends\n * const results = await perspective.infer(`\n * triple(A, \"knows\", B),\n * triple(B, \"knows\", C),\n * A \\= C\n * `);\n *\n * // Find all active todos\n * const todos = await perspective.infer(`\n * instance(Todo, \"Todo\"),\n * property_getter(\"Todo\", Todo, \"state\", \"active\")\n * `);\n * ```\n */\n async infer(query) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").queryProlog(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n }\n /**\n * Executes a SPARQL query against the perspective's link cache.\n * This allows powerful SQL-like queries on the link data stored in SPARQL.\n *\n * **Security Note:** Only read-only queries (SELECT, RETURN, etc.) are permitted.\n * Mutating operations (DELETE, UPDATE, INSERT, CREATE, DROP, DEFINE, etc.) are\n * blocked for security reasons. Use the perspective's add/remove methods to modify links.\n *\n * @param query - SPARQL query string (read-only operations only)\n * @returns Query results as parsed JSON\n *\n * Executes a SPARQL query against the perspective's RDF (Oxigraph) store.\n *\n * @param query - SPARQL query string\n * @returns Query results as parsed JSON\n */\n async querySparql(query) {\n const cached = getCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n if (cached !== undefined)\n return cached;\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").querySparql(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query);\n setCachedResult(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, query, result);\n return result;\n }\n /**\n * Execute a model query \u2014 the executor-side replacement for SPARQL query building + JS hydration.\n *\n * @param className - The model class name (e.g. \"Recipe\")\n * @param queryJson - Structured query as JSON string\n * @param shapeJson - Optional shape metadata JSON from the model class\n * @returns Object with `instances` array and `totalCount`\n */\n async modelQuery(className, queryJson, shapeJson) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").modelQuery(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, queryJson, shapeJson);\n }\n /**\n * Evaluate property getters for a batch of instances in a single RPC call.\n * Returns a map of `{ instanceId: { prop: value, ... } }`.\n *\n * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading\n * getter-backed properties on visible items (e.g. `replyingTo` on messages).\n *\n * @param className - The model class name (e.g. \"Message\")\n * @param instanceIds - Array of instance base expression URIs\n * @param shapeJson - Shape metadata JSON from the model class\n * @param propertyNames - Optional subset of property names to evaluate\n * @returns Map of instance ID \u2192 evaluated property values\n */\n async evaluateGetters(className, instanceIds, shapeJson, propertyNames) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").evaluateGetters(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, instanceIds, shapeJson, propertyNames);\n }\n /**\n * Subscribe to model query changes. Builds trigger SPARQL from the model shape\n * internally in Rust, registers a subscription, runs the initial query, and\n * pushes updated results when relevant links change.\n *\n * The subscription reuses the same GraphQL subscription channel as subscribeQuery().\n * Use keepAliveQuery() / disposeQuerySubscription() with the returned subscriptionId.\n *\n * @param className - The model class name\n * @param queryJson - JSON-serialized query parameters (same as modelQuery)\n * @param shapeJson - Optional shape metadata JSON from the model class\n * @returns Object with `subscriptionId` and initial `result`\n */\n async modelSubscribe(className, queryJson, shapeJson) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").modelSubscribe(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, className, queryJson, shapeJson);\n }\n /**\n * Adds a new link to the perspective.\n *\n * @param link - The link to add\n * @param status - Whether the link should be shared in a Neighbourhood\n * @param batchId - Optional batch ID to group this operation with others\n * @returns The created LinkExpression\n *\n * @example\n * ```typescript\n * // Add a simple relationship\n * await perspective.add({\n * source: \"did:key:alice\",\n * predicate: \"follows\",\n * target: \"did:key:bob\"\n * });\n *\n * // Add a local-only link\n * await perspective.add({\n * source: \"note://123\",\n * predicate: \"tag\",\n * target: \"private\"\n * }, \"local\");\n * ```\n */\n async add(link, status = 'shared', batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, status, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Adds multiple links to the perspective in a single operation.\n * More efficient than adding links one by one.\n *\n * @param links - Array of links to add\n * @param status - Whether the links should be shared\n * @param batchId - Optional batch ID to group this operation with others\n * @returns Array of created LinkExpressions\n */\n async addLinks(links, status = 'shared', batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, links, status, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Removes multiple links from the perspective.\n *\n * @param links - Array of links to remove\n * @param batchId - Optional batch ID to group this operation with others\n * @returns Array of removed LinkExpressions\n */\n async removeLinks(links, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeLinks(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, links, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Applies a set of link mutations (adds and removes) in a single operation.\n * Useful for atomic updates to the perspective.\n *\n * @param mutations - Object containing links to add and remove\n * @param status - Whether new links should be shared\n * @returns Object containing results of the mutations\n */\n async linkMutations(mutations, status = 'shared') {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").linkMutations(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, mutations, status);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Adds a pre-signed LinkExpression to the perspective.\n *\n * @param link - The signed LinkExpression to add\n * @param status - Whether the link should be shared\n * @param batchId - Optional batch ID to group this operation with others\n * @returns The added LinkExpression\n */\n async addLinkExpression(link, status = 'shared', batchId) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addLinkExpression(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, status, batchId);\n }\n /**\n * Updates an existing link with new data.\n *\n * @param oldLink - The existing link to update\n * @param newLink - The new link data\n * @param batchId - Optional batch ID to group this operation with others\n */\n async update(oldLink, newLink, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").updateLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, oldLink, newLink, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Removes a link from the perspective.\n *\n * @param link - The link to remove\n * @param batchId - Optional batch ID to group this operation with others\n */\n async remove(link, batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeLink(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, link, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /** Creates a new batch for grouping operations */\n async createBatch() {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /** Commits a batch of operations */\n async commitBatch(batchId) {\n const result = await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").commitBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, batchId);\n invalidatePerspectiveCache(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n return result;\n }\n /**\n * Retrieves and renders an Expression referenced in this perspective.\n *\n * @param expressionURI - URI of the Expression to retrieve\n * @returns The rendered Expression\n */\n async getExpression(expressionURI) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getExpression(expressionURI);\n }\n /**\n * Creates a new Expression in the specified Language.\n *\n * @param content - Content for the new Expression\n * @param languageAddress - Address of the Language to use\n * @returns URI of the created Expression\n */\n async createExpression(content, languageAddress) {\n return await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createExpression(content, languageAddress);\n }\n /**\n * Subscribes to link changes in the perspective.\n *\n * @param type - Type of change to listen for\n * @param cb - Callback function\n *\n * @example\n * ```typescript\n * // Listen for new links\n * perspective.addListener(\"link-added\", (link) => {\n * console.log(\"New link:\", link);\n * });\n *\n * // Listen for removed links\n * perspective.addListener(\"link-removed\", (link) => {\n * console.log(\"Link removed:\", link);\n * });\n * ```\n */\n async addListener(type, cb) {\n if (type === 'link-added') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").push(cb);\n }\n else if (type === 'link-removed') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").push(cb);\n }\n else if (type === 'link-updated') {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").push(cb);\n }\n }\n /**\n * Subscribes to sync state changes if this perspective is shared.\n *\n * @param cb - Callback function\n *\n * @example\n * ```typescript\n * perspective.addSyncStateChangeListener((state) => {\n * console.log(\"Sync state:\", state);\n * });\n * ```\n */\n async addSyncStateChangeListener(cb) {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\").push(cb);\n }\n /**\n * Unsubscribes from link changes.\n *\n * @param type - Type of change to stop listening for\n * @param cb - The callback function to remove\n */\n async removeListener(type, cb) {\n if (type === 'link-added') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").splice(index, 1);\n }\n else if (type === 'link-removed') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").splice(index, 1);\n }\n else if (type === 'link-updated') {\n const index = __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").indexOf(cb);\n if (index >= 0)\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").splice(index, 1);\n }\n }\n /** Clean up all subscriptions registered by this proxy.\n * Call this when the proxy is no longer needed to prevent subscription leaks.\n * After calling dispose(), the proxy should not be used. */\n dispose() {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").removeAllListeners(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkAddedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkRemovedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveLinkUpdatedCallbacks, \"f\").length = 0;\n __classPrivateFieldGet$a(this, _PerspectiveProxy_perspectiveSyncStateChangeCallbacks, \"f\").length = 0;\n }\n /**\n * Creates a snapshot of the current perspective state.\n * Useful for backup or sharing.\n *\n * @returns Perspective object containing all links\n */\n async snapshot() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").snapshotByUUID(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /**\n * Loads a perspective snapshot, replacing current content.\n *\n * @param snapshot - Perspective snapshot to load\n */\n async loadSnapshot(snapshot) {\n //Clean the input data from __typename\n const cleanedSnapshot = JSON.parse(JSON.stringify(snapshot));\n delete cleanedSnapshot.__typename;\n cleanedSnapshot.links.forEach(link => {\n delete link.data.__typename;\n });\n for (const link of cleanedSnapshot.links) {\n await this.addLinkExpression(link);\n }\n }\n /**\n * Gets a single target value matching a query.\n * Useful when you expect only one result.\n *\n * @param query - Query to find the target\n * @returns Target value or void if not found\n *\n * @example\n * ```typescript\n * // Get a user's name\n * const name = await perspective.getSingleTarget({\n * source: \"did:key:alice\",\n * predicate: \"name\"\n * });\n * ```\n */\n async getSingleTarget(query) {\n delete query.target;\n const foundLinks = await this.get(query);\n if (foundLinks.length)\n return foundLinks[0].data.target;\n else\n return null;\n }\n /**\n * Sets a single target value, removing any existing targets.\n *\n * @param link - Link defining the new target\n * @param status - Whether the link should be shared\n *\n * @example\n * ```typescript\n * // Set a user's status\n * await perspective.setSingleTarget({\n * source: \"did:key:alice\",\n * predicate: \"status\",\n * target: \"online\"\n * });\n * ```\n */\n async setSingleTarget(link, status = 'shared') {\n const query = new LinkQuery({ source: link.source, predicate: link.predicate });\n const foundLinks = await this.get(query);\n const removals = [];\n for (const l of foundLinks) {\n delete l.__typename;\n delete l.data.__typename;\n delete l.proof.__typename;\n removals.push(l);\n }\n const additions = [link];\n await this.linkMutations({ additions, removals }, status);\n }\n /** Returns all the Social DNA flows defined in this perspective */\n async sdnaFlows() {\n // Query for all flow registration links\n const flowLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_flow\"\n }));\n return flowLinks.map(l => {\n try {\n return Literal.fromUrl(l.data.target).get();\n }\n catch {\n return l.data.target;\n }\n });\n }\n /** Returns all Social DNA flows that can be started from the given expression */\n async availableFlows(exprAddr) {\n const allFlowNames = await this.sdnaFlows();\n const available = [];\n for (const name of allFlowNames) {\n const flow = await this.getFlow(name);\n if (!flow)\n continue;\n if (flow.flowable === \"any\") {\n available.push(name);\n }\n else {\n // Check if the expression matches the flowable link pattern\n const pattern = flow.flowable;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0) {\n available.push(name);\n }\n }\n }\n return available;\n }\n /** Starts the Social DNA flow @param flowName on the expression @param exprAddr */\n async startFlow(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n if (flow.startAction.length === 0)\n throw `Flow \"${flowName}\" has no start action`;\n await this.executeAction(flow.startAction, exprAddr, undefined);\n }\n /** Returns all expressions in the given state of given Social DNA flow */\n async expressionsInFlowState(flowName, flowState) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n return [];\n // Find the state with the matching value\n const state = flow.states.find(s => s.value === flowState);\n if (!state)\n return [];\n // Query for expressions matching this state's check pattern\n const pattern = state.stateCheck;\n const links = await this.get(new LinkQuery({\n predicate: pattern.predicate,\n target: pattern.target\n }));\n // Return the sources (expression addresses) - use source if pattern has no explicit source\n return links.map(l => pattern.source ? l.data.target : l.data.source);\n }\n /** Returns the given expression's flow state with regard to given Social DNA flow */\n async flowState(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n // Check each state to find which one the expression is in\n for (const state of flow.states) {\n const pattern = state.stateCheck;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0)\n return state.value;\n }\n throw `Expression \"${exprAddr}\" is not in any state of flow \"${flowName}\"`;\n }\n /** Returns available action names, with regard to Social DNA flow and expression's flow state */\n async flowActions(flowName, exprAddr) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n return [];\n // Determine current state\n let currentStateName = null;\n for (const state of flow.states) {\n const pattern = state.stateCheck;\n const source = pattern.source || exprAddr;\n const links = await this.get(new LinkQuery({\n source,\n predicate: pattern.predicate,\n target: pattern.target\n }));\n if (links.length > 0) {\n currentStateName = state.name;\n break;\n }\n }\n if (!currentStateName)\n return [];\n // Return transitions available from current state\n return flow.transitions\n .filter(t => t.fromState === currentStateName)\n .map(t => t.actionName);\n }\n /** Runs given Social DNA flow action */\n async runFlowAction(flowName, exprAddr, actionName) {\n const flow = await this.getFlow(flowName);\n if (!flow)\n throw `Flow \"${flowName}\" not found`;\n const transition = flow.transitions.find(t => t.actionName === actionName);\n if (!transition)\n throw `Action \"${actionName}\" not found in flow \"${flowName}\"`;\n await this.executeAction(transition.actions, exprAddr, undefined);\n }\n /** Returns the perspective's Social DNA code\n * This will return all SDNA code elements in an array.\n */\n async getSdna() {\n // First, find all the name literals that are linked from ad4m://self with SDNA predicates\n const sdnaPredicates = [\n \"ad4m://has_subject_class\",\n \"ad4m://has_flow\",\n \"ad4m://has_custom_sdna\"\n ];\n const allSdnaCode = [];\n for (const predicate of sdnaPredicates) {\n // Find name literals linked from ad4m://self with this predicate\n const nameLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: predicate\n }));\n // For each name literal found, get the actual SDNA code\n for (const nameLink of nameLinks) {\n const nameLiteral = nameLink.data.target;\n // Now find the SDNA code linked from this name with predicate \"ad4m://sdna\"\n const sdnaLinks = await this.get(new LinkQuery({\n source: nameLiteral,\n predicate: \"ad4m://sdna\"\n }));\n // Extract the SDNA code from each link\n for (const sdnaLink of sdnaLinks) {\n const code = Literal.fromUrl(sdnaLink.data.target).get();\n if (typeof code === 'string') {\n allSdnaCode.push(code);\n }\n }\n }\n }\n return allSdnaCode;\n }\n /** Returns the Social DNA code for a specific class\n * This will return the SDNA code for the specified class, or null if not found.\n */\n async getSdnaForClass(className) {\n // First, find the name literal for this class that is linked from ad4m://self\n const nameLiteral = Literal.from(className);\n const links = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n target: nameLiteral.toUrl(),\n predicate: \"ad4m://has_subject_class\"\n }));\n if (links.length === 0) {\n return null;\n }\n // Now find the SDNA code linked from this name with predicate \"ad4m://sdna\"\n const sdnaLinks = await this.get(new LinkQuery({\n source: nameLiteral.toUrl(),\n predicate: \"ad4m://sdna\"\n }));\n if (sdnaLinks.length === 0) {\n return null;\n }\n // Extract the SDNA code from the first link\n const code = Literal.fromUrl(sdnaLinks[0].data.target).get();\n return typeof code === 'string' ? code : null;\n }\n /**\n * Adds Social DNA code to the perspective.\n *\n * **Recommended:** Use {@link addShacl} instead, which accepts the `SHACLShape` type directly.\n * This method is primarily for the RPC API layer and legacy Prolog code.\n *\n * @param name - Unique name for this SDNA definition\n * @param sdnaCode - Prolog SDNA code (legacy, can be empty string if shaclJson provided)\n * @param sdnaType - Type of SDNA: \"subject_class\", \"flow\", or \"custom\"\n * @param shaclJson - SHACL JSON string (use addShacl() for type-safe alternative)\n *\n * @example\n * // Recommended: Use addShacl() with SHACLShape type\n * const shape = new SHACLShape('recipe://Recipe');\n * shape.addProperty({ name: 'title', path: 'recipe://title', datatype: 'xsd:string' });\n * await perspective.addShacl('Recipe', shape);\n *\n * // Legacy: Prolog code is auto-converted to SHACL\n * await perspective.addSdna('Recipe', prologCode, 'subject_class');\n */\n async addSdna(name, sdnaCode, sdnaType, shaclJson) {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addSdna(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, name, sdnaCode, sdnaType, shaclJson);\n }\n /**\n * Batch variant of addSdna \u2014 registers multiple SDNA entries in a single RPC call.\n * Acquires the Rust-side mutex once for the entire batch.\n */\n async addSdnaAll(entries) {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").addSdnaBatch(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, entries);\n }\n /**\n * Batch-registers multiple model classes as SHACL subject classes in a single RPC call.\n * Skips classes already registered on this perspective instance.\n */\n async ensureSubjectClasses(jsClasses) {\n const entries = [];\n for (const jsClass of jsClasses) {\n const className = jsClass.className || jsClass.prototype?.className || jsClass.name;\n if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").has(className))\n continue;\n if (!jsClass.generateSHACL) {\n throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);\n }\n const { shape } = jsClass.generateSHACL();\n entries.push({\n name: className,\n sdnaType: 'subject_class',\n shaclJson: JSON.stringify(shape.toJSON()),\n });\n }\n if (entries.length === 0)\n return;\n await this.addSdnaAll(entries);\n for (const entry of entries) {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").add(entry.name);\n }\n }\n /**\n * Adds a subject class to the perspective.\n * Alias for addSdna() with sdnaType='subject_class'.\n */\n async addSubjectClass(name, shaclJson) {\n return this.addSdna(name, '', 'subject_class', shaclJson);\n }\n /**\n * **Recommended way to add SDNA schemas.**\n *\n * Store a SHACL shape in this Perspective using the type-safe `SHACLShape` class.\n * The shape is serialized as RDF triples (links) for native AD4M storage and querying.\n *\n * @param name - Unique name for this schema (e.g., 'Recipe', 'Task')\n * @param shape - SHACLShape instance defining the schema\n *\n * @example\n * import { SHACLShape } from '@coasys/ad4m';\n *\n * const shape = new SHACLShape('recipe://Recipe');\n * shape.addProperty({\n * name: 'title',\n * path: 'recipe://title',\n * datatype: 'xsd:string',\n * minCount: 1\n * });\n * shape.addProperty({\n * name: 'ingredients',\n * path: 'recipe://has_ingredient',\n * // No maxCount = relation\n * });\n *\n * await perspective.addShacl('Recipe', shape);\n */\n async addShacl(name, shape) {\n // Serialize shape to links\n const shapeLinks = shape.toLinks();\n // Create name -> shape mapping links\n const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);\n const allLinks = [\n ...shapeLinks.map(l => new Link({\n source: l.source,\n predicate: l.predicate,\n target: l.target\n })),\n new Link({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_shacl\",\n target: nameMapping.toUrl()\n }),\n new Link({\n source: nameMapping.toUrl(),\n predicate: \"ad4m://shacl_shape_uri\",\n target: shape.nodeShapeUri\n })\n ];\n // Batch add all links at once\n await this.addLinks(allLinks);\n }\n /**\n * Retrieve a SHACL shape by name from this Perspective\n */\n async getShacl(name) {\n // Find the shape URI from the name mapping\n const nameMapping = Literal.fromUrl(`literal:string:shacl://${name}`);\n const shapeUriLinks = await this.get(new LinkQuery({\n source: nameMapping.toUrl(),\n predicate: \"ad4m://shacl_shape_uri\"\n }));\n if (shapeUriLinks.length === 0) {\n return null;\n }\n const shapeUri = shapeUriLinks[0].data.target;\n // First get property shape URIs so we can query everything in one go\n const propertyLinks = await this.get(new LinkQuery({\n source: shapeUri,\n predicate: \"sh://property\"\n }));\n // Fetch all links from the shape and its property shapes\n const sourceUris = [shapeUri, ...propertyLinks.map(l => l.data.target)];\n const allLinks = [];\n for (const uri of sourceUris) {\n const links = await this.get(new LinkQuery({ source: uri }));\n for (const l of links) {\n allLinks.push({\n source: l.data.source,\n predicate: l.data.predicate,\n target: l.data.target\n });\n }\n }\n const shapeLinks = allLinks;\n return SHACLShape.fromLinks(shapeLinks, shapeUri);\n }\n /**\n * Get all SHACL shapes stored in this Perspective\n */\n async getAllShacl() {\n const nameLinks = await this.get(new LinkQuery({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_shacl\"\n }));\n const shapes = [];\n for (const nameLink of nameLinks) {\n const nameUrl = nameLink.data.target;\n const name = Literal.fromUrl(nameUrl).get();\n const shapeName = name.replace('shacl://', '');\n const shape = await this.getShacl(shapeName);\n if (shape) {\n shapes.push({ name: shapeName, shape });\n }\n }\n return shapes;\n }\n /**\n * **Recommended way to add Flow definitions.**\n *\n * Store a SHACL Flow (state machine) in this Perspective using the type-safe `SHACLFlow` class.\n * The flow is serialized as RDF triples (links) for native AD4M storage and querying.\n *\n * @param name - Flow name (e.g., 'TODO', 'Approval')\n * @param flow - SHACLFlow instance defining the state machine\n *\n * @example\n * ```typescript\n * import { SHACLFlow } from '@coasys/ad4m';\n *\n * const todoFlow = new SHACLFlow('TODO', 'todo://');\n * todoFlow.flowable = 'any';\n *\n * // Define states\n * todoFlow.addState({ name: 'ready', value: 0, stateCheck: { predicate: 'todo://state', target: 'todo://ready' }});\n * todoFlow.addState({ name: 'done', value: 1, stateCheck: { predicate: 'todo://state', target: 'todo://done' }});\n *\n * // Define start action\n * todoFlow.startAction = [{ action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }];\n *\n * // Define transitions\n * todoFlow.addTransition({\n * actionName: 'Complete',\n * fromState: 'ready',\n * toState: 'done',\n * actions: [\n * { action: 'addLink', source: 'this', predicate: 'todo://state', target: 'todo://done' },\n * { action: 'removeLink', source: 'this', predicate: 'todo://state', target: 'todo://ready' }\n * ]\n * });\n *\n * await perspective.addFlow('TODO', todoFlow);\n * ```\n */\n async addFlow(name, flow) {\n // Serialize flow to links\n const flowLinks = flow.toLinks();\n // Create registration and mapping links\n const flowNameLiteral = Literal.from(name).toUrl();\n const allLinks = [\n ...flowLinks.map(l => new Link({\n source: l.source,\n predicate: l.predicate,\n target: l.target\n })),\n new Link({\n source: \"ad4m://self\",\n predicate: \"ad4m://has_flow\",\n target: flowNameLiteral\n }),\n new Link({\n source: flowNameLiteral,\n predicate: \"ad4m://flow_uri\",\n target: flow.flowUri\n })\n ];\n // Batch add all links at once\n await this.addLinks(allLinks);\n }\n /**\n * Retrieve a Flow definition by name from this Perspective\n *\n * @param name - Flow name to retrieve\n * @returns The SHACLFlow or null if not found\n */\n async getFlow(name) {\n const flowNameLiteral = Literal.from(name).toUrl();\n // Find flow URI from name mapping\n const flowUriLinks = await this.get(new LinkQuery({\n source: flowNameLiteral,\n predicate: \"ad4m://flow_uri\"\n }));\n if (flowUriLinks.length === 0) {\n return null;\n }\n const flowUri = flowUriLinks[0].data.target;\n // Compute alternate prefix for state/transition URIs\n const alternatePrefix = flowUri.endsWith('Flow')\n ? flowUri.slice(0, -4) + '.'\n : flowUri + '.';\n // Fetch flow links using SPARQL to match flowUri source OR alternatePrefix sources\n const sparqlQuery = `SELECT ?s ?p ?o WHERE {\n ?s ?p ?o .\n FILTER(?s = <${flowUri}> || STRSTARTS(STR(?s), \"${alternatePrefix}\"))\n }`;\n const sparqlResult = await this.querySparql(sparqlQuery);\n const flowLinks = (sparqlResult || []).map((r) => ({\n source: r.s,\n predicate: r.p,\n target: r.o\n }));\n return SHACLFlow.fromLinks(flowLinks, flowUri);\n }\n /** Returns all the Subject classes defined in this perspectives SDNA\n *\n * Uses SHACL-based lookup (Prolog-free implementation).\n */\n async subjectClasses() {\n try {\n // Query SHACL class links directly \u2014 no need for a separate RPC endpoint\n const classLinks = await this.get(new LinkQuery({\n predicate: \"rdf://type\",\n target: \"ad4m://SubjectClass\"\n }));\n const classNames = classLinks\n .map(l => {\n const source = l.data.source;\n // Extract class name from URI like \"recipe://Recipe\" or \"flux://Channel\"\n const parts = source.split(\"://\");\n const lastPart = parts[parts.length - 1];\n return lastPart.split('/').pop() || '';\n })\n .filter(name => name.length > 0);\n // Deduplicate\n return [...new Set(classNames)];\n }\n catch (e) {\n console.warn('subjectClasses: SHACL lookup failed:', e);\n return [];\n }\n }\n async stringOrTemplateObjectToSubjectClassName(subjectClass) {\n if (typeof subjectClass === \"string\")\n return subjectClass;\n else {\n let subjectClasses = await this.subjectClassesByTemplate(subjectClass);\n if (subjectClasses[0]) {\n return subjectClasses[0];\n }\n else {\n //@ts-ignore\n return subjectClass.className;\n }\n }\n }\n /**\n * Creates a new subject instance of the given subject class\n *\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class.\n * @param exprAddr The address of the expression to be turned into a subject instance\n * @param initialValues Optional initial values for properties. If provided, these will be\n * merged with constructor actions for better performance.\n * @param batchId Optional batch ID for grouping operations. If provided, returns the expression address\n * instead of the subject proxy since the subject won't exist until the batch is committed.\n * @returns A proxy object for the created subject, or just the expression address if in batch mode\n */\n async createSubject(subjectClass, exprAddr, initialValues, batchId) {\n let className;\n if (typeof subjectClass === \"string\") {\n className = subjectClass;\n await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({\n className,\n initialValues\n }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);\n }\n else {\n const obj = subjectClass;\n const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className\n || await this.findClassByProperties(obj);\n if (!resolvedClassName) {\n throw new Error(\"Could not resolve subject class name from object. Use a decorated class or pass a className string.\");\n }\n await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").createSubject(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({\n className: resolvedClassName,\n initialValues\n }), exprAddr, initialValues ? JSON.stringify(initialValues) : undefined, batchId);\n }\n // Skip subject proxy creation when in batch mode since the subject won't exist until batch is committed\n if (batchId) {\n return exprAddr;\n }\n // Return the expression address directly \u2014 callers should use Ad4mModel or\n // getSubjectData() to interact with the created instance.\n return exprAddr;\n }\n async getSubjectData(subjectClass, exprAddr) {\n if (typeof subjectClass === \"string\") {\n return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({ className: subjectClass }), exprAddr));\n }\n const obj = subjectClass;\n const resolvedClassName = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className\n || await this.findClassByProperties(obj);\n if (!resolvedClassName) {\n throw new Error(\"Could not resolve subject class name from object. Use a decorated class or pass a className string.\");\n }\n return JSON.parse(await __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getSubjectData(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid, JSON.stringify({ className: resolvedClassName }), exprAddr));\n }\n /**\n * Gets actions from SHACL links for a given predicate (e.g., ad4m://constructor, ad4m://destructor).\n * Returns the parsed action array if found, or null if not found.\n */\n async getActionsFromSHACL(className, predicate) {\n // Use regex to match exact class name followed by \"Shape\" at end of URI\n // This prevents \"RecipeShape\" from matching \"MyRecipeShape\"\n const escaped = this.escapeRegExp(className);\n const shapePattern = new RegExp(`[/:#]${escaped}Shape$`);\n const links = await this.get(new LinkQuery({ predicate }));\n for (const link of links) {\n if (shapePattern.test(link.data.source)) {\n // Parse actions from literal:string:{json}\n const prefix = \"literal:string:\";\n if (link.data.target.startsWith(prefix)) {\n const jsonStr = link.data.target.slice(prefix.length);\n // Decode URL-encoded JSON if needed, with fallback for raw % characters\n let decoded = jsonStr;\n try {\n decoded = decodeURIComponent(jsonStr);\n }\n catch { }\n try {\n return JSON.parse(decoded);\n }\n catch (e) {\n console.warn(`Failed to parse SHACL actions JSON for ${className}:`, e);\n return null;\n }\n }\n }\n }\n return null;\n }\n /** Removes a subject instance by running its (SDNA defined) destructor,\n * which means removing links around the given expression address\n *\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, the first subject class\n * that matches the given properties will be used.\n * @param exprAddr The address of the expression to be turned into a subject instance\n * @param batchId Optional batch ID for grouping operations. If provided, the removal will be part of the batch\n * and won't be executed until the batch is committed.\n */\n async removeSubject(subjectClass, exprAddr, batchId) {\n let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);\n // Get destructor actions from SHACL links (Prolog-free)\n let actions = await this.getActionsFromSHACL(className, \"ad4m://destructor\");\n if (!actions) {\n throw `No destructor found for subject class: ${className}. Make sure the class was registered with SHACL.`;\n }\n await this.executeAction(actions, exprAddr, undefined, batchId);\n }\n /** Checks if the given expression is a subject instance of the given subject class\n * @param expression The expression to be checked\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, the first subject class\n * that matches the given properties will be used.\n */\n async isSubjectInstance(expression, subjectClass) {\n let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);\n // Get metadata from SHACL links\n const metadata = await this.getSubjectClassMetadata(className);\n if (!metadata) {\n console.warn(`isSubjectInstance: No SHACL metadata found for class ${className}`);\n return false;\n }\n // If no required triples, any expression with links is an instance\n if (metadata.requiredTriples.length === 0) {\n const links = await this.get(new LinkQuery({ source: expression }));\n return links.length > 0;\n }\n // Build a single SPARQL ASK query with all required triple patterns\n const patterns = metadata.requiredTriples.map((t, i) => {\n const target = t.target ? `<${t.target}>` : `?t${i}`;\n return `<${expression}> <${t.predicate}> ${target} .`;\n }).join('\\n ');\n const result = await this.querySparql(`ASK WHERE {\\n ${patterns}\\n}`);\n return result === true;\n }\n /**\n * Gets subject class metadata from SHACL links using SHACLShape.fromLinks().\n * Retrieves the SHACL shape and extracts metadata for instance queries.\n */\n async getSubjectClassMetadata(className) {\n try {\n // Use getShacl() to retrieve the shape via SHACLShape.fromLinks()\n const shape = await this.getShacl(className);\n if (!shape) {\n console.warn(`No SHACL metadata found for ${className}`);\n return null;\n }\n const requiredPredicates = [];\n const requiredTriples = [];\n const properties = new Map();\n const relations = new Map();\n // Build property/relation maps and track writable predicates from shape properties\n const writablePredicates = new Set();\n for (const prop of shape.properties) {\n if (!prop.path || !prop.name)\n continue;\n if (prop.writable) {\n writablePredicates.add(prop.path);\n }\n const isRelation = prop.adder && prop.adder.length > 0;\n if (isRelation) {\n relations.set(prop.name, { predicate: prop.path });\n }\n else {\n properties.set(prop.name, {\n predicate: prop.path,\n resolveLanguage: prop.resolveLanguage\n });\n }\n }\n // Extract required predicates/triples from constructor actions\n if (shape.constructor_actions) {\n for (const action of shape.constructor_actions) {\n if (action.predicate) {\n requiredPredicates.push(action.predicate);\n const isWritableProperty = writablePredicates.has(action.predicate);\n if (action.target && action.target !== 'value' && !isWritableProperty) {\n requiredTriples.push({ predicate: action.predicate, target: action.target });\n }\n else {\n requiredTriples.push({ predicate: action.predicate });\n }\n }\n }\n }\n return { requiredPredicates, requiredTriples, properties, relations };\n }\n catch (e) {\n console.error(`Error getting SHACL metadata for ${className}:`, e);\n return null;\n }\n }\n /**\n * Generates a SPARQL query to find instances based on class metadata.\n */\n /**\n * Finds all instances matching subject class metadata by querying links.\n * Returns base URIs of matching instances.\n */\n async findInstancesByMetadata(metadata) {\n if (metadata.requiredTriples.length === 0) {\n // No required triples - return all unique sources that have any link\n const allLinks = await this.get(new LinkQuery({}));\n const sources = new Set(allLinks.map(l => l.data.source));\n return Array.from(sources).map(s => ({ base: s }));\n }\n // Build a single SPARQL SELECT with all required triple patterns joined\n const patterns = metadata.requiredTriples.map((t, i) => {\n const target = t.target ? `<${t.target}>` : `?t${i}`;\n return `?base <${t.predicate}> ${target} .`;\n }).join('\\n ');\n const results = await this.querySparql(`SELECT DISTINCT ?base WHERE {\\n ${patterns}\\n}`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => ({ base: row.base }));\n }\n /** Returns all subject instances of the given subject class as proxy objects.\n * @param subjectClass Either a string with the name of the subject class, or an object\n * with the properties of the subject class. In the latter case, all subject classes\n * that match the given properties will be used.\n */\n async getAllSubjectInstances(subjectClass) {\n let classes = [];\n let isClassConstructor = typeof subjectClass === \"function\";\n if (typeof subjectClass === \"string\") {\n classes = [subjectClass];\n }\n else if (isClassConstructor) {\n // It's an Ad4mModel class constructor\n //@ts-ignore\n classes = [subjectClass.name];\n }\n else {\n classes = await this.subjectClassesByTemplate(subjectClass);\n }\n let instances = [];\n for (let className of classes) {\n //console.log(`getAllSubjectInstances: Processing class ${className}`);\n // Query SDNA for metadata, then query SPARQL for instances\n const metadata = await this.getSubjectClassMetadata(className);\n //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);\n if (metadata) {\n const results = await this.findInstancesByMetadata(metadata);\n // console.log(`getAllSubjectInstances: SPARQL returned ${results?.length || 0} results`);\n for (const result of results || []) {\n //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);\n try {\n let instance;\n if (isClassConstructor) {\n // Create an instance of the actual Ad4mModel class\n //@ts-ignore\n instance = new subjectClass(this, result.base);\n // Load the instance data from links\n await instance.get();\n }\n else {\n // Return plain data for string-based lookups\n const data = await this.getSubjectData(className, result.base);\n instance = { id: result.base, ...data };\n }\n instances.push(instance);\n //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);\n }\n catch (e) {\n //console.warn(`Failed to create subject for ${result.base}:`, e);\n }\n }\n }\n }\n //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);\n return instances;\n }\n /**\n * Find a subject class by matching an object's properties/relations against SHACL shapes.\n * Queries SHACL links client-side to find a class whose properties contain all required ones.\n * @returns The matching class name, or null if no match found.\n */\n async findClassByProperties(obj) {\n // Extract properties and relations from the object\n let properties = [];\n let relations = [];\n const proto = Object.getPrototypeOf(obj);\n const ctor = proto?.constructor;\n const registryProps = ctor ? getPropertiesMetadata(ctor) : {};\n if (Object.keys(registryProps).length > 0) {\n properties = Object.keys(registryProps);\n }\n else {\n properties = Object.keys(obj).filter(key => !Array.isArray(obj[key]));\n }\n const registryRelations = ctor\n ? Object.fromEntries(Object.entries(getRelationsMetadata(ctor)).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'))\n : {};\n if (Object.keys(registryRelations).length > 0) {\n relations = Object.keys(registryRelations).filter(key => key !== 'isSubjectInstance');\n }\n else {\n relations = Object.keys(obj).filter(key => Array.isArray(obj[key]) && key !== 'isSubjectInstance');\n }\n if (properties.length === 0 && relations.length === 0) {\n return null;\n }\n // Single SPARQL query to get all class shapes with their properties and collections\n const results = await this.querySparql(`\n SELECT ?shape ?predicate ?target WHERE {\n { ?shape <rdf://type> <ad4m://SubjectClass> . BIND(<rdf://type> AS ?predicate) BIND(<ad4m://SubjectClass> AS ?target) }\n UNION\n { ?shape <sh://property> ?target . BIND(<sh://property> AS ?predicate) }\n UNION\n { ?shape <sh://collection> ?target . BIND(<sh://collection> AS ?predicate) }\n }\n `);\n if (!Array.isArray(results) || results.length === 0)\n return null;\n // Build a map of className -> { properties, relations }\n const classShapes = new Map();\n // First pass: find all subject classes\n for (const r of results) {\n if (r.predicate === 'rdf://type' && r.target === 'ad4m://SubjectClass') {\n const source = r.shape;\n const sepIdx = source.indexOf('://');\n if (sepIdx < 0)\n continue;\n const className = source.substring(sepIdx + 3).split('/').pop();\n if (!className)\n continue;\n classShapes.set(className, { shapeUri: source, properties: [], relations: [] });\n }\n }\n // Second pass: collect properties and relations for each class\n for (const r of results) {\n if (r.predicate === 'sh://property' || r.predicate === 'sh://collection') {\n // Match shape source to class (e.g., \"recipe://RecipeShape\" -> \"Recipe\")\n for (const [className, shape] of classShapes) {\n if (r.shape.endsWith(`${className}Shape`)) {\n const dotIdx = r.target.lastIndexOf('.');\n if (dotIdx < 0)\n continue;\n const name = r.target.substring(dotIdx + 1);\n if (r.predicate === 'sh://property') {\n shape.properties.push(name);\n }\n else {\n shape.relations.push(name);\n }\n }\n }\n }\n }\n // Find a class that has all required properties and relations\n for (const [className, shape] of classShapes) {\n const hasAllProps = properties.every(p => shape.properties.includes(p));\n const hasAllRels = relations.every(c => shape.relations.includes(c));\n if (hasAllProps && hasAllRels) {\n return className;\n }\n }\n return null;\n }\n /** Returns all subject classes that match the given template object.\n * This function looks at the properties of the template object and\n * its setters and relations to create a Prolog query that finds\n * all subject classes that would be converted to a proxy object\n * with exactly the same properties and relations.\n *\n * Since there could be multiple subject classes that match the given\n * criteria, this function returns a list of class names.\n *\n * @param obj The template object\n */\n async subjectClassesByTemplate(obj) {\n // className lookup first: the @Model decorator sets a precise className on the prototype,\n // so this is always more specific than property-set matching.\n // Property matching alone has a superset-ambiguity problem: if DerivedModel adds\n // properties to BaseModel, then DerivedModel's shape is a superset of BaseModel's\n // property list, so findClassByProperties could wrongly return DerivedModel for a\n // BaseModel instance (causing the derived SDNA constructor to fire and inject extra\n // links into what should be a plain base instance).\n try {\n // @ts-ignore - className is added dynamically by decorators\n const className = obj.className || obj.constructor?.className || obj.constructor?.prototype?.className;\n if (className) {\n const existingClasses = await this.subjectClasses();\n if (existingClasses.includes(className)) {\n return [className];\n }\n }\n }\n catch (e) {\n console.warn('subjectClassesByTemplate: className lookup failed:', e);\n }\n // Fall back to SHACL-based property matching for undecorated / dynamic objects\n try {\n const match = await this.findClassByProperties(obj);\n if (match) {\n return [match];\n }\n }\n catch (e) {\n console.warn('subjectClassesByTemplate: property matching failed:', e);\n }\n return [];\n }\n /** Takes a JS class (its constructor) and assumes that it was decorated by\n * the @subjectClass etc. decorators. It then tests if there is a subject class\n * already present in the perspective's SDNA that matches the given class.\n * If there is no such class, it gets the JS class's SDNA by calling its\n * static generateSDNA() function and adds it to the perspective's SDNA.\n */\n async ensureSDNASubjectClass(jsClass) {\n return this.ensureSubjectClass(jsClass);\n }\n /** Takes a JS class (its constructor) and ensures the SHACL subject class exists. */\n async ensureSubjectClass(jsClass) {\n // Get the class name from the JS class\n const className = jsClass.className || jsClass.prototype?.className || jsClass.name;\n // Skip if already registered for this perspective instance\n if (__classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").has(className))\n return;\n // Note: Duplicate checking is handled on the Rust side in add_sdna\n // Generate SHACL SDNA (Prolog-free)\n if (!jsClass.generateSHACL) {\n throw new Error(`Class ${jsClass.name} must have generateSHACL(). Use @Model decorator.`);\n }\n // Get SHACL shape (W3C standard + AD4M action definitions)\n const { shape } = jsClass.generateSHACL();\n // Serialize SHACL shape to JSON for Rust backend using SHACLShape.toJSON()\n const shaclJson = JSON.stringify(shape.toJSON());\n // Pass SHACL JSON to backend (Prolog-free)\n // Backend stores SHACL links directly\n await this.addSdna(className, '', 'subject_class', shaclJson);\n // Mark as registered for this perspective instance\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").add(className);\n }\n /** Clear the per-instance ensured subject class cache.\n * Call this after wiping a perspective's links so that\n * subsequent register() calls re-add SHACL definitions. */\n clearEnsuredSubjectClasses() {\n __classPrivateFieldGet$a(this, _PerspectiveProxy_ensuredSubjectClasses, \"f\").clear();\n }\n /**\n * Returns a list of all class names that have been registered as SHACL\n * subject classes in this perspective (via `ensureSDNASubjectClass` or `addSdna`).\n *\n * @returns Array of class name strings (e.g. `[\"Channel\", \"Message\", \"Task\"]`)\n */\n async listRegisteredClasses() {\n const results = await this.querySparql(`SELECT DISTINCT ?class WHERE { ?class <rdf://type> <ad4m://SubjectClass> . }`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => {\n const uri = row.class || '';\n // Extract class name from URI like \"recipe://Recipe\" or \"flux://Channel\"\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(slashIdx + 1);\n return uri;\n }).filter(Boolean);\n }\n /**\n * Returns the SHACL shape metadata for a registered class, including\n * property names, predicates, datatypes, and cardinality constraints.\n *\n * @param className - The name of the registered class\n * @returns Shape metadata or `null` if the class is not registered\n */\n async getClassShape(className) {\n // Find the shape URI for this class\n const safeName = className.replace(/['\"\\\\]/g, '');\n const shapeResults = await this.querySparql(`SELECT ?shapeUri ?targetClass WHERE {\n ?targetClass <rdf://type> <ad4m://SubjectClass> .\n ?targetClass <ad4m://shape> ?shapeUri .\n FILTER(STRENDS(STR(?targetClass), \"/${safeName}\") || STRENDS(STR(?targetClass), \"#${safeName}\"))\n } LIMIT 1`);\n if (!Array.isArray(shapeResults) || shapeResults.length === 0)\n return null;\n const shapeUri = shapeResults[0].shapeUri;\n shapeResults[0].targetClass;\n // Query all properties for this shape, including sh:in\n const propResults = await this.querySparql(`SELECT ?propShape ?path ?datatype ?minCount ?maxCount ?writable ?propType ?shIn WHERE {\n <${shapeUri}> <sh://property> ?propShape .\n ?propShape <sh://path> ?path .\n ?propShape <rdf://type> ?propType .\n OPTIONAL { ?propShape <sh://datatype> ?datatype }\n OPTIONAL { ?propShape <sh://minCount> ?minCount }\n OPTIONAL { ?propShape <sh://maxCount> ?maxCount }\n OPTIONAL { ?propShape <ad4m://writable> ?writable }\n OPTIONAL { ?propShape <sh://in> ?shIn }\n }`);\n const properties = (Array.isArray(propResults) ? propResults : []).map((row) => {\n // Extract property name from shape URI like \"recipe://Recipe.name\"\n const propUri = row.propShape || '';\n const dotIdx = propUri.lastIndexOf('.');\n const name = dotIdx >= 0 ? propUri.substring(dotIdx + 1) : propUri;\n const minCount = parseInt(row.minCount || '0', 10);\n const isCollection = row.propType === 'ad4m://CollectionShape';\n const writable = row.writable === 'true' || row.writable === 'literal:true';\n // Parse sh:in values if present\n let options;\n if (row.shIn) {\n try {\n let raw = row.shIn;\n // Strip literal: prefix if present, and URI-decode for robustness\n if (raw.startsWith('literal:string:')) {\n raw = decodeURIComponent(raw.substring('literal:string:'.length));\n }\n options = JSON.parse(raw);\n }\n catch { /* ignore parse errors */ }\n }\n return {\n name,\n predicate: row.path || '',\n datatype: row.datatype || undefined,\n required: minCount > 0,\n collection: isCollection,\n writable,\n ...(options && options.length > 0 ? { options } : {}),\n };\n });\n return { className: safeName, shapeUri, properties };\n }\n /**\n * Detects which registered subject classes a given instance conforms to,\n * based on its stored triples matching the class shapes' required properties.\n *\n * @param baseExpression - The instance's base expression / subject URI\n * @returns Array of class names the instance matches\n */\n async getInstanceClasses(baseExpression) {\n const safeId = baseExpression.replace(/['\"\\\\]/g, '');\n // Get all registered classes and their required conformance properties\n const results = await this.querySparql(`SELECT DISTINCT ?class WHERE {\n ?class <rdf://type> <ad4m://SubjectClass> .\n ?class <ad4m://shape> ?shape .\n ?shape <sh://property> ?propShape .\n ?propShape <sh://minCount> ?mc .\n FILTER(?mc >= 1)\n ?propShape <sh://path> ?path .\n <${safeId}> ?path ?_val .\n }`);\n if (!Array.isArray(results))\n return [];\n return results.map((row) => {\n const uri = row.class || '';\n const hashIdx = uri.lastIndexOf('#');\n if (hashIdx >= 0)\n return uri.substring(hashIdx + 1);\n const slashIdx = uri.lastIndexOf('/');\n if (slashIdx >= 0)\n return uri.substring(slashIdx + 1);\n return uri;\n }).filter(Boolean);\n }\n /**\n * Returns all named options (sh:in values) for a registered class, grouped by property.\n *\n * @param className - The name of the registered class\n * @returns Record mapping property name \u2192 array of { value, label } options\n */\n async getNamedOptions(className) {\n const shape = await this.getClassShape(className);\n if (!shape)\n return {};\n const result = {};\n for (const prop of shape.properties) {\n if (prop.options && prop.options.length > 0) {\n result[prop.name] = prop.options;\n }\n }\n return result;\n }\n /**\n * Adds a named option (sh:in value) to a property of a registered class.\n * This appends to the existing sh:in list stored on the property shape.\n *\n * @param className - The registered class name\n * @param propertyName - The property to add the option to\n * @param value - The RDF value for the option\n * @param label - Optional human-readable label\n */\n async addNamedOption(className, propertyName, value, label) {\n const shape = await this.getClassShape(className);\n if (!shape)\n throw new Error(`Class \"${className}\" not found`);\n const prop = shape.properties.find(p => p.name === propertyName);\n if (!prop)\n throw new Error(`Property \"${propertyName}\" not found on class \"${className}\"`);\n // Build the property shape URI\n const ns = extractNamespaceFromUri(shape.shapeUri);\n const propShapeId = `${ns}${className}.${propertyName}`;\n // Get existing options\n const existing = prop.options || [];\n // Don't add duplicates\n if (existing.some(o => o.value === value))\n return;\n const updated = [...existing, { value, ...(label ? { label } : {}) }];\n // Remove old sh:in link if exists by querying for it\n const oldLinks = await this.get(new LinkQuery({ source: propShapeId, predicate: \"sh://in\" }));\n for (const oldLink of oldLinks) {\n await this.remove(oldLink);\n }\n // Add new sh:in link\n await this.add(new Link({\n source: propShapeId,\n predicate: \"sh://in\",\n target: `literal:string:${JSON.stringify(updated)}`\n }));\n }\n getNeighbourhoodProxy() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").getNeighbourhoodProxy(__classPrivateFieldGet$a(this, _PerspectiveProxy_handle, \"f\").uuid);\n }\n /**\n * Returns a proxy object for working with AI capabilities.\n *\n * @returns AIClient instance\n *\n * @example\n * ```typescript\n * // Use AI to analyze perspective content\n * const summary = await perspective.ai.summarize();\n *\n * // Generate new content\n * const suggestion = await perspective.ai.suggest(\"next action\");\n * ```\n */\n get ai() {\n return __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\").aiClient;\n }\n /**\n * Creates a subscription for a Prolog query that updates in real-time.\n *\n * This method:\n * 1. Creates the subscription on the Rust side\n * 2. Sets up the subscription callback\n * 3. Waits for the initial result to come through the subscription channel\n * 4. Returns a fully initialized QuerySubscriptionProxy\n *\n * The returned subscription is guaranteed to be ready to receive updates,\n * as this method waits for the initialization process to complete.\n *\n * The subscription will be automatically cleaned up on both frontend and backend\n * when dispose() is called. Make sure to call dispose() when you're done to\n * prevent memory leaks and ensure proper cleanup of resources.\n *\n * @param query - Prolog query string\n * @returns Initialized QuerySubscriptionProxy instance\n *\n * @example\n * ```typescript\n * // Subscribe to active todos\n * const subscription = await perspective.subscribeInfer(`\n * instance(Todo, \"Todo\"),\n * property_getter(\"Todo\", Todo, \"state\", \"active\")\n * `);\n *\n * // Subscription is already initialized here\n * console.log(\"Initial result:\", subscription.result);\n *\n * // Set up callback for future updates\n * subscription.onResult((todos) => {\n * console.log(\"Active todos:\", todos);\n * });\n *\n * // Clean up subscription when done\n * subscription.dispose();\n * ```\n */\n async subscribeInfer(query) {\n const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"));\n // Start the subscription on the Rust side first to get the real subscription ID\n await subscriptionProxy.subscribe();\n // Wait for the initial result\n await subscriptionProxy.initialized;\n return subscriptionProxy;\n }\n /**\n * Creates a subscription for a SPARQL query that updates in real-time.\n *\n * This method:\n * 1. Creates the subscription on the Rust side\n * 2. Sets up the subscription callback\n * 3. Waits for the initial result to come through the subscription channel\n * 4. Returns a fully initialized QuerySubscriptionProxy\n *\n * The returned subscription is guaranteed to be ready to receive updates,\n * as this method waits for the initialization process to complete.\n *\n * The subscription will be automatically cleaned up on both frontend and backend\n * when dispose() is called. Make sure to call dispose() when you're done to\n * prevent memory leaks and ensure proper cleanup of resources.\n *\n /** Subscribe to a query with live updates via the SPARQL subscription endpoint.\n * @param query - Query string\n * @returns Initialized QuerySubscriptionProxy instance\n */\n async subscribeQuery(query) {\n const subscriptionProxy = new QuerySubscriptionProxy(this.uuid, query, __classPrivateFieldGet$a(this, _PerspectiveProxy_client, \"f\"));\n // Start the subscription on the Rust side first to get the real subscription ID\n await subscriptionProxy.subscribe();\n // Wait for the initial result\n await subscriptionProxy.initialized;\n return subscriptionProxy;\n }\n}\n_PerspectiveProxy_handle = new WeakMap(), _PerspectiveProxy_client = new WeakMap(), _PerspectiveProxy_perspectiveLinkAddedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkRemovedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveLinkUpdatedCallbacks = new WeakMap(), _PerspectiveProxy_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveProxy_ensuredSubjectClasses = new WeakMap();\n\nvar __classPrivateFieldSet$9 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$9 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _PerspectiveClient_apiClient, _PerspectiveClient_perspectiveAddedCallbacks, _PerspectiveClient_perspectiveUpdatedCallbacks, _PerspectiveClient_perspectiveRemovedCallbacks, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, _PerspectiveClient_expressionClient, _PerspectiveClient_neighbourhoodClient, _PerspectiveClient_aiClient, _PerspectiveClient_unsubscribers, _PerspectiveClient_linkUnsubscribers, _PerspectiveClient_querySubscriptionUnsubscribers;\nfunction normalizeQueryResult(raw, errorContext) {\n let finalResult = raw;\n if (typeof finalResult === 'string') {\n try {\n finalResult = JSON.parse(finalResult);\n }\n catch (e) {\n console.error(errorContext, e);\n }\n }\n return finalResult;\n}\nclass PerspectiveClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _PerspectiveClient_apiClient.set(this, void 0);\n _PerspectiveClient_perspectiveAddedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveUpdatedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveRemovedCallbacks.set(this, void 0);\n _PerspectiveClient_perspectiveSyncStateChangeCallbacks.set(this, void 0);\n _PerspectiveClient_expressionClient.set(this, void 0);\n _PerspectiveClient_neighbourhoodClient.set(this, void 0);\n _PerspectiveClient_aiClient.set(this, void 0);\n _PerspectiveClient_unsubscribers.set(this, void 0);\n _PerspectiveClient_linkUnsubscribers.set(this, void 0);\n _PerspectiveClient_querySubscriptionUnsubscribers.set(this, void 0);\n __classPrivateFieldSet$9(this, _PerspectiveClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_unsubscribers, [], \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_linkUnsubscribers, new Map(), \"f\");\n __classPrivateFieldSet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, new Map(), \"f\");\n if (subscribe) {\n this.subscribePerspectiveAdded();\n this.subscribePerspectiveUpdated();\n this.subscribePerspectiveRemoved();\n }\n }\n setExpressionClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_expressionClient, client, \"f\");\n }\n setNeighbourhoodClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_neighbourhoodClient, client, \"f\");\n }\n setAIClient(client) {\n __classPrivateFieldSet$9(this, _PerspectiveClient_aiClient, client, \"f\");\n }\n get aiClient() {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_aiClient, \"f\");\n }\n async all() {\n const perspectives = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.all');\n return perspectives.map(handle => new PerspectiveProxy(handle, this));\n }\n async byUUID(uuid) {\n try {\n const perspective = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.get', { uuid });\n if (!perspective)\n return null;\n return new PerspectiveProxy(perspective, this);\n }\n catch (e) {\n if (e instanceof RpcError && e.status === 404)\n return null;\n throw e;\n }\n }\n async snapshotByUUID(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.snapshot', { uuid });\n }\n async publishSnapshotByUUID(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.publishSnapshot', { uuid });\n }\n async queryLinks(uuid, query) {\n const params = { uuid };\n if (query.source)\n params.source = query.source;\n if (query.predicate)\n params.predicate = query.predicate;\n if (query.target)\n params.target = query.target;\n if (query.fromDate)\n params.fromDate = query.fromDate instanceof Date ? query.fromDate.toISOString() : String(query.fromDate);\n if (query.untilDate)\n params.untilDate = query.untilDate instanceof Date ? query.untilDate.toISOString() : String(query.untilDate);\n if (query.limit !== undefined)\n params.limit = query.limit;\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.queryLinks', params);\n }\n async queryProlog(uuid, query) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.queryProlog', { uuid, query });\n return JSON.parse(result);\n }\n async querySparql(uuid, query) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.querySparql', { uuid, engine: 'sparql', query });\n return JSON.parse(result);\n }\n async subscribeQuery(uuid, query) {\n const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.subscribeQuery', { uuid, query });\n const { subscriptionId, result } = response;\n const parsed = normalizeQueryResult(result, 'Error parsing subscribeQuery result:');\n return { subscriptionId, result: parsed };\n }\n async perspectiveKeepAliveQuery(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.keepAliveQuery', { uuid, subscriptionId });\n }\n async perspectiveDisposeQuerySubscription(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.disposeQuery', { uuid, subscriptionId });\n }\n subscribeToQueryUpdates(subscriptionId, onData) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n const event = data;\n if (event.type !== 'query-subscription-update')\n return;\n const eventSubscriptionId = event.subscriptionId || event.subscription_id;\n if (eventSubscriptionId !== subscriptionId)\n return;\n const parsed = normalizeQueryResult(event.result, 'Error parsing query subscription:');\n onData(parsed);\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").set(subscriptionId, unsub);\n return unsub;\n }\n async keepAliveQuery(uuid, subscriptionId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.keepAliveQuery', { uuid, subscriptionId });\n }\n async disposeQuerySubscription(uuid, subscriptionId) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").get(subscriptionId);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$9(this, _PerspectiveClient_querySubscriptionUnsubscribers, \"f\").delete(subscriptionId);\n }\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.disposeQuery', { uuid, subscriptionId });\n }\n async modelQuery(uuid, className, queryJson, shapeJson) {\n const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.modelQuery', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });\n return JSON.parse(resultJson);\n }\n async evaluateGetters(uuid, className, instanceIds, shapeJson, propertyNames) {\n const resultJson = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.evaluateGetters', {\n uuid,\n class_name: className,\n instance_ids: instanceIds,\n shape_json: shapeJson,\n ...(propertyNames && { property_names: propertyNames }),\n });\n return JSON.parse(resultJson);\n }\n async modelSubscribe(uuid, className, queryJson, shapeJson) {\n const response = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson });\n return {\n subscriptionId: response.subscription_id,\n result: JSON.parse(response.result)\n };\n }\n async add(name) {\n const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.create', { name });\n return new PerspectiveProxy(handle, this);\n }\n async update(uuid, name) {\n const handle = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.update', { uuid, name });\n return new PerspectiveProxy(handle, this);\n }\n async remove(uuid) {\n const result = await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.remove', { uuid });\n return { perspectiveRemove: result };\n }\n async addLink(uuid, link, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLink', { uuid, link, status, batchId });\n }\n async addLinks(uuid, links, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLinks', { uuid, links, status, batchId });\n }\n async removeLinks(uuid, links, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.removeLinks', { uuid, links, batchId });\n }\n async linkMutations(uuid, mutations, status) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.linkMutations', { uuid, mutations, status });\n }\n async addLinkExpression(uuid, link, status = 'shared', batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addLinkExpression', { uuid, link, status, batchId });\n }\n async updateLink(uuid, oldLink, newLink, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.updateLink', { uuid, oldLink, newLink, batchId });\n }\n async removeLink(uuid, link, batchId) {\n delete link.__typename;\n delete link.data.__typename;\n delete link.proof.__typename;\n delete link.status;\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.removeLink', { uuid, link, batchId });\n }\n async addSdna(uuid, name, sdnaCode, sdnaType, shaclJson) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addSdna', { uuid, name, sdnaCode: sdnaCode || \"\", sdnaType, shaclJson });\n }\n async addSdnaBatch(uuid, entries) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.addSdna', { uuid, entries: entries.map(e => ({ ...e, sdnaCode: e.sdnaCode || \"\" })) });\n }\n async executeCommands(uuid, commands, expression, parameters, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.executeCommands', { uuid, commands, expression, parameters, batchId });\n }\n async createSubject(uuid, subjectClass, expressionAddress, initialValues, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.createSubject', { uuid, subjectClass, expressionAddress, initialValues, batchId });\n }\n async getSubjectData(uuid, subjectClass, expressionAddress) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.getSubjectData', { uuid, subjectClass, expressionAddress });\n }\n // ExpressionClient functions, needed for Subjects:\n async getExpression(expressionURI) {\n return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, \"f\").get(expressionURI);\n }\n async createExpression(content, languageAddress) {\n return await __classPrivateFieldGet$9(this, _PerspectiveClient_expressionClient, \"f\").create(content, languageAddress);\n }\n // Subscriptions:\n addPerspectiveAddedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveAdded() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-added') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveAddedCallbacks, \"f\").forEach(cb => cb(data.perspective));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n addPerspectiveUpdatedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveUpdated() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-updated') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveUpdatedCallbacks, \"f\").forEach(cb => cb(data.perspective));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n addPerspectiveSyncedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveSyncStateChangeCallbacks, \"f\").push(cb);\n }\n async addPerspectiveSyncStateChangeListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'sync-state-change' && data.uuid === uuid) {\n cb.forEach(c => c(data.state));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n await new Promise(resolve => setTimeout(resolve, 500));\n }\n addPerspectiveRemovedListener(cb) {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, \"f\").push(cb);\n }\n subscribePerspectiveRemoved() {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'perspective-removed') {\n __classPrivateFieldGet$9(this, _PerspectiveClient_perspectiveRemovedCallbacks, \"f\").forEach(cb => cb(data.uuid));\n }\n });\n __classPrivateFieldGet$9(this, _PerspectiveClient_unsubscribers, \"f\").push(unsub);\n }\n async addPerspectiveLinkAddedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-added' && data.perspectiveUuid === uuid) {\n cb.forEach(c => c(data.link));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n async addPerspectiveLinkRemovedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-removed' && data.perspectiveUuid === uuid) {\n const link = data.link;\n if (!link.status) {\n delete link.status;\n }\n cb.forEach(c => c(link));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n async addPerspectiveLinkUpdatedListener(uuid, cb) {\n const unsub = __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'link-updated' && data.perspectiveUuid === uuid) {\n const newLink = data.newLink;\n const oldLink = data.oldLink;\n if (!newLink.status) {\n delete newLink.status;\n }\n if (!oldLink.status) {\n delete oldLink.status;\n }\n cb.forEach(c => c(data));\n }\n });\n let existing = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid) || [];\n existing.push(unsub);\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").set(uuid, existing);\n await __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").waitForSubscription();\n }\n /** Unsubscribe all link/sync-state listeners registered for the given perspective UUID.\n * Called by PerspectiveProxy.dispose() to prevent subscription leaks. */\n removeAllListeners(uuid) {\n const unsubs = __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").get(uuid);\n if (unsubs) {\n for (const fn of unsubs) {\n try {\n fn();\n }\n catch { }\n }\n __classPrivateFieldGet$9(this, _PerspectiveClient_linkUnsubscribers, \"f\").delete(uuid);\n }\n }\n getNeighbourhoodProxy(uuid) {\n return new NeighbourhoodProxy(__classPrivateFieldGet$9(this, _PerspectiveClient_neighbourhoodClient, \"f\"), uuid);\n }\n async createBatch(uuid) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.createBatch', { uuid });\n }\n async commitBatch(uuid, batchId) {\n return __classPrivateFieldGet$9(this, _PerspectiveClient_apiClient, \"f\").call('perspective.commitBatch', { uuid, batchId });\n }\n}\n_PerspectiveClient_apiClient = new WeakMap(), _PerspectiveClient_perspectiveAddedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveUpdatedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveRemovedCallbacks = new WeakMap(), _PerspectiveClient_perspectiveSyncStateChangeCallbacks = new WeakMap(), _PerspectiveClient_expressionClient = new WeakMap(), _PerspectiveClient_neighbourhoodClient = new WeakMap(), _PerspectiveClient_aiClient = new WeakMap(), _PerspectiveClient_unsubscribers = new WeakMap(), _PerspectiveClient_linkUnsubscribers = new WeakMap(), _PerspectiveClient_querySubscriptionUnsubscribers = new WeakMap();\n\n/**\n * PersistentCache \u2014 two-tier persistent key-value cache abstraction.\n *\n * Provides an IndexedDB-backed implementation for browsers and a no-op\n * NullCache fallback for Node.js / environments without IndexedDB.\n *\n * Design goals:\n * - Lazy open: IDB connection is deferred until first access\n * - Fire-and-forget writes: put() resolves immediately (best-effort persistence)\n * - Graceful degradation: all IDB errors resolve (never reject), so callers\n * never need try/catch around cache operations\n * - Tree-shakeable: import only what you need\n */\nvar __classPrivateFieldSet$8 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$8 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _IDBCache_instances, _IDBCache_dbName, _IDBCache_storeName, _IDBCache_dbPromise, _IDBCache_version, _IDBCache_open;\n// \u2500\u2500 IndexedDB Implementation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nclass IDBCache {\n constructor(dbName, storeName) {\n _IDBCache_instances.add(this);\n _IDBCache_dbName.set(this, void 0);\n _IDBCache_storeName.set(this, void 0);\n _IDBCache_dbPromise.set(this, null);\n _IDBCache_version.set(this, 1);\n __classPrivateFieldSet$8(this, _IDBCache_dbName, dbName, \"f\");\n __classPrivateFieldSet$8(this, _IDBCache_storeName, storeName, \"f\");\n }\n async get(key) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readonly');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n const req = store.get(key);\n req.onsuccess = () => resolve(req.result ?? undefined);\n req.onerror = () => resolve(undefined);\n });\n }\n catch {\n return undefined;\n }\n }\n async put(key, value) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.put(value, key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve(); // fire-and-forget\n });\n }\n catch {\n // degrade gracefully\n }\n }\n async delete(key) {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.delete(key);\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve();\n });\n }\n catch {\n // degrade gracefully\n }\n }\n async clear() {\n try {\n const db = await __classPrivateFieldGet$8(this, _IDBCache_instances, \"m\", _IDBCache_open).call(this);\n return new Promise((resolve) => {\n const tx = db.transaction(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"), 'readwrite');\n const store = tx.objectStore(__classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\"));\n store.clear();\n tx.oncomplete = () => resolve();\n tx.onerror = () => resolve();\n });\n }\n catch {\n // degrade gracefully\n }\n }\n}\n_IDBCache_dbName = new WeakMap(), _IDBCache_storeName = new WeakMap(), _IDBCache_dbPromise = new WeakMap(), _IDBCache_version = new WeakMap(), _IDBCache_instances = new WeakSet(), _IDBCache_open = function _IDBCache_open() {\n if (!__classPrivateFieldGet$8(this, _IDBCache_dbPromise, \"f\")) {\n __classPrivateFieldSet$8(this, _IDBCache_dbPromise, new Promise((resolve, reject) => {\n const storeName = __classPrivateFieldGet$8(this, _IDBCache_storeName, \"f\");\n const req = indexedDB.open(__classPrivateFieldGet$8(this, _IDBCache_dbName, \"f\"), __classPrivateFieldGet$8(this, _IDBCache_version, \"f\"));\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(storeName)) {\n db.createObjectStore(storeName);\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n }), \"f\");\n }\n return __classPrivateFieldGet$8(this, _IDBCache_dbPromise, \"f\");\n};\n// \u2500\u2500 NullCache (no-op fallback for Node.js) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nclass NullCache {\n async get(_key) { return undefined; }\n async put(_key, _value) { }\n async delete(_key) { }\n async clear() { }\n}\n// \u2500\u2500 Factory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Create a PersistentCache backed by IndexedDB (browser) or NullCache (Node.js).\n *\n * @param dbName - IndexedDB database name\n * @param storeName - IndexedDB object store name\n */\nfunction createPersistentCache(dbName, storeName) {\n try {\n if (typeof indexedDB !== 'undefined') {\n return new IDBCache(dbName, storeName);\n }\n }\n catch {\n // indexedDB access threw (e.g. in a worker with restricted globals)\n }\n return new NullCache();\n}\n\nvar __classPrivateFieldSet$7 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$7 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AgentClient_apiClient, _AgentClient_baseUrl, _AgentClient_token, _AgentClient_appsChangedCallback, _AgentClient_updatedCallbacks, _AgentClient_agentStatusChangedCallbacks, _AgentClient_hostingUserInfoChangedCallbacks, _AgentClient_computeLogUpdatedCallbacks, _AgentClient_unsubscribers, _AgentClient_memCache, _AgentClient_persistent, _AgentClient_selfDid;\nclass AgentClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _AgentClient_apiClient.set(this, void 0);\n _AgentClient_baseUrl.set(this, void 0);\n _AgentClient_token.set(this, void 0);\n _AgentClient_appsChangedCallback.set(this, void 0);\n _AgentClient_updatedCallbacks.set(this, void 0);\n _AgentClient_agentStatusChangedCallbacks.set(this, void 0);\n _AgentClient_hostingUserInfoChangedCallbacks.set(this, void 0);\n _AgentClient_computeLogUpdatedCallbacks.set(this, void 0);\n _AgentClient_unsubscribers.set(this, void 0);\n // \u2500\u2500 byDID cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // L1: in-memory promise cache with timestamps for TTL\n _AgentClient_memCache.set(this, new Map());\n // L2: persistent cache (IndexedDB in browser, NullCache in Node)\n _AgentClient_persistent.set(this, void 0);\n // Self-DID for event-driven invalidation (no TTL for own profile)\n _AgentClient_selfDid.set(this, null);\n __classPrivateFieldSet$7(this, _AgentClient_baseUrl, baseUrl, \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_token, token, \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_updatedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_agentStatusChangedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_appsChangedCallback, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_computeLogUpdatedCallbacks, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_unsubscribers, [], \"f\");\n __classPrivateFieldSet$7(this, _AgentClient_persistent, createPersistentCache('ad4m-agent-cache', 'agents'), \"f\");\n if (subscribe) {\n this.subscribeAgentUpdated();\n this.subscribeAgentStatusChanged();\n this.subscribeAppsChanged();\n }\n }\n async me() {\n const agent = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.get');\n let agentObject = new Agent(agent.did, agent.perspective);\n agentObject.directMessageLanguage = agent.directMessageLanguage;\n // Auto-set selfDid so event-driven cache invalidation works\n // without requiring apps to call setSelfDid() manually\n if (agentObject.did && !__classPrivateFieldGet$7(this, _AgentClient_selfDid, \"f\")) {\n __classPrivateFieldSet$7(this, _AgentClient_selfDid, agentObject.did, \"f\");\n }\n return agentObject;\n }\n async status() {\n const agentStatus = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.status');\n return new AgentStatus(agentStatus);\n }\n async generate(passphrase) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.generate', { passphrase });\n return new AgentStatus(result);\n }\n async import(args) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.import', { ...args });\n return new AgentStatus(result);\n }\n async lock(passphrase) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.lock', { passphrase });\n return new AgentStatus(result);\n }\n async unlock(passphrase, holochain = true) {\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.unlock', { passphrase, holochain });\n return new AgentStatus(result);\n }\n async byDID(did) {\n const now = Date.now();\n const cached = __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").get(did);\n if (cached) {\n const isSelf = did === __classPrivateFieldGet$7(this, _AgentClient_selfDid, \"f\");\n // Self-DID: L1 always valid (event-driven invalidation)\n // Remote DID: L1 valid within TTL\n if (isSelf || (now - cached.ts) < AgentClient.REMOTE_AGENT_TTL_MS) {\n return cached.promise;\n }\n }\n // Deduplicate: store the promise immediately so concurrent calls share one RPC\n const promise = (async () => {\n // L2: check persistent cache before network\n const persisted = await __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").get(did);\n if (persisted) {\n return persisted;\n }\n // L3: network fetch\n const result = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.byDid', { did });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(did, result); // fire-and-forget write to L2\n return result;\n })();\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(did, { promise, ts: now });\n // Clean up on failure so next call retries\n promise.catch(() => {\n if (__classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").get(did)?.promise === promise) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").delete(did);\n }\n });\n return promise;\n }\n /**\n * Set the current agent's own DID.\n * The self-DID receives event-driven invalidation and is never TTL-expired.\n */\n setSelfDid(did) {\n __classPrivateFieldSet$7(this, _AgentClient_selfDid, did, \"f\");\n }\n /**\n * Invalidate a specific DID's cache entry in both L1 and L2.\n */\n invalidateByDid(did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").delete(did);\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").delete(did); // fire-and-forget\n }\n /**\n * Clear the entire L1 (memory) byDID cache.\n * L2 (IndexedDB) is preserved \u2014 agent data remains valid across sessions.\n */\n clearByDidCache() {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").clear();\n }\n async updatePublicPerspective(perspective) {\n const cleanedPerspective = JSON.parse(JSON.stringify(perspective));\n delete cleanedPerspective.__typename;\n cleanedPerspective.links.forEach((link) => {\n delete link.__typename;\n delete link.data.__typename;\n delete link.proof.__typename;\n delete link.status;\n });\n const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.updateProfile', { publicPerspective: cleanedPerspective });\n const agent = new Agent(a.did, a.perspective);\n agent.directMessageLanguage = a.directMessageLanguage;\n // Immediately update byDID cache so subsequent byDID() calls\n // return fresh data without waiting for the subscription event\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n return agent;\n }\n async mutatePublicPerspective(mutations) {\n const perspectiveClient = new PerspectiveClient(__classPrivateFieldGet$7(this, _AgentClient_baseUrl, \"f\"), __classPrivateFieldGet$7(this, _AgentClient_token, \"f\"));\n const proxyPerspective = await perspectiveClient.add(\"Agent Perspective Proxy\");\n const agentMe = await this.me();\n if (agentMe.perspective) {\n await proxyPerspective.loadSnapshot(agentMe.perspective);\n }\n for (const addition of mutations.additions) {\n await proxyPerspective.add(addition);\n }\n for (const removal of mutations.removals) {\n await proxyPerspective.remove(removal);\n }\n const snapshot = await proxyPerspective.snapshot();\n const agent = await this.updatePublicPerspective(snapshot);\n await perspectiveClient.remove(proxyPerspective.uuid);\n return agent;\n }\n async updateDirectMessageLanguage(directMessageLanguage) {\n const a = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.updateProfile', { dmLanguage: directMessageLanguage });\n const agent = new Agent(a.did, a.perspective);\n agent.directMessageLanguage = a.directMessageLanguage;\n // Immediately update byDID cache so subsequent byDID() calls\n // return fresh data without waiting for the subscription event\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, { promise: Promise.resolve(agent), ts: Date.now() });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n return agent;\n }\n async addEntanglementProofs(proofs) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.addEntanglementProofs', { proofs });\n }\n async deleteEntanglementProofs(proofs) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.deleteEntanglementProofs', { proofs });\n }\n async getEntanglementProofs() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.getEntanglementProofs');\n }\n async entanglementProofPreFlight(deviceKey, deviceKeyType) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.entanglementProofPreflight', { deviceKey, deviceKeyType });\n }\n addUpdatedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, \"f\").push(listener);\n }\n addAppChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_appsChangedCallback, \"f\").push(listener);\n }\n subscribeAgentUpdated() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'agent-updated') {\n const agent = (data.agent || data);\n // Update L1 and L2 cache from the event payload\n if (agent.did) {\n __classPrivateFieldGet$7(this, _AgentClient_memCache, \"f\").set(agent.did, {\n promise: Promise.resolve(agent),\n ts: Date.now(),\n });\n __classPrivateFieldGet$7(this, _AgentClient_persistent, \"f\").put(agent.did, agent); // fire-and-forget\n }\n __classPrivateFieldGet$7(this, _AgentClient_updatedCallbacks, \"f\").forEach((cb) => cb(agent));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n subscribeAppsChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'apps-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_appsChangedCallback, \"f\").forEach((cb) => cb());\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addAgentStatusChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_agentStatusChangedCallbacks, \"f\").push(listener);\n }\n subscribeAgentStatusChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'agent-status-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_agentStatusChangedCallbacks, \"f\").forEach((cb) => cb((data.agent || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addHostingUserInfoChangedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, \"f\").push(listener);\n }\n subscribeHostingUserInfoChanged() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'hosting-user-info-changed') {\n __classPrivateFieldGet$7(this, _AgentClient_hostingUserInfoChangedCallbacks, \"f\").forEach((cb) => cb((data.info || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n addComputeLogUpdatedListener(listener) {\n __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, \"f\").push(listener);\n }\n subscribeComputeLogUpdated() {\n const unsub = __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'compute-log-updated') {\n __classPrivateFieldGet$7(this, _AgentClient_computeLogUpdatedCallbacks, \"f\").forEach((cb) => cb((data.entry || data)));\n }\n });\n __classPrivateFieldGet$7(this, _AgentClient_unsubscribers, \"f\").push(unsub);\n }\n async requestCapability(authInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.requestCapability', { authInfo });\n }\n async permitCapability(auth) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.permitCapability', { auth });\n }\n async generateJwt(requestId, rand) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.generateJwt', { requestId, rand });\n }\n async getApps() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.getApps');\n }\n async removeApp(requestId) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.removeApp', { id: requestId });\n }\n async revokeToken(requestId) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.revokeToken', { token: requestId });\n }\n async isLocked() {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.isLocked');\n }\n async signMessage(message) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('agent.sign', { message });\n }\n // Multi-user methods\n async createUser(email, password, appInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.create', { email, password, appInfo });\n }\n async loginUser(email, password) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.login', { email, password });\n }\n async requestLoginVerification(email, appInfo) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.requestVerification', { email, appInfo });\n }\n async verifyEmailCode(email, code, verificationType) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('user.verifyEmail', { email, code, verificationType });\n }\n // Hosting methods\n async hostingUserInfo() {\n const resp = await __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.info');\n const info = resp?.userInfo || resp;\n return new HostingUserInfo(info.email || '', info.freeAccess ? 'unlimited' : String(info.credits ?? info.remainingCredits ?? '0'), info.hotWalletAddress || undefined, !!info.freeAccess);\n }\n async computeLog(since, limit, userEmail) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('runtime.computeLog', { since, limit, userEmail });\n }\n async setHotWalletAddress(address) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.setHotWallet', { address });\n }\n async requestPayment(amountHOT) {\n return __classPrivateFieldGet$7(this, _AgentClient_apiClient, \"f\").call('hosting.requestPayment', { amountHOT });\n }\n}\n_AgentClient_apiClient = new WeakMap(), _AgentClient_baseUrl = new WeakMap(), _AgentClient_token = new WeakMap(), _AgentClient_appsChangedCallback = new WeakMap(), _AgentClient_updatedCallbacks = new WeakMap(), _AgentClient_agentStatusChangedCallbacks = new WeakMap(), _AgentClient_hostingUserInfoChangedCallbacks = new WeakMap(), _AgentClient_computeLogUpdatedCallbacks = new WeakMap(), _AgentClient_unsubscribers = new WeakMap(), _AgentClient_memCache = new WeakMap(), _AgentClient_persistent = new WeakMap(), _AgentClient_selfDid = new WeakMap();\n/** TTL for remote (non-self) agent profiles in L1 cache (ms). */\nAgentClient.REMOTE_AGENT_TTL_MS = 5 * 60000; // 5 minutes\n\nvar __classPrivateFieldSet$6 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$6 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _LanguageClient_apiClient;\nclass LanguageClient {\n constructor(baseUrl, token, sharedApiClient) {\n _LanguageClient_apiClient.set(this, void 0);\n __classPrivateFieldSet$6(this, _LanguageClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n async byAddress(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.get', { address });\n }\n async byFilter(filter) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.all', { filter });\n }\n async all() {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.all');\n }\n async writeSettings(languageAddress, settings) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.writeSettings', { address: languageAddress, settings });\n }\n async applyTemplateAndPublish(sourceLanguageHash, templateData) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.applyTemplate', { sourceLanguageHash, templateData });\n }\n async publish(languagePath, languageMeta) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.publish', { languagePath, languageMeta });\n }\n async meta(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.meta', { address });\n }\n async source(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.source', { address });\n }\n async remove(address) {\n return __classPrivateFieldGet$6(this, _LanguageClient_apiClient, \"f\").call('language.remove', { address });\n }\n}\n_LanguageClient_apiClient = new WeakMap();\n\nvar __classPrivateFieldSet$5 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$5 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _NeighbourhoodClient_apiClient, _NeighbourhoodClient_signalHandlers, _NeighbourhoodClient_signalUnsubscribers;\nclass NeighbourhoodClient {\n constructor(baseUrl, token, sharedApiClient) {\n _NeighbourhoodClient_apiClient.set(this, void 0);\n _NeighbourhoodClient_signalHandlers.set(this, new Map());\n _NeighbourhoodClient_signalUnsubscribers.set(this, new Map());\n __classPrivateFieldSet$5(this, _NeighbourhoodClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n async publishFromPerspective(perspectiveUUID, linkLanguage, meta) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.publish', {\n perspectiveUUID, linkLanguage, meta\n });\n }\n async joinFromUrl(url) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.join', { url });\n }\n async otherAgents(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.otherAgents', { uuid: perspectiveUUID });\n }\n async hasTelepresenceAdapter(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.hasTelepresence', { uuid: perspectiveUUID });\n }\n async onlineAgents(perspectiveUUID) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.onlineAgents', { uuid: perspectiveUUID });\n }\n async setOnlineStatus(perspectiveUUID, status) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.setOnlineStatus', { uuid: perspectiveUUID, status });\n }\n async setOnlineStatusU(perspectiveUUID, status) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.setOnlineStatus', { uuid: perspectiveUUID, status, signed: false });\n }\n async sendSignal(perspectiveUUID, remoteAgentDid, payload) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendSignal', {\n uuid: perspectiveUUID, remoteAgentDid, payload\n });\n }\n async sendSignalU(perspectiveUUID, remoteAgentDid, payload) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendSignal', {\n uuid: perspectiveUUID, remoteAgentDid, payload, signed: false\n });\n }\n async sendBroadcast(perspectiveUUID, payload, loopback = false) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendBroadcast', {\n uuid: perspectiveUUID, payload, loopback\n });\n }\n async sendBroadcastU(perspectiveUUID, payload, loopback = false) {\n return __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").call('neighbourhood.sendBroadcast', {\n uuid: perspectiveUUID, payload, loopback, signed: false\n });\n }\n dispatchSignal(perspectiveUUID, signal) {\n const handlers = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(signal);\n }\n catch (e) {\n console.error(\"Error in signal handler:\", e);\n }\n }\n }\n }\n async subscribeToSignals(perspectiveUUID) {\n const unsub = __classPrivateFieldGet$5(this, _NeighbourhoodClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'signal') {\n this.dispatchSignal(perspectiveUUID, data.signal);\n }\n });\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").set(perspectiveUUID, unsub);\n }\n async addSignalHandler(perspectiveUUID, handler) {\n let handlersForPerspective = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (!handlersForPerspective) {\n handlersForPerspective = [];\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").set(perspectiveUUID, handlersForPerspective);\n handlersForPerspective.push(handler);\n await this.subscribeToSignals(perspectiveUUID);\n }\n else {\n handlersForPerspective.push(handler);\n }\n }\n removeSignalHandler(perspectiveUUID, handler) {\n const handlersForPerspective = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").get(perspectiveUUID);\n if (handlersForPerspective) {\n const index = handlersForPerspective.indexOf(handler);\n if (index > -1) {\n handlersForPerspective.splice(index, 1);\n }\n if (handlersForPerspective.length === 0) {\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalHandlers, \"f\").delete(perspectiveUUID);\n const unsub = __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").get(perspectiveUUID);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$5(this, _NeighbourhoodClient_signalUnsubscribers, \"f\").delete(perspectiveUUID);\n }\n }\n }\n }\n}\n_NeighbourhoodClient_apiClient = new WeakMap(), _NeighbourhoodClient_signalHandlers = new WeakMap(), _NeighbourhoodClient_signalUnsubscribers = new WeakMap();\n\nvar __classPrivateFieldSet$4 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$4 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _RuntimeClient_apiClient, _RuntimeClient_messageReceivedCallbacks, _RuntimeClient_exceptionOccurredCallbacks, _RuntimeClient_notificationTriggeredCallbacks, _RuntimeClient_notificationRequestedCallbacks, _RuntimeClient_unsubscribers;\nfunction normalizeExceptionType(type) {\n if (typeof type !== 'string' || type === type.toUpperCase()) {\n return type;\n }\n return type\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n .toUpperCase();\n}\nclass RuntimeClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _RuntimeClient_apiClient.set(this, void 0);\n _RuntimeClient_messageReceivedCallbacks.set(this, void 0);\n _RuntimeClient_exceptionOccurredCallbacks.set(this, void 0);\n _RuntimeClient_notificationTriggeredCallbacks.set(this, void 0);\n _RuntimeClient_notificationRequestedCallbacks.set(this, void 0);\n _RuntimeClient_unsubscribers.set(this, void 0);\n __classPrivateFieldSet$4(this, _RuntimeClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_messageReceivedCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_exceptionOccurredCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_notificationTriggeredCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_notificationRequestedCallbacks, [], \"f\");\n __classPrivateFieldSet$4(this, _RuntimeClient_unsubscribers, [], \"f\");\n if (subscribe) {\n this.subscribeMessageReceived();\n this.subscribeExceptionOccurred();\n this.subscribeNotificationTriggered();\n }\n }\n async info() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.info');\n }\n async tlsDomain() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.tlsDomain');\n }\n async quit() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.quit');\n }\n async openLink(url) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.openLink', { url });\n }\n async addTrustedAgents(agents) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.addTrustedAgents', { agents });\n }\n async deleteTrustedAgents(agents) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.deleteTrustedAgents', { agents });\n }\n async getTrustedAgents() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('agent.getTrustedAgents');\n }\n async addKnownLinkLanguageTemplates(addresses) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addLinkLanguageTemplates', { addresses });\n }\n async removeKnownLinkLanguageTemplates(addresses) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.removeLinkLanguageTemplates', { addresses });\n }\n async knownLinkLanguageTemplates() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.linkLanguageTemplates');\n }\n async addFriends(dids) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addFriends', { dids });\n }\n async removeFriends(dids) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.removeFriends', { dids });\n }\n async friends() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.friends');\n }\n async hcAgentInfos() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.hcAgentInfos');\n }\n async getNetworkMetrics() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.networkMetrics');\n }\n async restartHolochain() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.restartHolochain');\n }\n async hcAddAgentInfos(agentInfos) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.addHcAgentInfos', { agentInfos });\n }\n async verifyStringSignedByDid(did, didSigningKeyId, data, signedData) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.verifySignature', { did, didSigningKeyId, data, signedData });\n }\n async setStatus(perspective) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setStatus', { status: perspective });\n }\n async friendStatus(did) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.friendStatus', { did });\n }\n async friendSendMessage(did, message) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.sendFriendMessage', { did, message });\n }\n async messageInbox(filter) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.inbox', { filter });\n }\n async messageOutbox(filter) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.outbox', { filter });\n }\n async requestInstallNotification(notification) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.createNotification', { ...notification });\n }\n async grantNotification(id) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.grantNotification', { id, granted: true });\n }\n async exportDb(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.exportData', { type: \"db\", filePath });\n }\n async importDb(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.importData', { type: \"db\", filePath });\n }\n async notifications() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.notifications');\n }\n async updateNotification(id, notification) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.updateNotification', { ...notification, id });\n }\n async removeNotification(id) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.deleteNotification', { id });\n }\n async exportPerspective(uuid, filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.exportData', { type: \"perspective\", perspectiveUuid: uuid, filePath });\n }\n async importPerspective(filePath) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.importData', { type: \"perspective\", filePath });\n }\n async multiUserEnabled() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.multiUserEnabled');\n }\n async setMultiUserEnabled(enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.setMultiUserEnabled', { enabled });\n }\n async freeHostingEnabled() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.freeHostingEnabled');\n }\n async setFreeHostingEnabled(enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setFreeHostingEnabled', { enabled });\n }\n async listUsers() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.list');\n }\n async userWalletAddress(email) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.wallet', { email });\n }\n async emailTestModeEnable() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'enable' });\n }\n async emailTestModeDisable() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'disable' });\n }\n async emailTestGetCode(email) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'get-code', email });\n }\n async emailTestClearCodes() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'clear-codes' });\n }\n async emailTestSetExpiry(email, verificationType, expiresAt) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.emailTest', { action: 'set-expiry', email, verificationType, expiresAt });\n }\n // ---- Unyt / mHOT methods ----\n async unytAgentKey() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytAgentKey');\n }\n async unytHotAgentPubkey() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytHotAgentPubkey');\n }\n async unytWalletBalance() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytWalletBalance');\n }\n async unytWalletHistory(page, perPage) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytWalletHistory', { page, perPage });\n }\n async unytVersionInfo() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytVersionInfo');\n }\n async unytSetMembraneProof(proof) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytSetMembraneProof', { proof });\n }\n async unytReinstallDna() {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytReinstallDna');\n }\n async unytSendHot(recipient, amount) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.unytSendHot', { recipient, amount });\n }\n async setUserCredits(email, amount) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.credits', { email, amount });\n }\n async setUserFreeAccess(email, enabled) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('user.freeAccess', { email, enabled });\n }\n async setHostRates(ratesJson) {\n return __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.setHostRates', { ratesJson });\n }\n async getHostRates() {\n const result = await __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").call('runtime.getHostRates');\n try {\n return JSON.parse(result);\n }\n catch {\n return [];\n }\n }\n addNotificationTriggeredCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_notificationTriggeredCallbacks, \"f\").push(cb);\n }\n subscribeNotificationTriggered() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'notification-triggered') {\n __classPrivateFieldGet$4(this, _RuntimeClient_notificationTriggeredCallbacks, \"f\").forEach(cb => cb(data.notification));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n addMessageCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_messageReceivedCallbacks, \"f\").push(cb);\n }\n subscribeMessageReceived() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'message-received') {\n __classPrivateFieldGet$4(this, _RuntimeClient_messageReceivedCallbacks, \"f\").forEach(cb => cb(data.message));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n addExceptionCallback(cb) {\n __classPrivateFieldGet$4(this, _RuntimeClient_exceptionOccurredCallbacks, \"f\").push(cb);\n }\n subscribeExceptionOccurred() {\n const unsub = __classPrivateFieldGet$4(this, _RuntimeClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'exception-occurred' && data.exception) {\n const exception = data.exception;\n const normalizedException = {\n ...exception,\n type: normalizeExceptionType(exception.type),\n };\n __classPrivateFieldGet$4(this, _RuntimeClient_exceptionOccurredCallbacks, \"f\").forEach(cb => cb(normalizedException));\n }\n });\n __classPrivateFieldGet$4(this, _RuntimeClient_unsubscribers, \"f\").push(unsub);\n }\n}\n_RuntimeClient_apiClient = new WeakMap(), _RuntimeClient_messageReceivedCallbacks = new WeakMap(), _RuntimeClient_exceptionOccurredCallbacks = new WeakMap(), _RuntimeClient_notificationTriggeredCallbacks = new WeakMap(), _RuntimeClient_notificationRequestedCallbacks = new WeakMap(), _RuntimeClient_unsubscribers = new WeakMap();\n\nvar __classPrivateFieldSet$3 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$3 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ExpressionClient_instances, _ExpressionClient_apiClient, _ExpressionClient_memCache, _ExpressionClient_inflight, _ExpressionClient_totalMemBytes, _ExpressionClient_persistent, _ExpressionClient_memCacheResult;\nclass ExpressionClient {\n constructor(baseUrl, token, sharedApiClient) {\n _ExpressionClient_instances.add(this);\n _ExpressionClient_apiClient.set(this, void 0);\n // L1: in-memory LRU cache (hot path, sub-ms)\n _ExpressionClient_memCache.set(this, new Map());\n _ExpressionClient_inflight.set(this, new Map());\n _ExpressionClient_totalMemBytes.set(this, 0);\n // L2: persistent cache (IndexedDB in browser, NullCache in Node)\n _ExpressionClient_persistent.set(this, void 0);\n __classPrivateFieldSet$3(this, _ExpressionClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n __classPrivateFieldSet$3(this, _ExpressionClient_persistent, createPersistentCache('ad4m-expression-cache', 'expressions'), \"f\");\n }\n async get(url, alwaysGet = false) {\n // Existing literal fast-path\n if (!alwaysGet) {\n try {\n let literalValue = Literal.fromUrl(url).get();\n if (typeof literalValue === 'object' && literalValue !== null) {\n if ('author' in literalValue && 'timestamp' in literalValue && 'data' in literalValue && 'proof' in literalValue) {\n return literalValue;\n }\n }\n }\n catch (e) { }\n }\n // L1: memory hit\n if (!alwaysGet) {\n const memHit = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(url);\n if (memHit)\n return memHit.data;\n }\n // Deduplicate in-flight requests\n if (!alwaysGet) {\n const existing = __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").get(url);\n if (existing)\n return existing;\n }\n // L2 check + L3 network\n const promise = (async () => {\n if (!alwaysGet) {\n const persisted = await __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").get(url);\n if (persisted) {\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, url, persisted); // promote to L1\n return persisted;\n }\n }\n // L3: network fetch\n const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.get', { url });\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, url, result);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").put(url, result); // fire-and-forget write to L2\n return result;\n })();\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").set(url, promise);\n try {\n return await promise;\n }\n finally {\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").delete(url);\n }\n }\n async getMany(urls) {\n // Check L1 first\n const results = urls.map(u => __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(u)?.data ?? null);\n let uncachedIndices = results\n .map((r, i) => r === null ? i : -1)\n .filter(i => i >= 0);\n if (uncachedIndices.length === 0)\n return results;\n // Check L2 for remaining misses\n const l2Results = await Promise.all(uncachedIndices.map(i => __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").get(urls[i])));\n const stillMissing = [];\n for (let j = 0; j < uncachedIndices.length; j++) {\n const idx = uncachedIndices[j];\n if (l2Results[j]) {\n results[idx] = l2Results[j];\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, urls[idx], l2Results[j]); // promote to L1\n }\n else {\n stillMissing.push(idx);\n }\n }\n if (stillMissing.length === 0)\n return results;\n // L3: fetch only truly uncached URLs\n const uncachedUrls = stillMissing.map(i => urls[i]);\n const fetched = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.getMany', { urls: uncachedUrls });\n for (let i = 0; i < stillMissing.length; i++) {\n const idx = stillMissing[i];\n results[idx] = fetched[i];\n if (fetched[i]) {\n __classPrivateFieldGet$3(this, _ExpressionClient_instances, \"m\", _ExpressionClient_memCacheResult).call(this, uncachedUrls[i], fetched[i]);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").put(uncachedUrls[i], fetched[i]); // fire-and-forget\n }\n }\n return results;\n }\n /**\n * Clear both L1 (memory) and L2 (persistent) expression caches.\n */\n clearCache() {\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").clear();\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").clear();\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, 0, \"f\");\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").clear(); // fire-and-forget\n }\n async getRaw(url) {\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.get', { url, raw: true });\n }\n async create(content, languageAddress) {\n const serialized = JSON.stringify(content);\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.create', { content: serialized, languageAddress });\n }\n async interactions(url) {\n return __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.interactions', { url });\n }\n async interact(url, interactionCall) {\n const result = await __classPrivateFieldGet$3(this, _ExpressionClient_apiClient, \"f\").call('expression.interact', { url, interactionCall });\n // Interactions can mutate the expression \u2014 invalidate cache so next get() fetches fresh\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").delete(url);\n __classPrivateFieldGet$3(this, _ExpressionClient_inflight, \"f\").delete(url);\n __classPrivateFieldGet$3(this, _ExpressionClient_persistent, \"f\").delete(url); // fire-and-forget\n return result;\n }\n}\n_ExpressionClient_apiClient = new WeakMap(), _ExpressionClient_memCache = new WeakMap(), _ExpressionClient_inflight = new WeakMap(), _ExpressionClient_totalMemBytes = new WeakMap(), _ExpressionClient_persistent = new WeakMap(), _ExpressionClient_instances = new WeakSet(), _ExpressionClient_memCacheResult = function _ExpressionClient_memCacheResult(url, data) {\n const size = JSON.stringify(data).length;\n // Evict oldest entries if we'd exceed limits\n while (__classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").size >= ExpressionClient.MAX_MEM_ENTRIES ||\n __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") + size > ExpressionClient.MAX_MEM_BYTES) {\n const oldest = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").keys().next().value;\n if (!oldest)\n break;\n const entry = __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").get(oldest);\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") - entry.size, \"f\");\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").delete(oldest);\n }\n __classPrivateFieldGet$3(this, _ExpressionClient_memCache, \"f\").set(url, { data, size });\n __classPrivateFieldSet$3(this, _ExpressionClient_totalMemBytes, __classPrivateFieldGet$3(this, _ExpressionClient_totalMemBytes, \"f\") + size, \"f\");\n};\n/** Maximum number of entries in the L1 memory cache. */\nExpressionClient.MAX_MEM_ENTRIES = 200;\n/** Maximum total size (in bytes) of L1 memory cache values. */\nExpressionClient.MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB\n\nvar base64Js = {};\n\nbase64Js.byteLength = byteLength;\nbase64Js.toByteArray = toByteArray;\nbase64Js.fromByteArray = fromByteArray;\n\nvar lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62;\nrevLookup['_'.charCodeAt(0)] = 63;\n\nfunction getLens (b64) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=');\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xFF;\n arr[curByte++] = (tmp >> 8) & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xFF;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xFF;\n arr[curByte++] = tmp & 0xFF;\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF);\n output.push(tripletToBase64(tmp));\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n );\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n );\n }\n\n return parts.join('')\n}\n\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n // \"inconsistent bit counts\");\n //Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n for (n = 0; n <= max_code; n++) {\n let len = tree[n * 2 + 1]/*.Len*/;\n if (len === 0) { continue; }\n /* Now reverse the bits */\n tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);\n\n //Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n }\n};\n\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nconst tr_static_init = () => {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nclass AIPromptExamplesInput {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n }\n}\nclass AIPromptExamples {\n constructor(input, output) {\n this.input = input;\n this.output = output;\n }\n}\nclass AITaskInput {\n constructor(name, model_id, system_prompt, prompt_examples, metaData) {\n this.name = name;\n this.modelId = model_id;\n this.systemPrompt = system_prompt;\n this.promptExamples = prompt_examples;\n this.metaData = metaData;\n }\n}\nclass AITask {\n constructor(name, model_id, task_id, system_prompt, prompt_examples, metaData, created_at, updated_at) {\n this.name = name;\n this.modelId = model_id;\n this.taskId = task_id;\n this.systemPrompt = system_prompt;\n this.promptExamples = prompt_examples;\n this.metaData = metaData;\n this.createdAt = created_at;\n this.updatedAt = updated_at;\n }\n}\nclass AIModelLoadingStatus {\n constructor(model, status, progress, downloaded, loaded) {\n this.model = model;\n this.status = status;\n this.progress = progress;\n this.downloaded = downloaded;\n this.loaded = loaded;\n }\n}\n\nvar __classPrivateFieldSet$2 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$2 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AIClient_apiClient, _AIClient_transcriptionUnsubscribers, _AIClient_pendingStreamIds;\nclass AIClient {\n constructor(baseUrl, token, subscribe = true, sharedApiClient) {\n _AIClient_apiClient.set(this, void 0);\n _AIClient_transcriptionUnsubscribers.set(this, new Map());\n _AIClient_pendingStreamIds.set(this, new Set());\n __classPrivateFieldSet$2(this, _AIClient_apiClient, sharedApiClient || new ApiClient(baseUrl, token), \"f\");\n }\n serializeModelInput(model) {\n const payload = { ...model };\n if ('modelType' in payload) {\n payload.type = payload.modelType;\n delete payload.modelType;\n }\n return payload;\n }\n async getModels() {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.models');\n }\n async addModel(model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.addModel', { model: this.serializeModelInput(model) });\n }\n async updateModel(modelId, model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.updateModel', { id: modelId, model: this.serializeModelInput(model) });\n }\n async removeModel(modelId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.removeModel', { id: modelId });\n }\n async setDefaultModel(modelType, modelId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.setDefaultModel', { id: modelId, modelType });\n }\n async getDefaultModel(modelType) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.getDefaultModel', { modelType });\n }\n async tasks() {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.tasks');\n }\n async addTask(name, modelId, systemPrompt, promptExamples, metaData) {\n const task = new AITaskInput(name, modelId, systemPrompt, promptExamples, metaData);\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.addTask', { task });\n }\n async removeTask(taskId) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.removeTask', { id: taskId });\n }\n async updateTask(taskId, task) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.updateTask', {\n id: taskId,\n task: {\n name: task.name,\n modelId: task.modelId,\n systemPrompt: task.systemPrompt,\n promptExamples: task.promptExamples\n }\n });\n }\n async modelLoadingStatus(model) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.modelLoadingStatus', { model });\n }\n async prompt(taskId, prompt) {\n return __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.prompt', { taskId, prompt });\n }\n async embed(modelId, text) {\n const aiEmbed = await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.embed', { modelId, text });\n const compressed = base64Js.toByteArray(aiEmbed);\n const decompressed = JSON.parse(pako.inflate(compressed, { to: 'string' }));\n return decompressed;\n }\n async openTranscriptionStream(modelId, streamCallback, params) {\n const streamId = await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.transcriptionOpen', { modelId, params });\n const unsub = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").subscribe((data) => {\n if (data.type === 'transcription-text' && data.streamId === streamId && data.text) {\n streamCallback(data.text);\n }\n });\n __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").set(streamId, unsub);\n return streamId;\n }\n async closeTranscriptionStream(streamId) {\n __classPrivateFieldGet$2(this, _AIClient_pendingStreamIds, \"f\").delete(streamId);\n await __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").call('ai.transcriptionClose', { streamId });\n const unsub = __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").get(streamId);\n if (unsub) {\n unsub();\n __classPrivateFieldGet$2(this, _AIClient_transcriptionUnsubscribers, \"f\").delete(streamId);\n }\n }\n /**\n * Feed an audio utterance to one or more transcription streams.\n * Sends raw binary Float32Array as application/octet-stream.\n * NOTE: This method still uses HTTP fetch because binary audio data\n * cannot be efficiently sent over the JSON-based WebSocket RPC protocol.\n * Transcription results are delivered via the WS event channel.\n */\n async feedTranscriptionStream(streamIds, audio) {\n const ids = Array.isArray(streamIds) ? streamIds : [streamIds];\n // Ensure we have a typed array for binary transport\n const typedAudio = audio instanceof Float32Array\n ? audio\n : new Float32Array(audio);\n if (ids.length === 0 || typedAudio.length === 0) {\n return;\n }\n const baseUrl = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").getBaseUrl();\n const token = __classPrivateFieldGet$2(this, _AIClient_apiClient, \"f\").getToken();\n // Use slice to get only the relevant portion of the underlying ArrayBuffer\n // (Float32Array may be a view over a larger buffer)\n const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);\n const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'X-Stream-Ids': ids.join(','),\n ...(token ? { 'Authorization': `Bearer ${token}` } : {}),\n },\n body: bodyBuffer,\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(`[AIClient] feed failed: ${response.status} ${response.statusText} ${text}`);\n }\n }\n}\n_AIClient_apiClient = new WeakMap(), _AIClient_transcriptionUnsubscribers = new WeakMap(), _AIClient_pendingStreamIds = new WeakMap();\n\n/**\n * Shared query helpers used by both the Prolog and SPARQL query pipelines.\n */\n/**\n * Resolves the predicate for a parent query.\n *\n * Uses TS discriminated union narrowing:\n * - Raw form (`{ id, predicate }`) \u2192 predicate used as-is\n * - Model form (`{ model, id, field? }`) \u2192 lookup from relation metadata\n * - With `field`: direct key lookup\n * - Without `field`: scan for a relation whose `target()` matches `childCtor`\n */\nfunction resolveParentPredicate(parent, childCtor) {\n // Raw form \u2014 explicit predicate\n if ('predicate' in parent)\n return parent.predicate;\n // Model form \u2014 resolve from relation metadata\n const { model } = parent;\n const relMeta = getRelationsMetadata(model);\n // Direct lookup by field name when provided\n if (parent.field) {\n const entry = relMeta[parent.field];\n if (!entry) {\n throw new Error(`parent(): field \"${parent.field}\" is not a registered relation on ${model.name}`);\n }\n return entry.predicate;\n }\n // Fallback: scan for a relation whose target matches the child class\n for (const [, entry] of Object.entries(relMeta)) {\n if (entry.target && entry.target() === childCtor) {\n return entry.predicate;\n }\n }\n throw new Error(`parent(): could not resolve predicate \u2014 no relation on ${model.name} targets ${childCtor.name || 'the queried class'}`);\n}\n\n/**\n * JSON Schema \u2192 Ad4mModel class builder and related utilities.\n *\n * Contains:\n * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)\n * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)\n * - Predicate / namespace resolution helpers\n * - `buildModelFromJSONSchema()` \u2014 core implementation of `Ad4mModel.fromJSONSchema()`\n *\n * @module\n */\n// \u2500\u2500\u2500 Schema Type Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nfunction normalizeNamespaceString(namespace) {\n if (!namespace)\n return '';\n if (namespace.includes('://')) {\n const [scheme, rest] = namespace.split('://');\n const path = (rest || '').replace(/\\/+$/, '');\n return `${scheme}://${path}`;\n }\n else {\n return namespace.replace(/\\/+$/, '');\n }\n}\nfunction normalizeSchemaType(type) {\n if (!type)\n return undefined;\n if (typeof type === \"string\")\n return type;\n if (Array.isArray(type) && type.length > 0) {\n const nonNull = type.find((t) => t !== \"null\");\n return nonNull || type[0];\n }\n return undefined;\n}\nfunction isSchemaType(schema, expectedType) {\n return normalizeSchemaType(schema.type) === expectedType;\n}\nfunction isArrayType(schema) {\n return isSchemaType(schema, \"array\");\n}\nfunction isObjectType(schema) {\n return isSchemaType(schema, \"object\");\n}\nfunction isNumericType(schema) {\n const normalized = normalizeSchemaType(schema.type);\n return normalized === \"number\" || normalized === \"integer\";\n}\n// \u2500\u2500\u2500 Predicate / Namespace Resolution \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Determines the namespace for predicates using cascading precedence:\n * 1. Explicit namespace in options\n * 2. x-ad4m metadata in schema\n * 3. Infer from schema title\n * 4. Try to extract from $id\n * 5. Error if nothing works\n */\nfunction determineNamespace(schema, options) {\n // 1. Explicit namespace in options (highest precedence)\n if (options.namespace) {\n return options.namespace;\n }\n // 2. x-ad4m metadata in schema\n if (schema[\"x-ad4m\"]?.namespace) {\n return schema[\"x-ad4m\"].namespace;\n }\n // 3. Infer from schema title\n if (schema.title) {\n return `${schema.title.toLowerCase()}://`;\n }\n // 4. Try to extract from $id if it's a URL\n if (schema.$id) {\n try {\n const url = new URL(schema.$id);\n const pathParts = url.pathname.split('/').filter(p => p);\n if (pathParts.length > 0) {\n const lastPart = pathParts[pathParts.length - 1];\n const baseName = lastPart.replace(/\\.schema\\.json$/, '').replace(/\\.json$/, '');\n return `${baseName.toLowerCase()}://`;\n }\n }\n catch {\n // If $id is not a valid URL, continue to error\n }\n }\n // 5. Error if no namespace can be determined\n throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:\n - options.namespace\n - schema[\"x-ad4m\"].namespace \n - schema.title\n - valid schema.$id`);\n}\n/**\n * Determines the predicate for a specific property using cascading precedence:\n * 1. Explicit property mapping\n * 2. x-ad4m metadata in property schema\n * 3. Predicate template\n * 4. Custom predicate generator\n * 5. Default: namespace + property name\n */\nfunction determinePredicate(schema, propertyName, propertySchema, namespace, options) {\n // 1. Explicit property mapping (highest precedence)\n if (options.propertyMapping?.[propertyName]) {\n return options.propertyMapping[propertyName];\n }\n // 2. x-ad4m metadata in property schema\n if (propertySchema[\"x-ad4m\"]?.through) {\n return propertySchema[\"x-ad4m\"].through;\n }\n // 3. Generate from namespace + property name\n if (options.predicateTemplate) {\n const normalizedNs = normalizeNamespaceString(namespace);\n const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];\n const nsNoScheme = rest || '';\n return options.predicateTemplate\n .replace('${namespace}', nsNoScheme)\n .replace('${scheme}', scheme)\n .replace('${ns}', nsNoScheme)\n .replace('${title}', schema.title || '')\n .replace('${property}', propertyName);\n }\n // 4. Custom predicate generator\n if (options.predicateGenerator) {\n return options.predicateGenerator(schema.title || '', propertyName);\n }\n // 5. Default: namespace + property name\n const normalizedNs = normalizeNamespaceString(namespace);\n if (normalizedNs.includes('://')) {\n // For namespaces like \"product://\", append property directly\n return `${normalizedNs}${propertyName}`;\n }\n else {\n return `${normalizedNs}://${propertyName}`;\n }\n}\n/**\n * Gets property-specific options using cascading precedence:\n * 1. Property-specific options\n * 2. x-ad4m metadata in property\n * 3. Global option\n * 4. Default value\n */\nfunction getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {\n // 1. Property-specific options\n if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {\n return options.propertyOptions[propertyName][optionName];\n }\n // 2. x-ad4m metadata in property\n if (propertySchema[\"x-ad4m\"]?.[optionName] !== undefined) {\n return propertySchema[\"x-ad4m\"][optionName];\n }\n // 3. Global option\n if (options[optionName] !== undefined) {\n return options[optionName];\n }\n // 4. Default value\n return defaultValue;\n}\n/**\n * Gets default value for a JSON Schema type.\n */\nfunction getDefaultValueForType(type) {\n switch (type) {\n case 'string': return '';\n case 'number': return 0;\n case 'integer': return 0;\n case 'boolean': return false;\n case 'array': return [];\n case 'object': return {};\n default: return '';\n }\n}\n// \u2500\u2500\u2500 buildModelFromJSONSchema \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Core implementation of `Ad4mModel.fromJSONSchema()`.\n *\n * Creates a dynamic Ad4mModel subclass from a JSON Schema definition,\n * wiring up property / relation metadata, setters, and the `@Model` decorator.\n *\n * @param BaseClass - The Ad4mModel class (or subclass) to extend\n * @param schema - JSON Schema definition\n * @param options - Configuration options\n * @returns Generated Ad4mModel subclass\n */\nfunction buildModelFromJSONSchema(BaseClass, schema, options) {\n // Disallow top-level \"author\" property since Ad4mModel provides it implicitly via link authorship\n if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, \"author\")) {\n throw new Error('JSON Schema must not define a top-level \"author\" property because Ad4mModel already exposes it. Please rename the property (e.g., \"writer\").');\n }\n // Determine namespace with cascading precedence\n const namespace = determineNamespace(schema, options);\n // Create the dynamic class\n const DynamicModelClass = class extends BaseClass {\n };\n // Set up class metadata\n if (!options.name || options.name.trim() === '') {\n throw new Error(\"options.name is required and cannot be empty\");\n }\n DynamicModelClass.className = options.name;\n DynamicModelClass.prototype.className = options.name;\n // Generate properties and relations metadata\n const properties = {};\n const relations = {};\n if (schema.properties) {\n for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {\n const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);\n const isRequired = schema.required?.includes(propertyName) || false;\n const propertyType = normalizeSchemaType(propertySchema.type);\n const isArray = isArrayType(propertySchema);\n if (isArray) {\n // Handle arrays as relations\n // Store the singular form as the relation key since SDNA generation expects singular\n relations[propertyName] = {\n through: predicate,\n local: getPropertyOption(propertyName, propertySchema, options, 'local')\n };\n // Define the property on prototype\n Object.defineProperty(DynamicModelClass.prototype, propertyName, {\n configurable: true,\n writable: true,\n value: []\n });\n // Add relation methods\n const adderName = `add${capitalize(propertyName)}`;\n const removerName = `remove${capitalize(propertyName)}`;\n const setterName = `set${capitalize(propertyName)}`;\n DynamicModelClass.prototype[adderName] = function () {\n // Placeholder function for SDNA generation\n };\n DynamicModelClass.prototype[removerName] = function () {\n // Placeholder function for SDNA generation\n };\n DynamicModelClass.prototype[setterName] = function () {\n // Placeholder function for SDNA generation\n };\n }\n else {\n // Handle regular properties\n let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');\n // If no specific resolveLanguage for this property, use the global one\n if (!resolveLanguage && options.resolveLanguage) {\n resolveLanguage = options.resolveLanguage;\n }\n const local = getPropertyOption(propertyName, propertySchema, options, 'local');\n // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format\n let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');\n if (readOnly === undefined) {\n const xWritable = propertySchema[\"x-ad4m\"]?.writable;\n readOnly = xWritable !== undefined ? !xWritable : false;\n }\n const writable = !readOnly;\n let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');\n // Handle nested objects by serializing to JSON\n if (isObjectType(propertySchema) && !resolveLanguage) {\n resolveLanguage = 'literal';\n console.warn(`Property \"${propertyName}\" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);\n }\n // Ensure numeric properties use literal language for correct typing\n if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {\n resolveLanguage = 'literal';\n }\n // Default resolveLanguage to 'literal' for all remaining property types,\n // matching the @Property decorator behaviour. Without this, string values\n // stored as literal: URLs are returned unparsed.\n if (resolveLanguage === undefined || resolveLanguage === null) {\n resolveLanguage = 'literal';\n }\n // If property is required, ensure it has an initial value\n if (isRequired && !initial) {\n if (isObjectType(propertySchema)) {\n initial = 'literal:json:{}';\n }\n else {\n initial = \"ad4m://undefined\";\n }\n }\n properties[propertyName] = {\n through: predicate,\n required: isRequired,\n writable: writable,\n ...(resolveLanguage && { resolveLanguage }),\n ...(local !== undefined && { local }),\n ...(initial && { initial })\n };\n // Define the property on prototype\n Object.defineProperty(DynamicModelClass.prototype, propertyName, {\n configurable: true,\n writable: true,\n value: getDefaultValueForType(propertyType)\n });\n // Add setter function if writable\n if (writable) {\n const setterName = propertyNameToSetterName(propertyName);\n DynamicModelClass.prototype[setterName] = function () {\n // This is a placeholder function that the SDNA generation looks for\n // The actual setter logic is handled by the Ad4mModel base class\n };\n }\n }\n }\n }\n // No auto-flag generation \u2014 models with all-optional properties use\n // open-world structural matching. Consumers who need type discrimination\n // should add an explicit @Flag to their model definition.\n // Attach metadata to WeakMap registries\n for (const [propName, propMeta] of Object.entries(properties)) {\n setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);\n }\n for (const [relName, relMeta] of Object.entries(relations)) {\n setRelationRegistryEntry(DynamicModelClass, relName, {\n predicate: relMeta.through || \"\",\n kind: 'hasMany',\n ...(relMeta.getter !== undefined && { getter: relMeta.getter }),\n ...(relMeta.local !== undefined && { local: relMeta.local }),\n });\n }\n // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()\n DynamicModelClass.prototype.__jsonSchema = schema;\n DynamicModelClass.prototype.__jsonSchemaOptions = options;\n // Apply the Model decorator to set up the generateSDNA method\n const ModelDecorator = Model$1({ name: options.name });\n ModelDecorator(DynamicModelClass);\n return DynamicModelClass;\n}\n\n/**\n * SPARQL query building utilities for Ad4mModel.\n *\n * Uses the RDF 1.2 reifier storage model where each AD4M link is stored as:\n * 1. Direct triple: <source> <predicate> <target> . (default graph)\n * 2. Reifier: <link:HASH> <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( source predicate target )>> .\n * 3. Metadata: <link:HASH> ad4m://ontology/* \"value\" . (default graph)\n *\n * All AD4M URIs (source, predicate, target) become RDF IRIs.\n *\n * @module\n */\n/**\n * Check whether a `where` clause contains filters that cannot be pushed down\n * to SPARQL and must be evaluated in JS after hydration.\n *\n * JS-only filters include:\n * - Literal-stored properties (equality, comparison, contains, etc.)\n * - Reverse relations (belongsToOne / belongsToMany)\n * - author / timestamp filters (skipped by buildSPARQLWhereFilters)\n *\n * When JS-only filters exist, SPARQL-level LIMIT/OFFSET must NOT be applied\n * because the database would cap the candidate set before JS filters run,\n * potentially discarding matches beyond the LIMIT.\n */\nfunction hasJsOnlyWhereFilters(metadata, allRelationsMetadata, where) {\n if (!where)\n return false;\n for (const [propertyName, condition] of Object.entries(where)) {\n if (propertyName === \"base\" || propertyName === \"id\")\n continue;\n // author/timestamp filters are handled in JS\n if (propertyName === \"author\" || propertyName === \"timestamp\")\n return true;\n const propMeta = metadata.properties[propertyName];\n if (!propMeta)\n continue;\n // Reverse relations are JS-only\n const relMeta = allRelationsMetadata[propertyName];\n if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {\n return true;\n }\n // Literal-stored properties: equality/IN/NOT can be pushed to SPARQL via\n // <ad4m://fn/parse_literal>(), but comparison operators (gt/lt/gte/lte/between/contains)\n // must remain JS-only because parse_literal returns strings.\n if (isLiteralStoredProperty(propMeta)) {\n if (typeof condition === 'object' && condition !== null && !Array.isArray(condition)) {\n const ops = condition;\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps)\n return true;\n // NOT with simple value can be pushed to SPARQL \u2014 not JS-only\n }\n // Simple equality and IN filters can be pushed to SPARQL \u2014 not JS-only\n }\n }\n return false;\n}\n/**\n * Determine if a property stores values as literal: IRIs (needs parse_literal for comparisons).\n * Properties with resolveLanguage === \"literal\" AND properties without resolveLanguage\n * both store values as literal: URIs. Only properties with a non-literal resolveLanguage\n * (e.g. file storage) or flag properties store raw URIs.\n */\nfunction isLiteralStoredProperty(propMeta) {\n if (propMeta.flag)\n return false;\n // If resolveLanguage is set to something other than \"literal\", it's a language expression URI\n if (propMeta.resolveLanguage && propMeta.resolveLanguage !== \"literal\")\n return false;\n // Everything else (resolveLanguage === \"literal\" or undefined) stores as literal: URIs\n return true;\n}\n/**\n * Escape a string for use as a SPARQL string literal.\n */\nfunction escapeSPARQL(value) {\n return value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\")\n .replace(/\\0/g, \"\")\n .replace(/\\f/g, \"\\\\u000C\");\n}\n/**\n * Format a value as a SPARQL string literal (double-quoted).\n */\nfunction formatSPARQLValue(value) {\n if (typeof value === \"string\") {\n return `\"${escapeSPARQL(value)}\"`;\n }\n return `\"${String(value)}\"`;\n}\n/**\n * Format an AD4M URI as an RDF IRI for use in SPARQL triple patterns.\n * All AD4M link source/predicate/target values become IRIs in angle brackets.\n * The Rust SPARQL service transparently transforms these to valid IRI format.\n *\n * Rejects characters that would break or inject into a SPARQL IRI token,\n * matching the Rust-side `validate_iri()` function.\n */\nfunction iri(value) {\n if (/[<>{}\" ]/.test(value)) {\n throw new Error(`Invalid IRI component: '${value}'`);\n }\n return `<${value}>`;\n}\n/**\n * Map a user-facing property name to the SPARQL variable alias used in the query.\n *\n * Properties appear in the query as:\n * - Required properties: `?cfTarget_${name}`\n * - Where-clause joins: `?wTarget_${name}`\n * - Initial-value fallback: `?cfInitTarget_${name}`\n *\n * For ORDER BY, we prefer the conformance variable (always present for required props),\n * then the where-target variable.\n */\nfunction mapPropertyToSPARQLVar(propertyName, metadata) {\n const propMeta = metadata.properties[propertyName];\n if (propMeta) {\n if (propMeta.required && !propMeta.getter && !(propMeta.flag && propMeta.initial)) {\n return `?cfTarget_${propertyName}`;\n }\n if (propMeta.initial && !propMeta.flag) {\n return `?cfInitTarget_${propertyName}`;\n }\n }\n // Fallback: where-clause variable or raw name\n return `?wTarget_${propertyName}`;\n}\n/**\n * Build a SPARQL query that returns all links belonging to instances of\n * the given model class, optionally filtered by `where` conditions.\n *\n * Uses direct triple patterns: ?source ?predicate ?target\n * with named graph storage and metadata keyed by graph IRI.\n */\nfunction buildSPARQLQuery(metadata, allRelationsMetadata, query, modelClass) {\n const joinPatterns = [];\n const filterExpressions = [];\n // Parent filter \u2014 direct triple pattern\n if (query.parent) {\n const parentPredicate = resolveParentPredicate(query.parent, modelClass);\n joinPatterns.push(`\n ${iri(query.parent.id)} ${iri(parentPredicate)} ?source .`);\n }\n // Required property JOIN patterns \u2014 direct triple patterns\n let hasConformance = false;\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.required) {\n if (propMeta.getter)\n continue;\n hasConformance = true;\n if (propMeta.flag && propMeta.initial) {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);\n }\n else {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ?cfTarget_${propMeta.name} .`);\n }\n }\n }\n // Fallback: initial-value JOIN patterns\n if (!hasConformance) {\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.initial) {\n hasConformance = true;\n if (propMeta.flag) {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ${iri(propMeta.initial)} .`);\n }\n else {\n joinPatterns.push(`\n ?source ${iri(propMeta.predicate)} ?cfInitTarget_${propMeta.name} .`);\n }\n break;\n }\n }\n }\n // Fallback: open-world structural matching\n // Use a subquery with DISTINCT to avoid row multiplication when the main\n // ?source ?predicate ?target pattern cross-joins with multiple structural matches.\n if (!hasConformance && joinPatterns.length === 0) {\n const knownPredicates = [];\n for (const [, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.predicate) {\n knownPredicates.push(iri(propMeta.predicate));\n }\n }\n if (metadata.relations) {\n for (const [, relMeta] of Object.entries(metadata.relations)) {\n if (relMeta.predicate) {\n knownPredicates.push(iri(relMeta.predicate));\n }\n }\n }\n if (knownPredicates.length > 0) {\n joinPatterns.push(`\n { SELECT DISTINCT ?source WHERE { ?source ?cf_structPred ?cf_structTarget . FILTER(?cf_structPred IN (${knownPredicates.join(\", \")})) } }`);\n }\n }\n // Build WHERE clause filters from user query\n const { joins: userJoins, filters: userFilters } = buildSPARQLWhereFilters(metadata, allRelationsMetadata, query.where);\n joinPatterns.push(...userJoins);\n filterExpressions.push(...userFilters);\n // Main triple pattern \u2014 fetches all links for matched sources\n // Direct triple in default graph + RDF 1.2 reifier for link metadata\n // FILTER(isIRI(?source)) excludes non-IRI subjects\n const joinClause = joinPatterns.join(\"\\n\");\n const filterClause = filterExpressions.length > 0\n ? `FILTER(\\n ${filterExpressions.join(\" &&\\n \")}\\n )`\n : \"\";\n // Determine if SPARQL-level pagination is safe.\n // When JS-only where filters exist, we must NOT limit at the SPARQL level\n // because the database would cap candidates before JS filters run.\n const canPaginateInSPARQL = !hasJsOnlyWhereFilters(metadata, allRelationsMetadata, query.where)\n && (query.limit !== undefined || query.offset !== undefined);\n // Build a pagination subquery that constrains ?source to only the page\n // of interest. This avoids fetching all links for all matching instances.\n const paginationSubquery = canPaginateInSPARQL\n ? buildPaginationSubquery(joinPatterns, filterExpressions, metadata, query)\n : '';\n if (paginationSubquery) {\n // Use the pagination subquery to constrain ?source, then fetch all links\n // for those sources only.\n return `\n\n SELECT ?source ?predicate ?target ?author ?timestamp WHERE {\n ${paginationSubquery}${joinClause}\n ?source ?predicate ?target .\n ?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>> .\n FILTER(isIRI(?source) && isIRI(?predicate))\n ?_reifier <ad4m://ontology/author> ?author .\n ?_reifier <ad4m://ontology/timestamp> ?timestamp .\n ${filterClause}\n }\n `.trim();\n }\n return `\n\n SELECT ?source ?predicate ?target ?author ?timestamp WHERE {${joinClause}\n ?source ?predicate ?target .\n ?_reifier <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> <<( ?source ?predicate ?target )>> .\n FILTER(isIRI(?source) && isIRI(?predicate))\n ?_reifier <ad4m://ontology/author> ?author .\n ?_reifier <ad4m://ontology/timestamp> ?timestamp .\n ${filterClause}\n }\n `.trim();\n}\n/**\n * Build an inner subquery that selects DISTINCT ?source URIs with\n * ORDER BY, LIMIT, and OFFSET applied at the instance level.\n *\n * Because the outer SELECT returns multiple rows per instance (one per link),\n * we cannot apply LIMIT/OFFSET there. Instead this subquery constrains\n * ?source to only the instances on the requested page.\n *\n * @internal \u2014 used by buildSPARQLQuery when SPARQL-level pagination is safe.\n */\nfunction buildPaginationSubquery(joinPatterns, filterExpressions, metadata, query) {\n const innerJoin = joinPatterns.join('\\n');\n const innerFilter = filterExpressions.length > 0\n ? `FILTER(\\n ${filterExpressions.join(' &&\\n ')}\\n )`\n : '';\n // Build ORDER BY clause from query.order\n let orderByClause = '';\n const orderJoinPatterns = [];\n if (query.order) {\n const orderTerms = Object.entries(query.order).map(([prop, dir]) => {\n const sparqlVar = mapPropertyToSPARQLVar(prop, metadata);\n // Check if this order property's variable is already bound by existing\n // join patterns. If not, add an OPTIONAL join so ORDER BY is deterministic.\n const varAlreadyBound = innerJoin.includes(sparqlVar);\n if (!varAlreadyBound) {\n const propMeta = metadata.properties[prop];\n if (propMeta && propMeta.predicate && !propMeta.getter) {\n orderJoinPatterns.push(`\\n OPTIONAL { ?source <${propMeta.predicate}> ${sparqlVar} . }`);\n }\n }\n return dir === 'DESC' ? `DESC(${sparqlVar})` : `ASC(${sparqlVar})`;\n });\n if (orderTerms.length > 0) {\n orderByClause = `ORDER BY ${orderTerms.join(' ')}`;\n }\n }\n // No default ordering \u2014 when no explicit order is specified, results come in\n // natural (insertion) order.\n const tsSelect = '';\n const tsPattern = '';\n const limitClause = query.limit !== undefined ? `LIMIT ${query.limit}` : '';\n const offsetClause = query.offset !== undefined && query.offset > 0 ? `OFFSET ${query.offset}` : '';\n return `\n { SELECT DISTINCT ?source${tsSelect} WHERE {${innerJoin}${orderJoinPatterns.join('')}${tsPattern}\n FILTER(isIRI(?source))\n ${innerFilter}\n } ${orderByClause} ${limitClause} ${offsetClause} }\\n`;\n}\n/**\n * Build SPARQL FILTER expressions from user `where` conditions.\n * Uses direct triple patterns instead of link-node reification.\n */\nfunction buildSPARQLWhereFilters(metadata, _allRelationsMetadata, where) {\n if (!where)\n return { joins: [], filters: [] };\n const joins = [];\n const filters = [];\n for (const [propertyName, condition] of Object.entries(where)) {\n // 'base' maps to ?source\n if (propertyName === \"base\" || propertyName === \"id\") {\n if (Array.isArray(condition)) {\n const formatted = condition.map(v => iri(v)).join(\", \");\n filters.push(`?source IN (${formatted})`);\n }\n else if (typeof condition === \"object\" && condition !== null) {\n const ops = condition;\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map(v => iri(v)).join(\", \");\n filters.push(`!(?source IN (${formatted}))`);\n }\n else {\n filters.push(`?source != ${iri(ops.not)}`);\n }\n }\n }\n else {\n filters.push(`?source = ${iri(String(condition))}`);\n }\n continue;\n }\n if (propertyName === \"author\" || propertyName === \"timestamp\") {\n continue;\n }\n const propMeta = metadata.properties[propertyName];\n if (!propMeta)\n continue;\n // Skip reverse relations (belongsToOne / belongsToMany) \u2014 these are registered as\n // read-only properties but the link direction is reversed (target\u2192source, not source\u2192target).\n // Adding a forward join pattern would match nothing. These are filtered in JS post-filter.\n const relMeta = _allRelationsMetadata[propertyName];\n if (relMeta && (relMeta.kind === 'belongsToOne' || relMeta.kind === 'belongsToMany')) {\n continue;\n }\n // Determine if this property stores values as literal: IRIs\n const useParseLiteral = isLiteralStoredProperty(propMeta);\n // For literal-stored properties, push equality/IN/NOT filters to SPARQL using\n // <ad4m://fn/parse_literal>() which extracts the raw value from literal: IRIs.\n // The correct SPARQL syntax is <ad4m://fn/parse_literal>(?var) \u2014 NOT fn::parse_literal\n // (which was SurrealDB syntax that Oxigraph rejects at parse time).\n // Comparison operators (gt/lt/gte/lte/between/contains) remain JS-only because\n // parse_literal returns strings and numeric/date comparisons would be unreliable.\n // JS post-filter in instancesFromQueryResult remains as a safety net for all cases.\n if (useParseLiteral) {\n if (typeof condition === \"object\" && condition !== null && !Array.isArray(condition)) {\n const ops = condition;\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps) {\n // Comparison operators: join only, filter in JS\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);\n }\n if (ops.not !== undefined) {\n // NOT filter: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map((v) => formatSPARQLValue(v)).join(\", \");\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) NOT IN (${formatted})`);\n }\n else {\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) != ${formatSPARQLValue(ops.not)}`);\n }\n }\n }\n else if (Array.isArray(condition)) {\n // IN filter: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n const formatted = condition.map((v) => formatSPARQLValue(v)).join(\", \");\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) IN (${formatted})`);\n }\n else {\n // Simple equality: push down to SPARQL\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n filters.push(`STR(<ad4m://fn/parse_literal>(?wTarget_${propertyName})) = ${formatSPARQLValue(condition)}`);\n }\n }\n else if (Array.isArray(condition)) {\n const formatted = condition.map(v => iri(v)).join(\", \");\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_${propertyName} .`);\n filters.push(`?wTarget_${propertyName} IN (${formatted})`);\n }\n else if (typeof condition === \"object\" && condition !== null) {\n const ops = condition;\n if (ops.not !== undefined) {\n if (Array.isArray(ops.not)) {\n const formatted = ops.not.map(v => iri(v)).join(\", \");\n filters.push(`\n NOT EXISTS {\n ?source ${iri(propMeta.predicate)} ?wTarget_not_${propertyName} .\n FILTER(?wTarget_not_${propertyName} IN (${formatted}))\n }\n `);\n }\n else {\n filters.push(`\n NOT EXISTS {\n ?source ${iri(propMeta.predicate)} ${iri(ops.not)} .\n }\n `);\n }\n }\n const hasCompOps = ops.gt !== undefined || ops.gte !== undefined ||\n ops.lt !== undefined || ops.lte !== undefined ||\n ops.between !== undefined || ops.contains !== undefined;\n if (hasCompOps) {\n joins.push(`\n ?source ${iri(propMeta.predicate)} ?wTarget_cmp_${propertyName} .`);\n }\n }\n else {\n // Simple equality \u2014 non-literal property, use exact IRI match\n joins.push(`\n ?source ${iri(propMeta.predicate)} ${iri(String(condition))} .`);\n }\n }\n return { joins, filters };\n}\n\n/**\n * ModelQueryBuilder \u2014 fluent query builder for Ad4mModel.\n *\n * Allows building queries with a chainable interface and either\n * running them once or subscribing to real-time updates.\n */\n/** Query builder for Ad4mModel queries.\n * Allows building queries with a fluent interface and either running them once\n * or subscribing to updates.\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .order({ rating: \"DESC\" })\n * .limit(10);\n *\n * // Run once\n * const recipes = await builder.run();\n *\n * // Or subscribe to updates\n * await builder.subscribe(recipes => {\n * console.log(\"Updated recipes:\", recipes);\n * });\n * ```\n */\nclass ModelQueryBuilder {\n constructor(perspective, ctor, query) {\n this.queryParams = {};\n this.modelClassName = null;\n this.perspective = perspective;\n this.ctor = ctor;\n if (query)\n this.queryParams = query;\n }\n /**\n * Disposes of the current subscription if one exists.\n *\n * This method:\n * 1. Stops the keepalive signals to the subscription\n * 2. Unsubscribes from subscription updates\n * 3. Notifies the backend to clean up subscription resources\n * 4. Clears the subscription reference\n *\n * You should call this method when you're done with a subscription\n * to prevent memory leaks and ensure proper cleanup.\n */\n dispose() {\n if (this.currentSubscription) {\n this.currentSubscription.dispose();\n this.currentSubscription = undefined;\n }\n }\n /**\n * Adds where conditions to the query.\n *\n * @param conditions - The conditions to filter by\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .where({\n * category: \"Dessert\",\n * rating: { gt: 4 },\n * tags: [\"vegan\", \"quick\"],\n * published: true\n * })\n * ```\n */\n where(conditions) {\n this.queryParams.where = conditions;\n return this;\n }\n /**\n * Sets the order for the query results.\n *\n * @param orderBy - The ordering criteria\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .order({ createdAt: \"DESC\" })\n * ```\n */\n order(orderBy) {\n this.queryParams.order = orderBy;\n return this;\n }\n /**\n * Sets the maximum number of results to return.\n *\n * @param limit - Maximum number of results\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .limit(10)\n * ```\n */\n limit(limit) {\n this.queryParams.limit = limit;\n return this;\n }\n /**\n * Sets the number of results to skip.\n *\n * @param offset - Number of results to skip\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .offset(20) // Skip first 20 results\n * ```\n */\n offset(offset) {\n this.queryParams.offset = offset;\n return this;\n }\n /**\n * Scopes the query to instances linked from a parent.\n *\n * The predicate is resolved in order of precedence:\n * 1. **Instance only** \u2014 the parent's constructor is used as the model\n * class; its relation metadata is scanned for a relation whose\n * `target()` matches the queried model class.\n * 2. **Instance + options with `field`** \u2014 direct field-name lookup on\n * the parent model's relation metadata (disambiguates when a parent\n * has multiple relations targeting the same child class).\n * 3. **String id + model class** \u2014 same metadata scan (or field lookup if\n * options include `field`).\n * 4. **String id + string predicate** \u2014 raw escape hatch, no metadata lookup.\n *\n * Passing a plain string id with no second argument throws because the\n * predicate cannot be resolved without a model class.\n *\n * @param idOrInstance - The parent's expression URI **or** an Ad4mModel instance\n * @param modelOrPredicate - A model class (predicate auto-resolved) **or** a raw predicate string\n * @param options - Optional settings: `field` for direct relation-name lookup\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * // Instance \u2014 predicate auto-resolved from Cookbook's @HasMany(() => Recipe)\n * Recipe.query(perspective).parent(cookbook).get();\n *\n * // Instance + field \u2014 disambiguate when parent has multiple relations to same child\n * Recipe.query(perspective).parent(cookbook, { field: \"recipes\" }).get();\n *\n * // String id + model class\n * Recipe.query(perspective).parent(cookbookId, Cookbook).get();\n *\n * // String id + model class + field\n * Recipe.query(perspective).parent(cookbookId, Cookbook, { field: \"recipes\" }).get();\n *\n * // String id + raw predicate (escape hatch)\n * Recipe.query(perspective).parent(cookbookId, \"cookbook://recipe\").get();\n * ```\n */\n parent(idOrInstance, modelOrPredicate, options) {\n const id = typeof idOrInstance === 'string' ? idOrInstance : idOrInstance.id;\n // Handle options-object as second arg: parent(instance, { field: \"recipes\" })\n if (typeof modelOrPredicate === 'object' && modelOrPredicate !== null && !('prototype' in modelOrPredicate)) {\n if (typeof idOrInstance === 'string') {\n throw new Error('parent() called with a string id and options object requires a model class as second argument');\n }\n const model = idOrInstance.constructor;\n this.queryParams.parent = { id, model, field: modelOrPredicate.field };\n return this;\n }\n const field = options?.field;\n if (typeof modelOrPredicate === 'string') {\n // Raw predicate string \u2192 raw form of ParentScope\n this.queryParams.parent = { id, predicate: modelOrPredicate };\n }\n else if (typeof modelOrPredicate === 'function') {\n // Model class \u2192 model form of ParentScope\n this.queryParams.parent = { id, model: modelOrPredicate, ...(field && { field }) };\n }\n else if (typeof idOrInstance !== 'string') {\n // Ad4mModel instance \u2014 derive model class from constructor\n this.queryParams.parent = { id, model: idOrInstance.constructor, ...(field && { field }) };\n }\n else {\n throw new Error('parent() called with a string id requires a second argument: either a model class or a predicate string');\n }\n return this;\n }\n /**\n * Specifies which properties to include in the results.\n *\n * @param properties - Array of property names to include\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * .properties([\"name\", \"description\", \"rating\"])\n * ```\n */\n properties(properties) {\n this.queryParams.properties = properties;\n return this;\n }\n /**\n * Controls whether SPARQL property getters are evaluated during hydration.\n *\n * By default, collection queries evaluate property getters (deepQuery=true).\n * Call `.deepQuery(false)` to skip getter evaluation for performance.\n *\n * @param enabled - Whether to evaluate property getters (default: true)\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * const messages = await Message.query(perspective)\n * .parent(channel)\n * .deepQuery(false) // skip property getters for performance\n * .limit(30)\n * .get();\n * ```\n */\n deepQuery(enabled = true) {\n this.queryParams.deepQuery = enabled;\n return this;\n }\n /**\n * Specifies which relations to eager-load (hydrate into model instances).\n *\n * Without `include`, relation fields contain raw expression URIs (strings).\n * With `include`, the URIs are resolved into fully-hydrated model instances\n * using the `target` class declared in the relation decorator.\n *\n * Supports nested includes for multi-level eager loading.\n *\n * @param map - An IncludeMap describing which relations to hydrate\n * @returns The query builder for chaining\n *\n * @example\n * ```typescript\n * // Hydrate comments one level deep\n * const recipes = await Recipe.query(perspective)\n * .include({ comments: true })\n * .run();\n * // recipe.comments is now Comment[] (model instances), not string[]\n *\n * // Nested: hydrate comments AND each comment's author\n * const recipes = await Recipe.query(perspective)\n * .include({ comments: { author: true } })\n * .run();\n * ```\n */\n include(map) {\n this.queryParams.include = map;\n return this;\n }\n overrideModelClassName(className) {\n this.modelClassName = className;\n return this;\n }\n /**\n * Sets the query engine to use.\n * @deprecated Prolog engine has been removed. All queries use SPARQL/Rust.\n */\n engine(_eng) {\n return this;\n }\n /**\n * Executes the query once and returns the results.\n *\n * @returns Array of matching entities\n *\n * @example\n * ```typescript\n * const recipes = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .get();\n * ```\n */\n async get() {\n return await this.executeSparqlQuery();\n }\n /**\n * Executes the query once using SPARQL and returns the results.\n */\n async getSparql() {\n return this.executeSparqlQuery();\n }\n /**\n * Shared query execution logic \u2014 routes through the executor-side modelQuery endpoint.\n */\n async executeSparqlQuery() {\n const { results } = await this.ctor.executeModelQuery(this.perspective, this.queryParams, this.modelClassName);\n return results;\n }\n /**\n * Returns the first matching instance, or `null` if none match.\n *\n * Internally sets `limit: 1` and delegates to `get()`.\n *\n * @returns The first matching instance, or `null`\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.query(perspective)\n * .where({ name: \"Pasta\" })\n * .first();\n * ```\n */\n async first() {\n const savedLimit = this.queryParams.limit;\n this.queryParams.limit = 1;\n const results = await this.get();\n this.queryParams.limit = savedLimit;\n return results[0] ?? null;\n }\n /**\n * Subscribes to the query and receives updates when results change.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription (default)\n * 2. Sets up the callback to process future updates\n * 3. Returns the initial results immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param callback - Function to call with updated results\n * @returns Initial results array\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ status: \"cooking\" });\n *\n * const initialRecipes = await builder.subscribe(recipes => {\n * console.log(\"Updated recipes:\", recipes);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async subscribe(callback) {\n // Clean up any existing subscription\n this.dispose();\n const ctor = this.ctor;\n // Build the model query params (className, queryJson, shapeJson)\n const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(this.queryParams, this.modelClassName);\n // Register model subscription via Rust \u2014 this builds trigger SPARQL internally,\n // registers the subscription, and runs the initial query in one call.\n const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n // Convert JSON instances to model class instances\n const parseResults = (raw) => {\n return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);\n };\n // Resolve non-literal (file-language) properties \u2014 handles both raw URI strings\n // and already-resolved FileData objects returned by the Rust executor.\n const resolveAndReturn = async (instances) => {\n await ctor.resolveNonLiteralProps(this.perspective, instances);\n return instances;\n };\n // Parse initial results (with non-literal resolution)\n const initialResults = await resolveAndReturn(parseResults(initialModelResult));\n // Track last emitted result fingerprint to suppress duplicate callbacks\n let lastResultFingerprint = null;\n const buildFingerprint = (results) => {\n if (results.length === 0)\n return '0:';\n return JSON.stringify(results, (_, v) => typeof v === 'function' ? undefined : v);\n };\n lastResultFingerprint = buildFingerprint(initialResults);\n // Listen for subscription updates via the same GraphQL subscription channel.\n // When Rust re-runs the model query and finds changed results, it pushes them.\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n try {\n const parsed = parseResults(rawResult);\n console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${parsed.length} instances`);\n resolveAndReturn(parsed).then((results) => {\n const fp = buildFingerprint(results);\n if (fp === lastResultFingerprint) {\n console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);\n return;\n }\n console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);\n lastResultFingerprint = fp;\n callback(results);\n }).catch((e) => {\n console.error('Model subscription update resolve error:', e);\n });\n }\n catch (e) {\n console.error('Model subscription update parse error:', e);\n }\n });\n // Set up keepalive with recovery \u2014 uses setTimeout loop so we can\n // break out and resubscribe when the server evicts the subscription.\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0; // Reset on success\n }\n catch (e) {\n console.warn(`Model subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.subscribe(callback);\n }\n catch (resubErr) {\n console.error('Model subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Model subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return; // new subscription owns its own keepalive loop\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n // Store dispose function\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n // Take snapshots for dirty tracking\n for (const inst of initialResults) {\n inst.takeSnapshot?.(this.queryParams.include);\n }\n return initialResults;\n }\n /**\n * Subscribes to the query and receives updates using SPARQL.\n * @deprecated Use subscribe() instead \u2014 now routes through Rust model subscription.\n */\n async subscribeSparql(callback) {\n return this.subscribe(callback);\n }\n /**\n * Gets the total count of matching entities.\n *\n * @returns Total count\n *\n * @example\n * ```typescript\n * const totalDesserts = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .count();\n * ```\n */\n async count() {\n const { totalCount } = await this.ctor.executeModelQuery(this.perspective, { ...this.queryParams, limit: 0 }, this.modelClassName);\n return totalCount;\n }\n /**\n * Gets the total count of matching entities using SPARQL.\n * Delegates to count().\n */\n async countSparql() {\n return await this.count();\n }\n /**\n * Subscribes to count updates for matching entities.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription for the count (default)\n * 2. Sets up the callback to process future count updates\n * 3. Returns the initial count immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param callback - Function to call with updated count\n * @returns Initial count\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ status: \"active\" });\n *\n * const initialCount = await builder.countSubscribe(count => {\n * console.log(\"Active items:\", count);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async countSubscribe(callback) {\n // Clean up any existing subscription\n this.dispose();\n const countParams = { ...this.queryParams, limit: 0 };\n const { className, queryJson, shapeJson } = this.ctor.prepareModelQueryParams(countParams, this.modelClassName);\n const { subscriptionId, result: initialModelResult } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n const parseCount = (raw) => {\n const data = typeof raw === 'string' ? JSON.parse(raw) : raw;\n return data.totalCount ?? 0;\n };\n const initialCount = parseCount(initialModelResult);\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n try {\n callback(parseCount(rawResult));\n }\n catch (e) {\n console.error('Count subscription update parse error:', e);\n }\n });\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0;\n }\n catch (e) {\n console.warn(`Count subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Count resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.countSubscribe(callback);\n }\n catch (resubErr) {\n console.error('Count subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Count subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return;\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n return initialCount;\n }\n /**\n * Subscribes to count updates using SPARQL.\n * @deprecated Use countSubscribe() instead \u2014 now routes through Rust model subscription.\n */\n async countSubscribeSparql(callback) {\n return this.countSubscribe(callback);\n }\n /**\n * Gets a page of results with pagination metadata.\n *\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @returns Paginated results with metadata\n *\n * @example\n * ```typescript\n * const page = await Recipe.query(perspective)\n * .where({ category: \"Main\" })\n * .paginate(10, 1);\n * console.log(`Page ${page.pageNumber}, ${page.results.length} of ${page.totalCount}`);\n * ```\n */\n async paginate(pageSize, pageNumber) {\n const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };\n const { results, totalCount } = await this.ctor.executeModelQuery(this.perspective, paginationQuery, this.modelClassName);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Gets a page of results using SPARQL.\n * Delegates to paginate().\n */\n async paginateSparql(pageSize, pageNumber) {\n return await this.paginate(pageSize, pageNumber);\n }\n /**\n * Subscribes to paginated results updates.\n *\n * This method:\n * 1. Creates and initializes a SPARQL live query subscription for the paginated results (default)\n * 2. Sets up the callback to process future page updates\n * 3. Returns the initial page immediately\n *\n * Remember to call dispose() when you're done with the subscription\n * to clean up resources.\n *\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @param callback - Function to call with updated pagination results\n * @returns Initial pagination results\n *\n * @example\n * ```typescript\n * const builder = Recipe.query(perspective)\n * .where({ category: \"Main\" });\n *\n * const initialPage = await builder.paginateSubscribe(10, 1, page => {\n * console.log(\"Updated page:\", page.results);\n * });\n *\n * // When done with subscription:\n * builder.dispose();\n * ```\n *\n */\n async paginateSubscribe(pageSize, pageNumber, callback) {\n // Clean up any existing subscription\n this.dispose();\n const ctor = this.ctor;\n // Subscribe to the full result set (no limit/offset) so the subscription\n // detects changes anywhere in the dataset. Rust builds trigger SPARQL\n // from the shape predicates.\n const subscriptionParams = { ...(this.queryParams || {}) };\n delete subscriptionParams.limit;\n delete subscriptionParams.offset;\n const { className, queryJson, shapeJson } = ctor.prepareModelQueryParams(subscriptionParams, this.modelClassName);\n const { subscriptionId } = await this.perspective.modelSubscribe(className, queryJson, shapeJson);\n // Build the paginated query for Rust endpoint (count: true fetches both results and totalCount in one call)\n const paginatedQuery = {\n ...(this.queryParams || {}),\n limit: pageSize,\n offset: pageSize * (pageNumber - 1),\n count: true,\n };\n const processResults = async () => {\n const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);\n callback({ results, totalCount, pageSize, pageNumber });\n };\n const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {\n console.debug(`[ModelQueryBuilder.paginateSubscribe] Update received for ${subscriptionId}, re-fetching paginated data...`);\n processResults().catch(e => console.error('Paginate subscription error:', e));\n });\n let disposed = false;\n let keepaliveTimer;\n let resubscribeAttempts = 0;\n const MAX_RESUBSCRIBE_ATTEMPTS = 5;\n const keepaliveLoop = async () => {\n if (disposed)\n return;\n try {\n await this.perspective.client.keepAliveQuery(this.perspective.uuid, subscriptionId);\n resubscribeAttempts = 0;\n }\n catch (e) {\n console.warn(`Paginate subscription keepalive failed for ${subscriptionId}:`, e);\n if (!disposed && resubscribeAttempts < MAX_RESUBSCRIBE_ATTEMPTS) {\n resubscribeAttempts++;\n const backoffMs = Math.min(1000 * Math.pow(2, resubscribeAttempts), 60000);\n console.warn(`Paginate resubscribing (attempt ${resubscribeAttempts}/${MAX_RESUBSCRIBE_ATTEMPTS}, backoff ${backoffMs}ms)...`);\n await new Promise(r => setTimeout(r, backoffMs));\n try {\n unsubscribe();\n await this.paginateSubscribe(pageSize, pageNumber, callback);\n }\n catch (resubErr) {\n console.error('Paginate subscription resubscribe failed:', resubErr);\n }\n }\n else if (resubscribeAttempts >= MAX_RESUBSCRIBE_ATTEMPTS) {\n console.error(`Paginate subscription ${subscriptionId}: max resubscribe attempts reached, giving up.`);\n }\n return;\n }\n if (!disposed) {\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n }\n };\n keepaliveTimer = setTimeout(keepaliveLoop, 30000);\n this.currentSubscription = {\n dispose: () => {\n disposed = true;\n if (keepaliveTimer)\n clearTimeout(keepaliveTimer);\n unsubscribe();\n this.perspective.client.disposeQuerySubscription(this.perspective.uuid, subscriptionId).catch(() => { });\n },\n };\n // Initial fetch (single call with count: true)\n const { results, totalCount } = await ctor.executeModelQuery(this.perspective, paginatedQuery, this.modelClassName);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Subscribes to paginated results updates using SPARQL.\n * Delegates to paginateSubscribe().\n */\n async paginateSubscribeSparql(pageSize, pageNumber, callback) {\n return await this.paginateSubscribe(pageSize, pageNumber, callback);\n }\n}\n\n/**\n * hydration.ts \u2014 Instance hydration helpers extracted from Ad4mModel.\n *\n * After the Rust model_query pipeline migration, most hydration logic moved\n * to Rust. This file retains:\n * - normalizeValue() \u2014 snapshot dirty-tracking\n */\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Pure helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n/**\n * Normalize a value for snapshot storage.\n * Arrays of model instances are reduced to their `.id` strings so that\n * dirty-tracking compares stable identifiers instead of object references.\n */\nfunction normalizeValue(value) {\n if (Array.isArray(value)) {\n return value.map((v) => v && typeof v === 'object' && typeof v.id === 'string' ? v.id : v);\n }\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// Default decoder for file-storage (non-literal resolveLanguage) properties\n// ---------------------------------------------------------------------------\n/**\n * When the Rust executor resolves a non-literal expression it may return a\n * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a\n * raw URI string. If the model class has no custom `transform` registered\n * (e.g. it was synthesised from a SHACL shape at runtime) we still want to\n * decode the content rather than passing raw `FileData` to callers.\n *\n * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):\n * - `application/json` (default when `file_type` is absent) \u2192 JSON.parse\n * - anything else \u2192 raw decoded string\n *\n * If `resolved` is not a `FileData` object the value is returned unchanged so\n * that callers can use this as a safe unconditional fallback.\n */\nfunction defaultFileDecode(resolved) {\n if (resolved !== null &&\n typeof resolved === 'object' &&\n 'data_base64' in resolved) {\n const fd = resolved;\n let raw;\n try {\n raw = atob(fd.data_base64);\n }\n catch {\n return resolved; // malformed base64 \u2014 keep as-is\n }\n const isJson = !fd.file_type || fd.file_type === 'application/json';\n if (isJson) {\n try {\n return JSON.parse(raw);\n }\n catch {\n return raw;\n }\n }\n return raw;\n }\n return resolved;\n}\n// ---------------------------------------------------------------------------\n// Helpers for Rust-side include resolution\n// ---------------------------------------------------------------------------\n/**\n * Recursively enrich relation metadata in the shape with target class shapes\n * so the Rust endpoint can resolve includes in-process (no extra GraphQL\n * round-trips per relation).\n */\nfunction enrichShapeForIncludes(metadata, include, allRelMeta) {\n for (const [relName, includeVal] of Object.entries(include)) {\n if (!includeVal)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n const TargetClass = meta.target();\n // Deep-copy so we don't mutate the cached metadata\n const targetMeta = JSON.parse(JSON.stringify(TargetClass.getModelMetadata()));\n // Ensure the relation is in metadata.relations (fallback for edge cases)\n if (!metadata.relations[relName]) {\n metadata.relations[relName] = {\n name: relName,\n predicate: meta.predicate,\n direction: meta.kind === 'belongsToMany' || meta.kind === 'belongsToOne'\n ? 'reverse'\n : 'forward',\n };\n }\n const rel = metadata.relations[relName];\n rel.kind = meta.kind;\n rel.maxCount = meta.maxCount;\n rel.targetShape = targetMeta;\n rel.targetClassName = targetMeta.className;\n // Recurse for nested includes\n const nested = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.include\n : undefined;\n if (nested) {\n const targetRelMeta = getRelationsMetadata(TargetClass);\n enrichShapeForIncludes(targetMeta, nested, targetRelMeta);\n }\n }\n}\n/**\n * Construct a model class instance from a plain JSON object returned by the\n * Rust endpoint. Recursively converts included relation values (which come\n * back as plain JSON objects) into proper model class instances.\n */\nfunction jsonToModelInstance(ModelClass, perspective, json, include, properties) {\n const instance = new ModelClass(perspective, json.id || json.baseExpression);\n // When a properties projection is active, remove own properties set by the\n // constructor that are not in the projected JSON. This ensures assertions\n // like `expect(r).to.not.have.own.property(\"body\")` pass.\n if (properties) {\n const jsonKeys = new Set(Object.keys(json));\n for (const key of Object.getOwnPropertyNames(instance)) {\n // Keep internal fields (backing store for getters), id, baseExpression, perspective\n if (key === 'id' || key === 'baseExpression' || key === 'perspective' || key.startsWith('_'))\n continue;\n if (!jsonKeys.has(key)) {\n delete instance[key];\n }\n }\n }\n for (const [key, value] of Object.entries(json)) {\n if (key === 'baseExpression' || key === 'id')\n continue;\n // Skip getter-only properties anywhere in the prototype chain\n let isReadonly = false;\n let proto = Object.getPrototypeOf(instance);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, key);\n if (desc) {\n isReadonly = !!(desc.get && !desc.set);\n break;\n }\n proto = Object.getPrototypeOf(proto);\n }\n if (isReadonly)\n continue;\n // Parse ISO timestamps to epoch milliseconds (matches hydrateFromLinks behaviour)\n if ((key === 'createdAt' || key === 'updatedAt') && typeof value === 'string' && value.includes('T')) {\n instance[key] = new Date(value).getTime();\n continue;\n }\n instance[key] = value;\n }\n // Apply property transform functions from decorators (only for literal-resolved\n // or no-resolveLanguage properties; non-literal properties are resolved + transformed\n // asynchronously in executeModelQuery).\n try {\n const propsMeta = getPropertiesMetadata(ModelClass);\n for (const [propName, opts] of Object.entries(propsMeta)) {\n const o = opts;\n if (typeof o.transform !== 'function' || !(propName in json))\n continue;\n // Skip non-literal resolveLanguage props \u2014 they need async expression resolution first\n if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')\n continue;\n instance[propName] = o.transform(instance[propName]);\n }\n }\n catch (e) {\n console.debug('jsonToModelInstance: transform metadata unavailable:', e);\n }\n // Recursively convert included relation values to class instances\n if (include) {\n const relMeta = getRelationsMetadata(ModelClass);\n for (const [relName, includeVal] of Object.entries(include)) {\n if (!includeVal)\n continue;\n const meta = relMeta[relName];\n if (!meta?.target)\n continue;\n const TargetClass = meta.target();\n const nestedInclude = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.include\n : undefined;\n const nestedProperties = typeof includeVal === 'object' && includeVal !== null\n ? includeVal.properties\n : undefined;\n const raw = instance[relName];\n if (Array.isArray(raw)) {\n instance[relName] = raw.map((item) => {\n if (typeof item === 'object' && item !== null && item.id) {\n return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);\n }\n return item;\n });\n }\n else if (typeof raw === 'object' && raw !== null && raw.id) {\n instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);\n }\n }\n }\n return instance;\n}\n/**\n * Base class for defining data models in AD4M.\n *\n * @description\n * Ad4mModel provides the foundation for creating data models that are stored in AD4M perspectives.\n * Each model instance is represented as a subgraph in the perspective, with properties and relations\n * mapped to links in that graph. The class uses Prolog-based queries to efficiently search and filter\n * instances based on their properties and relationships.\n *\n * Key concepts:\n * - Each model instance has a unique base expression that serves as its identifier\n * - Properties are stored as links with predicates defined by the `through` option\n * - Relations represent one-to-many relationships as sets of links\n * - Queries are translated to Prolog for efficient graph pattern matching\n * - Changes are tracked through the perspective's subscription system\n *\n * @example\n * ```typescript\n * // Define a recipe model\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * // Required property with literal value\n * @Property({\n * through: \"recipe://name\",\n * resolveLanguage: \"literal\"\n * })\n * name: string = \"\";\n *\n * // Optional property with custom initial value\n * @Optional({\n * through: \"recipe://status\",\n * initial: \"recipe://draft\"\n * })\n * status: string = \"\";\n *\n * // Read-only computed property\n * @ReadOnly({\n * through: \"recipe://rating\",\n * getter: `\n * findall(Rating, triple(Base, \"recipe://user_rating\", Rating), Ratings),\n * sum_list(Ratings, Sum),\n * length(Ratings, Count),\n * Value is Sum / Count\n * `\n * })\n * averageRating: number = 0;\n *\n * // Relation of ingredients\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n *\n * // Relation of comments linked to another model\n * @HasMany(() => Comment, { through: \"recipe://comment\" })\n * comments: Comment[] = [];\n * }\n *\n * // Create and save a new recipe\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Chocolate Cake\";\n * recipe.ingredients = [\"flour\", \"sugar\", \"cocoa\"];\n * await recipe.save();\n *\n * // Query recipes in different ways\n * // Get all recipes\n * const allRecipes = await Recipe.findAll(perspective);\n *\n * // Find recipes with specific criteria\n * const desserts = await Recipe.findAll(perspective, {\n * where: {\n * status: \"recipe://published\",\n * averageRating: { gt: 4 }\n * },\n * order: { name: \"ASC\" },\n * limit: 10\n * });\n *\n * // Use the fluent query builder\n * const popularRecipes = await Recipe.query(perspective)\n * .where({ averageRating: { gt: 4.5 } })\n * .order({ averageRating: \"DESC\" })\n * .limit(5)\n * .get();\n *\n * // Subscribe to real-time updates\n * await Recipe.query(perspective)\n * .where({ status: \"recipe://cooking\" })\n * .subscribe(recipes => {\n * console.log(\"Currently being cooked:\", recipes);\n * });\n *\n * // Paginate results\n * const { results, totalCount, pageNumber } = await Recipe.query(perspective)\n * .where({ status: \"recipe://published\" })\n * .paginate(10, 1);\n * ```\n */\nclass Ad4mModel {\n /**\n * Backwards compatibility alias for createdAt.\n * @deprecated Use createdAt instead. This will be removed in a future version.\n */\n get timestamp() {\n return this.createdAt;\n }\n /**\n * Generates the SDNA (Subject DNA) Prolog rules for this model class.\n * Injected at class-definition time by the `@Model` decorator.\n * Returns a default value on un-decorated base classes.\n */\n static generateSDNA() {\n return { sdna: '', name: '' };\n }\n /**\n * Generates the SHACL shape graph for this model class.\n * Injected at class-definition time by the `@Model` decorator.\n * Returns `{ shape: null, name: '' }` on un-decorated base classes \u2014\n * the decorator's `parentSHACL?.shape?.nodeShapeUri` check handles this.\n */\n static generateSHACL() {\n return { shape: null, name: '' };\n }\n static async getClassName(perspective) {\n // Check if this is the Ad4mModel class itself or a subclass\n const isBaseClass = this === Ad4mModel;\n // For the base Ad4mModel class, we can't use the cache\n if (isBaseClass) {\n return await perspective.stringOrTemplateObjectToSubjectClassName(this);\n }\n // Get or create the cache for this class\n let classCache = this.classNamesByClass.get(this);\n if (!classCache) {\n classCache = {};\n this.classNamesByClass.set(this, classCache);\n }\n // Get or create the cached name for this perspective\n const perspectiveID = perspective.uuid;\n if (!classCache[perspectiveID]) {\n classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);\n }\n return classCache[perspectiveID];\n }\n /**\n * Extracts metadata from decorators for query building.\n *\n * @description\n * This method reads the metadata stored by decorators (@Property, @HasMany, etc.)\n * and returns it in a structured format that's easier to work with for query builders\n * and other systems that need to introspect model structure.\n *\n * The metadata includes:\n * - Class name from @Model\n * - Property metadata (predicates, types, constraints, etc.)\n * - Relation metadata (predicates, filters, etc.)\n *\n * For models created via `fromJSONSchema()`, this method will derive metadata from\n * the WeakMap registries that were populated during the dynamic class creation.\n * If these structures are empty but a JSON schema was attached to the class,\n * it can fall back to deriving metadata from that schema.\n *\n * @returns Structured metadata object containing className, properties, and relations\n * @throws Error if the class doesn't have @Model decorator\n *\n * @example\n * ```typescript\n * @Model({ name: \"Recipe\" })\n * class Recipe extends Ad4mModel {\n * @Property({ through: \"recipe://name\", resolveLanguage: \"literal\" })\n * name: string = \"\";\n *\n * @HasMany({ through: \"recipe://ingredient\" })\n * ingredients: string[] = [];\n * }\n *\n * const metadata = Recipe.getModelMetadata();\n * console.log(metadata.className); // \"Recipe\"\n * console.log(metadata.properties.name.predicate); // \"recipe://name\"\n * console.log(metadata.relations.ingredients.predicate); // \"recipe://ingredient\"\n * ```\n */\n static getModelMetadata() {\n // Access the prototype with any type to access decorator-added properties\n const prototype = this.prototype;\n // Validate that the class has @Model decorator\n // The decorator sets prototype.className, so we check for its existence\n if (!prototype.className || prototype.className === 'Ad4mModel') {\n throw new Error(\"Model class must be decorated with @Model\");\n }\n // Extract className\n const className = prototype.className;\n // Extract properties from WeakMap registry\n const propertiesMetadata = {};\n const prototypeProperties = getPropertiesMetadata(this);\n for (const [propertyName, opts] of Object.entries(prototypeProperties)) {\n const options = opts;\n propertiesMetadata[propertyName] = {\n name: propertyName,\n predicate: options.through || \"\",\n required: options.required || false,\n readOnly: !(options.writable ?? false),\n ...(options.initial !== undefined && { initial: options.initial }),\n ...(options.resolveLanguage !== undefined && { resolveLanguage: options.resolveLanguage }),\n ...(options.prologGetter !== undefined && { prologGetter: options.prologGetter }),\n ...(options.getter !== undefined && { getter: options.getter }),\n ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),\n ...(options.local !== undefined && { local: options.local }),\n ...(options.transform !== undefined && { transform: options.transform }),\n ...(options.flag !== undefined && { flag: options.flag })\n };\n }\n // Extract relations (relations) from WeakMap registry\n const relationsMetadata = {};\n const allRelationsMeta = getRelationsMetadata(this);\n const prototypeRelations = allRelationsMeta;\n for (const [relationName, opts] of Object.entries(prototypeRelations)) {\n const options = opts;\n relationsMetadata[relationName] = {\n name: relationName,\n predicate: options.predicate || \"\",\n ...(options.local !== undefined && { local: options.local }),\n ...(options.getter !== undefined && { getter: options.getter }),\n direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',\n ...(options.kind !== undefined && { kind: options.kind }),\n ...(options.maxCount !== undefined && { maxCount: options.maxCount }),\n ...(options.target !== undefined && { target: options.target }),\n ...(options.filter !== undefined && { filter: options.filter }),\n ...(options.where !== undefined && { where: options.where }),\n };\n }\n // Fallback: If both structures are empty but a JSON schema is attached, derive from it\n // This handles edge cases where fromJSONSchema() was called but metadata wasn't properly populated\n const hasProperties = Object.keys(propertiesMetadata).length > 0;\n const hasRelations = Object.keys(relationsMetadata).length > 0;\n const hasMetadata = hasProperties || hasRelations;\n if (!hasMetadata && prototype.__jsonSchema) {\n // Derive metadata from the attached JSON schema\n const schema = prototype.__jsonSchema;\n const options = prototype.__jsonSchemaOptions || {};\n if (schema.properties) {\n for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {\n const isArray = isArrayType(propertySchema);\n const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, options), options);\n if (isArray) {\n relationsMetadata[propertyName] = {\n name: propertyName,\n predicate: predicate,\n ...(propertySchema[\"x-ad4m\"]?.local !== undefined && { local: propertySchema[\"x-ad4m\"].local })\n };\n }\n else {\n const isRequired = schema.required?.includes(propertyName) || false;\n propertiesMetadata[propertyName] = {\n name: propertyName,\n predicate: predicate,\n required: isRequired,\n readOnly: propertySchema[\"x-ad4m\"]?.writable === false,\n ...(propertySchema[\"x-ad4m\"]?.resolveLanguage && { resolveLanguage: propertySchema[\"x-ad4m\"].resolveLanguage }),\n ...(propertySchema[\"x-ad4m\"]?.initial && { initial: propertySchema[\"x-ad4m\"].initial }),\n ...(propertySchema[\"x-ad4m\"]?.local !== undefined && { local: propertySchema[\"x-ad4m\"].local })\n };\n }\n }\n }\n }\n return {\n className,\n properties: propertiesMetadata,\n relations: relationsMetadata,\n };\n }\n /**\n * Constructs a new model instance.\n *\n * @param perspective - The perspective where this model will be stored\n * @param baseExpression - Optional expression URI for this instance.\n * If omitted, a random Literal URL is generated.\n * @param source - Optional source expression this instance is linked to\n *\n * @example\n * ```typescript\n * // Create a new recipe with auto-generated base expression\n * const recipe = new Recipe(perspective);\n *\n * // Create with specific base expression\n * const recipe = new Recipe(perspective, \"literal:...\");\n * ```\n */\n constructor(perspective, baseExpression) {\n this._snapshot = null;\n this._baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomId(24)).toUrl();\n this._perspective = perspective;\n }\n /**\n * The unique identifier (expression URI) of this model instance.\n */\n get id() {\n return this._baseExpression;\n }\n /**\n * Protected getter for the perspective.\n * Allows subclasses to access the perspective while keeping it private from external code.\n */\n get perspective() {\n return this._perspective;\n }\n /**\n * Get property metadata from decorator.\n * @private\n */\n getPropertyMetadata(key) {\n const ctor = this.constructor;\n const props = getPropertiesMetadata(ctor);\n return props[key];\n }\n /**\n * Get relation options from decorator\n * @private\n */\n getRelationOptions(key) {\n const ctor = this.constructor;\n const rels = getRelationsMetadata(ctor);\n return rels[key];\n }\n /**\n * Generate property setter action from metadata.\n * @private\n */\n generatePropertySetterAction(key, metadata) {\n // Flags are always immutable \u2014 throw a clear error\n if (metadata.flag) {\n throw new Error(`Property \"${key}\" is a @Flag and cannot be written. ` +\n `Flags are immutable type markers set at creation time.`);\n }\n // Check if property is read-only\n if (metadata.readOnly) {\n throw new Error(`Property \"${key}\" is read-only and cannot be written`);\n }\n if (metadata.prologSetter) {\n // Custom Prolog setter - throw error for now (Phase 2)\n throw new Error(`Custom Prolog setter for property \"${key}\" not yet supported without Prolog. ` +\n `Use standard @Property decorator or enable Prolog for custom setters.`);\n }\n if (!metadata.through) {\n throw new Error(`Property \"${key}\" has no 'through' predicate defined`);\n }\n return [{\n action: \"setSingleTarget\",\n source: \"this\",\n predicate: metadata.through,\n target: \"value\",\n ...(metadata.local && { local: true })\n }];\n }\n /**\n * Generate relation action from metadata.\n * @private\n */\n generateRelationAction(key, actionType) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n throw new Error(`Relation \"${key}\" has no metadata defined`);\n }\n if (!metadata.predicate) {\n throw new Error(`Relation \"${key}\" has no predicate defined`);\n }\n const actionMap = {\n adder: \"addLink\",\n remover: \"removeLink\",\n setter: \"collectionSetter\"\n };\n return [{\n action: actionMap[actionType],\n source: \"this\",\n predicate: metadata.predicate,\n target: \"value\",\n ...(metadata.local && { local: true })\n }];\n }\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Snapshot / dirty tracking\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * @param includedRelations Controls which relation fields are recorded\n * in the snapshot for dirty-tracking:\n * \u2022 `undefined` (default) \u2014 snapshot ALL relations (used by `.get()`,\n * `.create()`, `.save()` etc. where full hydration has occurred).\n * \u2022 `IncludeMap` object (e.g. `{ views: true }`) \u2014 only snapshot the\n * relations named in the map. Fields not listed are omitted from\n * the snapshot so that `changedFields()` ignores them.\n * \u2022 `null` / empty object \u2014 skip ALL relations (used by bare\n * subscriptions that don't eagerly load relations).\n */\n /** @internal */\n takeSnapshot(includedRelations) {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n const snap = {};\n // Always snapshot properties\n for (const propName of Object.keys(metadata.properties)) {\n const val = this[propName];\n snap[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n // Snapshot relations only when appropriate:\n // undefined \u2192 all relations (backward compat)\n // IncludeMap \u2192 only the keys present in the map\n // null / {} \u2192 none\n if (includedRelations === undefined) {\n // Full snapshot \u2014 e.g. after getData() / create()\n for (const relName of Object.keys(metadata.relations)) {\n const val = this[relName];\n snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n else if (includedRelations && Object.keys(includedRelations).length > 0) {\n // Partial snapshot \u2014 only the explicitly included relations\n for (const relName of Object.keys(includedRelations)) {\n if (relName in metadata.relations) {\n const val = this[relName];\n snap[relName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n }\n // else: null or empty object \u2192 skip all relations\n this._snapshot = snap;\n }\n /**\n * Returns `true` if any tracked property or relation has changed\n * since the last hydration (or since `takeSnapshot()` was last called).\n *\n * Always returns `true` if no snapshot exists (e.g. a freshly\n * constructed instance that hasn't been fetched yet).\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.create(perspective, { name: \"Pasta\" });\n * recipe.isDirty(); // false \u2014 just hydrated\n * recipe.name = \"Risotto\";\n * recipe.isDirty(); // true\n * ```\n */\n isDirty() {\n if (!this._snapshot)\n return true;\n return this.changedFields().length > 0;\n }\n /**\n * Returns the names of properties/relations that differ from the\n * snapshot taken at the last hydration.\n *\n * Returns **all** field names if no snapshot exists.\n *\n * @example\n * ```typescript\n * recipe.name = \"New Name\";\n * recipe.changedFields(); // [\"name\"]\n * ```\n */\n changedFields() {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n if (!this._snapshot) {\n return [\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ];\n }\n const changed = [];\n const allFields = [\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ];\n for (const field of allFields) {\n // Skip fields that were not recorded in the snapshot (e.g. relation\n // fields omitted because the originating query had no `include`).\n // Without this guard, a relation populated by hydrateFromLinks with\n // raw string IDs would appear \"dirty\" against a missing snapshot\n // entry and trigger an unnecessary (and potentially destructive)\n // setRelationValues call during innerUpdate.\n if (!(field in this._snapshot))\n continue;\n const current = normalizeValue(this[field]);\n const original = this._snapshot[field];\n if (Array.isArray(current) || Array.isArray(original)) {\n // Order-insensitive comparison (sorted) so reordering alone\n // doesn't mark a relation as dirty.\n const a = Array.isArray(current) ? [...current].sort() : [];\n const b = Array.isArray(original) ? [...original].sort() : [];\n if (a.length !== b.length || a.some((v, i) => v !== b[i])) {\n changed.push(field);\n }\n }\n else if (current !== original) {\n changed.push(field);\n }\n }\n return changed;\n }\n async getData(opts) {\n // Route through the Rust model query endpoint \u2014 same pipeline as executeModelQuery\n // but for a single instance by ID.\n try {\n const ctor = this.constructor;\n const query = {\n where: { id: this._baseExpression },\n limit: 1,\n deepQuery: true, // Single-instance get() always evaluates property getters\n };\n if (opts?.properties)\n query.properties = opts.properties;\n if (opts?.include)\n query.include = opts.include;\n const { results } = await ctor.executeModelQuery(this._perspective, query, null);\n if (results.length > 0) {\n const hydrated = results[0];\n // Copy all hydrated values from the Rust-side result onto this instance\n for (const [key, value] of Object.entries(hydrated)) {\n if (key === '_baseExpression' || key === '_perspective' || key === '_snapshot')\n continue;\n if (key.startsWith('_'))\n continue;\n // Check for readonly getters\n let isReadonly = false;\n let proto = Object.getPrototypeOf(this);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, key);\n if (desc) {\n isReadonly = !!(desc.get && !desc.set);\n break;\n }\n proto = Object.getPrototypeOf(proto);\n }\n if (isReadonly)\n continue;\n this[key] = value;\n }\n }\n // Property getters and relation conformance getters are now evaluated\n // Rust-side via evaluate_getters() in model_query.rs.\n }\n catch (e) {\n console.error(`getData via Rust model query failed for ${this._baseExpression}:`, e);\n }\n this.takeSnapshot(opts?.include);\n return this;\n }\n /**\n * Generates a SPARQL query from a Query object.\n *\n * @description\n * This method translates high-level query parameters into a SPARQL query string\n * that can be executed against the SPARQL backend. Unlike Prolog queries which\n * operate on SDNA-aware predicates, SPARQL queries operate directly on raw links\n * stored in SPARQL.\n *\n * The generated query uses a CTE (Common Table Expression) pattern:\n * 1. First, identify candidate base expressions by filtering links based on where conditions\n * 2. Then, for each candidate base, resolve properties and relations via subqueries\n * 3. Finally, apply ordering, pagination (LIMIT/START) at the SQL level\n *\n * Key architectural notes:\n * - SPARQL stores only raw links (source, predicate, target, author, timestamp)\n * - No SDNA knowledge at the database level\n * - Properties are resolved via subqueries that look for links with specific predicates\n * - Relations are similar but return multiple values instead of one\n * - Special fields (base, author, timestamp) are accessed directly, not via subqueries\n *\n * @param perspective - The perspective to query (used for metadata extraction)\n * @param query - Query parameters (where, order, limit, offset, properties, relations)\n * @returns Complete SPARQL query string ready for execution\n *\n * @example\n * ```typescript\n * const query = Recipe.queryToSPARQL(perspective, {\n * where: { name: \"Pasta\", rating: { gt: 4 } },\n * order: { timestamp: \"DESC\" },\n * limit: 10\n * });\n * // Returns: SELECT source AS base, array::first(target[WHERE predicate = ...]) AS name, ...\n * // FROM link WHERE ... GROUP BY source ORDER BY timestamp DESC LIMIT 10\n * ```\n */\n static async queryToSPARQL(perspective, query) {\n const metadata = this.getModelMetadata();\n const allRelMeta = getRelationsMetadata(this);\n return buildSPARQLQuery(metadata, allRelMeta, query, this);\n }\n /**\n * Build the JSON parameters needed for a model query/subscription endpoint.\n * Returns the className, queryJson, and shapeJson that the Rust executor expects.\n * @internal\n */\n static prepareModelQueryParams(query = {}, classNameOverride) {\n const metadata = this.getModelMetadata();\n const className = classNameOverride || metadata.className;\n // Expand includeAll: true to a full IncludeMap covering every forward relation.\n if (query.includeAll) {\n const allRelMeta = getRelationsMetadata(this);\n const expanded = {};\n for (const [relName, relMeta] of Object.entries(allRelMeta)) {\n if (relMeta.direction !== 'reverse') {\n expanded[relName] = true;\n }\n }\n query = { ...query, include: { ...expanded, ...query.include } };\n }\n const queryInput = {};\n if (query.parent) {\n const parentPredicate = resolveParentPredicate(query.parent, this);\n queryInput.parent = { id: query.parent.id, predicate: parentPredicate };\n }\n if (query.properties)\n queryInput.properties = query.properties;\n if (query.include) {\n // Split include keys: $-prefixed / IncludeProjection values \u2192 queryInput.projections\n // All other keys (boolean | RelationSubQuery) \u2192 queryInput.include\n const normalIncludes = {};\n const projections = {};\n for (const [key, val] of Object.entries(query.include)) {\n if (key.startsWith('$')) {\n projections[key] = val;\n }\n else {\n normalIncludes[key] = val;\n }\n }\n if (Object.keys(normalIncludes).length > 0)\n queryInput.include = normalIncludes;\n if (Object.keys(projections).length > 0) {\n // Enrich projections with target shapes so Rust can apply where clause filtering\n const allRelMeta = getRelationsMetadata(this);\n for (const [, proj] of Object.entries(projections)) {\n const relMeta = allRelMeta[proj.from];\n if (!proj.targetShape && relMeta?.target) {\n try {\n const TargetClass = relMeta.target();\n const targetMeta = TargetClass.getModelMetadata?.();\n if (targetMeta) {\n proj.targetShape = targetMeta;\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target class unavailable for projection:`, e);\n }\n }\n }\n queryInput.projections = projections;\n }\n }\n if (query.where)\n queryInput.where = query.where;\n if (query.order) {\n queryInput.order = Object.entries(query.order).map(([k, v]) => [k, v]);\n }\n if (query.offset !== undefined)\n queryInput.offset = query.offset;\n if (query.limit !== undefined)\n queryInput.limit = query.limit;\n if (query.count !== undefined)\n queryInput.count = query.count;\n queryInput.deepQuery = query.deepQuery ?? true;\n if (queryInput.include) {\n const allRelMeta = getRelationsMetadata(this);\n enrichShapeForIncludes(metadata, queryInput.include, allRelMeta);\n }\n // Pre-compute conformance getters for Rust-side evaluation.\n // Where clauses are NOT compiled into getter SPARQL because stored\n // property values are signed expression envelopes (literal:json:...),\n // not simple literal:string:X values. Instead, where clauses are\n // attached as metadata for Rust-side post-evaluation filtering.\n {\n const allRelMeta = getRelationsMetadata(this);\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n const rel = relMeta;\n if (rel.getter || rel.direction === 'reverse' || rel.filter === false)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n try {\n const TargetClass = meta.target();\n const filter = buildConformanceFilter(meta.predicate, TargetClass);\n if (filter) {\n rel.getter = filter.getter;\n }\n // Attach where-clause metadata for Rust-side post-getter filtering\n if (rel.where) {\n try {\n const targetMetadata = TargetClass.getModelMetadata?.() ?? null;\n if (targetMetadata) {\n const predicates = {};\n for (const propName of Object.keys(rel.where)) {\n if (['id', 'author', 'timestamp'].includes(propName))\n continue;\n const propMeta = targetMetadata.properties[propName];\n if (propMeta?.predicate) {\n predicates[propName] = propMeta.predicate;\n }\n }\n if (Object.keys(predicates).length > 0) {\n rel.whereFilter = rel.where;\n rel.wherePredicates = predicates;\n }\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target metadata unavailable for relation '${relName}':`, e);\n }\n }\n }\n catch (e) {\n console.debug(`prepareModelQueryParams: target class unavailable for relation '${relName}':`, e);\n }\n }\n }\n return {\n className,\n queryJson: JSON.stringify(queryInput),\n shapeJson: JSON.stringify(metadata),\n metadata,\n };\n }\n /**\n * Parse raw model query/subscription result JSON into typed model instances.\n * Used by ModelQueryBuilder to convert subscription updates without circular imports.\n * @internal\n */\n static parseModelResult(perspective, raw, include, properties) {\n const data = typeof raw === 'string' ? JSON.parse(raw) : raw;\n const arr = data.instances || data;\n if (!Array.isArray(arr))\n return [];\n return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));\n }\n /**\n * Resolve non-literal (file-language) properties on an array of already-constructed\n * model instances. Handles two cases:\n *\n * 1. The Rust executor returned a raw URI string \u2192 fetch via `getExpression` then apply transform.\n * 2. The Rust executor already resolved the expression and returned a `FileData` object\n * (happens when the perspective backend eagerly fetches file content) \u2192 apply transform\n * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-\n * synthesised model classes).\n *\n * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without\n * duplicating logic or introducing a circular dependency.\n * @internal\n */\n static async resolveNonLiteralProps(perspective, instances) {\n const propsMeta = getPropertiesMetadata(this);\n const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&\n opts.resolveLanguage !== 'literal');\n if (resolveProps.length === 0)\n return;\n await Promise.all(instances.map(async (inst) => {\n for (const [propName, opts] of resolveProps) {\n const val = inst[propName];\n const transform = opts.transform;\n const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);\n if (typeof val === 'string' && val && !val.startsWith('literal:')) {\n // Case 1: raw URI \u2014 fetch from language runtime\n try {\n const expression = await perspective.getExpression(val);\n if (expression) {\n let resolved;\n try {\n resolved = JSON.parse(expression.data);\n }\n catch {\n resolved = expression.data;\n }\n inst[propName] = applyTransform(resolved);\n }\n }\n catch (e) {\n console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);\n }\n }\n else if (val !== null && val !== undefined && typeof val === 'object') {\n // Case 2: already resolved by Rust \u2014 apply transform / default decode\n inst[propName] = applyTransform(val);\n }\n }\n }));\n }\n // instancesFromQueryResult \u2014 removed (superseded by Rust executeModelQuery pipeline)\n /**\n * Execute a model query via the executor-side endpoint.\n *\n * This replaces the old SPARQL-build \u2192 hydrate \u2192 JS-filter \u2192 JS-sort \u2192 JS-paginate pipeline\n * with a single RPC to the executor that handles everything in Rust.\n *\n * @internal\n */\n static async executeModelQuery(perspective, query = {}, classNameOverride) {\n // Delegate all query input building, shape enrichment, and getter\n // pre-computation to the shared prepareModelQueryParams helper.\n const { className, queryJson, shapeJson } = this.prepareModelQueryParams(query, classNameOverride);\n const result = await perspective.modelQuery(className, queryJson, shapeJson);\n // Convert JSON instances to model class instances, recursively constructing\n // class instances for any included relations resolved by Rust.\n const instances = result.instances.map((json) => {\n return jsonToModelInstance(this, perspective, json, query.include, query.properties);\n });\n // Resolve non-literal expressions (e.g. file languages where the stored\n // value is a content-addressed hash that must be fetched from the language\n // runtime). The Rust endpoint may return either a raw target URI (string)\n // or an already-resolved FileData object \u2014 both cases are handled here.\n await this.resolveNonLiteralProps(perspective, instances);\n // Take snapshots for dirty tracking (exclude $-prefixed projection keys)\n const snapshotRelations = query.include\n ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))\n : undefined;\n for (const inst of instances) {\n inst.takeSnapshot(snapshotRelations && Object.keys(snapshotRelations).length > 0 ? snapshotRelations : undefined);\n }\n return {\n results: instances,\n totalCount: result.totalCount,\n };\n }\n /**\n * Gets all instances of the model in the perspective that match the query params.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * All queries now use the Rust SPARQL pipeline.\n * @returns Array of matching models\n *\n * @example\n * ```typescript\n * const allRecipes = await Recipe.findAll(perspective);\n *\n * const recipes = await Recipe.findAll(perspective, {\n * where: {\n * name: \"Pasta\",\n * rating: { gt: 4 }\n * },\n * order: { createdAt: \"DESC\" },\n * limit: 10\n * });\n * ```\n */\n static async findAll(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n if (query.properties && query.properties.length === 0) {\n throw new Error(\"properties[] must not be empty \u2014 omit the field to return all properties, or specify at least one field name\");\n }\n const { results } = await this.executeModelQuery(perspective, query);\n return results;\n }\n /**\n * Finds the first instance matching the query, or `null` if none exists.\n *\n * Equivalent to `findAll` with `limit: 1` \u2014 only one instance is hydrated.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * @returns The first matching instance, or `null`\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.findOne(perspective, {\n * where: { name: \"Pasta\" }\n * });\n * if (recipe) {\n * console.log(recipe.name);\n * }\n * ```\n */\n static async findOne(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n const limitedQuery = { ...query, limit: 1 };\n const results = await this.findAll(perspective, limitedQuery);\n return results[0] ?? null;\n }\n /**\n * Gets all instances with count of total matches without offset & limit applied.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @param _engine - **Deprecated.** Accepted for backward compatibility but ignored.\n * @returns Object containing results array and total count\n *\n * @example\n * ```typescript\n * const { results, totalCount } = await Recipe.findAllAndCount(perspective, {\n * where: { category: \"Dessert\" },\n * limit: 10\n * });\n * console.log(`Showing 10 of ${totalCount} dessert recipes`);\n * ```\n */\n static async findAllAndCount(perspective, query = {}, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n return await this.executeModelQuery(perspective, query);\n }\n /**\n * Helper function for pagination with explicit page size and number.\n *\n * @param perspective - The perspective to search in\n * @param pageSize - Number of items per page\n * @param pageNumber - Which page to retrieve (1-based)\n * @param query - Optional additional query parameters\n * @returns Paginated results with metadata\n *\n * @example\n * ```typescript\n * const page = await Recipe.paginate(perspective, 10, 1, {\n * where: { category: \"Main Course\" }\n * });\n * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);\n * ```\n */\n static async paginate(perspective, pageSize, pageNumber, query, \n /** @deprecated Ignored \u2014 Prolog engine has been removed. */\n _engine) {\n const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };\n const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);\n return { results, totalCount, pageSize, pageNumber };\n }\n /**\n * Generates a SPARQL COUNT query for the model.\n *\n * @param perspective - The perspective context\n * @param query - Query parameters to filter the count\n * @returns SPARQL COUNT query string\n *\n * @private\n */\n // countQueryToSPARQL \u2014 removed (zero callers; Rust COUNT fast-path supersedes)\n /**\n * Gets a count of all matching instances.\n *\n * @param perspective - The perspective to search in\n * @param query - Optional query parameters to filter results\n * @returns Total count of matching entities\n *\n * @example\n * ```typescript\n * const totalRecipes = await Recipe.count(perspective);\n * const activeRecipes = await Recipe.count(perspective, {\n * where: { status: \"active\" }\n * });\n * ```\n */\n static async count(perspective, query = {}) {\n const { totalCount } = await this.executeModelQuery(perspective, { ...query, limit: 0 });\n return totalCount;\n }\n async setProperty(key, value, batchId) {\n const metadata = this.getPropertyMetadata(key);\n if (!metadata) {\n console.warn(`Property \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generatePropertySetterAction(key, metadata);\n // Get resolve language from metadata (replaces Prolog query)\n let resolveLanguage = metadata.resolveLanguage;\n // Skip storing empty/null/undefined values to avoid invalid empty literals (e.g. literal:string:)\n if (value === undefined || value === null || value === \"\") {\n return;\n }\n if (resolveLanguage) {\n value = await this._perspective.createExpression(value, resolveLanguage);\n }\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value }], batchId);\n }\n /** Resolve a relation argument to a plain string ID. Accepts either a raw\n * string ID or an Ad4mModel instance (in which case `.id` is used). */\n resolveRelationId(value) {\n if (typeof value === 'string')\n return value;\n if (value && typeof value === 'object' && typeof value.id === 'string')\n return value.id;\n return String(value);\n }\n async setRelationValues(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'setter');\n if (value != null) {\n if (Array.isArray(value)) {\n await this._perspective.executeAction(actions, this._baseExpression, value.map((v) => ({ name: \"value\", value: this.resolveRelationId(v) })), batchId);\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n async addRelationValue(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'adder');\n if (value != null) {\n if (Array.isArray(value)) {\n await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(v) }], batchId)));\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n async removeRelationValue(key, value, batchId) {\n const metadata = this.getRelationOptions(key);\n if (!metadata) {\n console.warn(`Relation \"${key}\" has no metadata, skipping`);\n return;\n }\n // Generate actions from metadata (replaces Prolog query)\n const actions = this.generateRelationAction(key, 'remover');\n if (value != null) {\n if (Array.isArray(value)) {\n await Promise.all(value.map((v) => this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(v) }], batchId)));\n }\n else {\n await this._perspective.executeAction(actions, this._baseExpression, [{ name: \"value\", value: this.resolveRelationId(value) }], batchId);\n }\n }\n }\n /**\n * Saves the model instance to the perspective.\n *\n * **New instances** (no snapshot yet): creates the subject via\n * `createSubject` with initial scalar values, then sets relations\n * via `innerUpdate`.\n *\n * **Existing instances** (snapshot present, i.e. fetched via `get()`\n * or a query): updates only dirty fields via `innerUpdate`, then\n * refreshes from the perspective.\n *\n * @param batchId - Optional batch ID for batch operations\n * @throws Will throw if instance creation, linking, or updating fails\n *\n * @example\n * ```typescript\n * // Create\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Spaghetti\";\n * await recipe.save();\n *\n * // Update\n * recipe.rating = 10;\n * await recipe.save();\n * ```\n */\n async save(batchId) {\n // Existing instance \u2192 update path (has been fetched / hydrated before)\n if (this._snapshot) {\n await this.innerUpdate(true, batchId);\n if (batchId) {\n // Batch hasn't been committed yet \u2014 getData() would fetch stale data\n // and overwrite in-memory values. Just refresh the snapshot so further\n // saves within the same batch diff correctly.\n this.takeSnapshot();\n }\n else {\n await this.getData();\n }\n return;\n }\n // New instance \u2192 create path\n let batchCreatedHere = false;\n if (!batchId) {\n batchId = await this.perspective.createBatch();\n batchCreatedHere = true;\n }\n // Check if the model has any constructor actions (required properties,\n // flags, or properties with initial values). Models whose properties are\n // all optional, have no @Flag, and have no initial values produce an empty\n // SHACL constructor, so calling createSubject would fail on the Rust side\n // (\"No SHACL constructor found\"). In that case we skip createSubject\n // entirely and let innerUpdate write the links directly.\n const metadata = this.constructor.getModelMetadata();\n const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);\n // Track properties that have resolveLanguage (non-literal) so they can be\n // set via setProperty after createSubject (which doesn't resolve languages).\n const deferredResolveLanguageProps = [];\n if (hasConstructor) {\n // First filter out the properties that are not relations (arrays)\n const initialValues = {};\n for (const [key, value] of Object.entries(this)) {\n if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {\n // Check if this property requires language resolution (e.g. file storage).\n // If so, resolve the expression *before* passing to createSubject so\n // the constructor receives a valid URI instead of raw data.\n const propMeta = metadata.properties[key];\n if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {\n // Defer these properties \u2014 they need createExpression which may\n // fail inside a batch context on some languages. We'll set them\n // via setProperty after createSubject.\n deferredResolveLanguageProps.push(key);\n continue;\n }\n initialValues[key] = value;\n }\n }\n // Get the class name instead of passing the instance to avoid Prolog query generation\n const className = await this.perspective.stringOrTemplateObjectToSubjectClassName(this);\n // Create the subject with the initial values\n await this.perspective.createSubject(className, this._baseExpression, initialValues, batchId);\n }\n // Set properties and relations via innerUpdate.\n // When createSubject was skipped (no constructor actions), we must enable\n // property writing so that scalar values are persisted as links.\n await this.innerUpdate(!hasConstructor, batchId);\n // Now handle any deferred resolveLanguage properties that were excluded\n // from initialValues. setProperty will call createExpression to upload\n // the data to the appropriate language and store the resulting URI.\n for (const key of deferredResolveLanguageProps) {\n const value = this[key];\n if (value !== undefined && value !== null) {\n await this.setProperty(key, value, batchId);\n }\n }\n // If we got a batchId passed in, we let the caller decide when to commit.\n // We can't call getData() since the instance won't exist in the perspective\n // until the batch is committed.\n if (batchCreatedHere) {\n await this.perspective.commitBatch(batchId);\n await this.getData();\n }\n else {\n // Take a snapshot so that a subsequent save() within the same batch\n // routes through the UPDATE path instead of CREATE, avoiding duplicate\n // links (e.g. two competing \"title\" values).\n this.takeSnapshot();\n }\n }\n cleanCopy() {\n const ctor = this.constructor;\n const metadata = ctor.getModelMetadata();\n const cleanCopy = {};\n // Only include schema-declared fields (properties + relations),\n // preserving internal ORM machinery (_id, _perspective, generated\n // addX/removeX/setX methods, _snapshot, etc.)\n const schemaFields = new Set([\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ]);\n for (const key of schemaFields) {\n const value = this[key];\n if (value !== undefined && value !== null && key !== \"author\" && key !== \"timestamp\") {\n cleanCopy[key] = value;\n }\n }\n return cleanCopy;\n }\n async innerUpdate(setProperties = true, batchId) {\n const ctor = this.constructor;\n // Determine which fields actually changed (skip unchanged when snapshot exists)\n const dirty = this._snapshot ? new Set(this.changedFields()) : null;\n // Only iterate schema-declared fields, not internal ORM properties\n const metadata = ctor.getModelMetadata();\n const schemaFields = new Set([\n ...Object.keys(metadata.properties),\n ...Object.keys(metadata.relations),\n ]);\n const entries = Object.entries(this);\n for (const [key, value] of entries) {\n // Only process schema-declared fields\n if (!schemaFields.has(key))\n continue;\n // Skip unchanged fields when a snapshot is available\n if (dirty && !dirty.has(key))\n continue;\n // Skip read-only computed relations \u2014 explicit getters never write links.\n // For target+filter relations, skip only when another relation on this\n // model claims the same predicate (i.e., this is a filtered *view* of a\n // base relation and writing would collide).\n const relMeta = metadata.relations[key];\n if (relMeta) {\n if (relMeta.getter)\n continue;\n if (relMeta.target && relMeta.filter !== false) {\n // Check for predicate collision with a sibling relation\n const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&\n otherMeta.predicate === relMeta.predicate);\n if (hasCollision)\n continue;\n }\n }\n if (value !== undefined && value !== null) {\n if (value?.action) {\n switch (value.action) {\n case \"setter\":\n await this.setRelationValues(key, value.value, batchId);\n break;\n case \"adder\":\n await this.addRelationValue(key, value.value, batchId);\n break;\n case \"remover\":\n await this.removeRelationValue(key, value.value, batchId);\n break;\n default:\n await this.setRelationValues(key, value.value, batchId);\n break;\n }\n }\n else if (Array.isArray(value)) {\n // Handle all arrays as relations, including empty ones (which clears the relation)\n await this.setRelationValues(key, value, batchId);\n }\n else if (value !== undefined && value !== null && value !== \"\") {\n if (setProperties) {\n // Check if this is a relation property (has relation metadata)\n const relationMeta = this.getRelationOptions(key);\n if (relationMeta) {\n // Skip - it's a relation, not a regular property\n continue;\n }\n // Skip flag properties \u2014 they are immutable after creation\n const propMeta = this.getPropertyMetadata(key);\n if (propMeta?.flag) {\n continue;\n }\n await this.setProperty(key, value, batchId);\n }\n }\n }\n }\n }\n /**\n * Evaluate SPARQL getters for a batch of instances on demand.\n *\n * Since deepQuery defaults to true, property getters are evaluated\n * automatically during collection queries. Use this method when\n * deepQuery was explicitly set to false and you want to lazily\n * resolve getter-backed properties for a subset of instances.\n *\n * @param instances - Array of model instances to evaluate getters on\n * @param perspective - The perspective to query against\n * @param propertyNames - Optional list of getter-backed property names to evaluate.\n * If omitted, all getters are evaluated.\n *\n * @example\n * ```typescript\n * const messages = await Message.query(perspective).deepQuery(false).limit(30).get();\n * // messages[i].replyingTo is undefined (getter skipped)\n *\n * // Evaluate getters for the visible subset\n * await Message.evaluateGetters(messages.slice(0, 10), perspective, ['replyingTo']);\n * // messages[0..9].replyingTo is now populated\n * ```\n */\n static async evaluateGetters(instances, perspective, propertyNames) {\n if (instances.length === 0)\n return;\n const metadata = this.getModelMetadata();\n // Pre-compute conformance getters so the shape sent to Rust includes them\n const allRelMeta = getRelationsMetadata(this);\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n const rel = relMeta;\n if (rel.getter || rel.direction === 'reverse' || rel.filter === false)\n continue;\n const meta = allRelMeta[relName];\n if (!meta?.target)\n continue;\n try {\n const TargetClass = meta.target();\n const filter = buildConformanceFilter(meta.predicate, TargetClass);\n if (filter)\n rel.getter = filter.getter;\n }\n catch (e) {\n console.debug(`evaluateGetters: target class unavailable for relation '${relName}':`, e);\n }\n }\n const shapeJson = JSON.stringify(metadata);\n const instanceIds = instances.map(inst => inst.id || inst._baseExpression);\n // Single RPC call evaluates all getters in-process on the executor\n const result = await perspective.evaluateGetters(metadata.className, instanceIds, shapeJson, propertyNames);\n // Determine which property names were evaluated for snapshot sync\n const evaluatedPropertyNames = [];\n for (const [propName, propMeta] of Object.entries(metadata.properties)) {\n if (propMeta.getter) {\n if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(propName)) {\n evaluatedPropertyNames.push(propName);\n }\n }\n }\n // Also include relation getters\n for (const [relName, relMeta] of Object.entries(metadata.relations)) {\n if (relMeta.getter) {\n if (!propertyNames || propertyNames.length === 0 || propertyNames.includes(relName)) {\n evaluatedPropertyNames.push(relName);\n }\n }\n }\n // Apply results to instances and sync snapshots\n for (const instance of instances) {\n const id = instance.id || instance._baseExpression;\n const props = result[id];\n if (props) {\n for (const [key, value] of Object.entries(props)) {\n instance[key] = value;\n }\n }\n // Sync snapshot so isDirty() doesn't flag getter-only changes\n const modelInstance = instance;\n if (modelInstance._snapshot) {\n for (const propName of evaluatedPropertyNames) {\n const val = instance[propName];\n modelInstance._snapshot[propName] = normalizeValue(Array.isArray(val) ? [...val] : val);\n }\n }\n }\n }\n /**\n * Gets the model instance with all properties and relations populated.\n *\n * @param optsOrInclude - Optional hydration options. Accepts two forms:\n * - `GetOptions` wrapper: `{ include: { comments: true }, properties: ['title'] }`\n * - `IncludeMap` shorthand: `{ comments: true }` (equivalent to `{ include: { comments: true } }`)\n * @returns The populated model instance\n * @throws Will throw if data retrieval fails\n *\n * @example\n * ```typescript\n * const recipe = new Recipe(perspective, existingId);\n * await recipe.get();\n * console.log(recipe.name, recipe.ingredients);\n *\n * // Shorthand \u2014 pass IncludeMap directly:\n * await recipe.get({ ingredients: true });\n *\n * // Full options \u2014 includes sparse fieldset:\n * await recipe.get({ include: { ingredients: true }, properties: ['name'] });\n * ```\n */\n async get(optsOrInclude) {\n // Normalise: if the caller passed a plain IncludeMap shorthand (no `include`\n // or `properties` key at the top level) wrap it in GetOptions automatically.\n let opts;\n if (!optsOrInclude) {\n opts = undefined;\n }\n else if ('include' in optsOrInclude || 'properties' in optsOrInclude) {\n opts = optsOrInclude;\n }\n else {\n opts = { include: optsOrInclude };\n }\n return await this.getData(opts);\n }\n /**\n * Deletes the model instance from the perspective.\n *\n * @param batchId - Optional batch ID for batch operations\n * @throws Will throw if removal fails\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.findAll(perspective)[0];\n * await recipe.delete();\n *\n * // Or with batch operations:\n * const batchId = await perspective.createBatch();\n * await recipe.delete(batchId);\n * await perspective.commitBatch(batchId);\n * ```\n */\n async delete(batchId) {\n const metadata = this.constructor.getModelMetadata();\n const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);\n if (hasDestructor) {\n // Remove the subject itself (destructor actions)\n await this._perspective.removeSubject(this, this._baseExpression, batchId);\n }\n else {\n // No destructor (all-optional model).\n // SAFETY: We must NOT remove all outgoing links because another model\n // class may be instantiated on the same base expression. Removing\n // everything would silently destroy that other instance's data \u2014 and\n // if that instance has a destructor, it can no longer be called\n // cleanly, leaving link debris.\n //\n // Instead we only remove outgoing links whose predicate is declared\n // by THIS model's schema (properties + relations).\n try {\n const knownPredicates = new Set();\n for (const p of Object.values(metadata.properties)) {\n if (p.predicate)\n knownPredicates.add(p.predicate);\n }\n for (const r of Object.values(metadata.relations)) {\n if (r.predicate)\n knownPredicates.add(r.predicate);\n }\n const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));\n const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));\n if (ownLinks.length > 0) {\n await this._perspective.removeLinks(ownLinks, batchId);\n }\n }\n catch (e) {\n console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);\n }\n }\n // Clean up incoming links \u2014 remove any links that point **to** this instance.\n // Unlike outgoing links (scoped above), incoming links originate from OTHER\n // nodes. Removing them doesn't damage sibling models on this node; it\n // prevents dangling references elsewhere (e.g. a parent's has_child link).\n try {\n const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));\n if (incomingLinks.length > 0) {\n await this._perspective.removeLinks(incomingLinks, batchId);\n }\n }\n catch (e) {\n // Non-fatal: the subject was already deleted; incoming link cleanup is best-effort\n console.warn(`delete(): failed to clean up incoming links for ${this._baseExpression}:`, e);\n }\n }\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Static convenience methods\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * Creates and saves a new model instance in one step.\n *\n * @param perspective - The perspective to create the instance in\n * @param data - Property values to assign before saving\n * @param options - Optional settings:\n * - `parent` \u2014 a `ParentScope` (model form or raw form) whose `id` will\n * be used to create an incoming link from the parent to the new instance.\n * - `batchId` \u2014 an existing batch id; when provided the link write and\n * `save()` are added to the batch instead of committed immediately.\n * @returns The saved model instance\n *\n * @example\n * ```typescript\n * // Simple create\n * const recipe = await Recipe.create(perspective, {\n * name: \"Spaghetti\",\n * rating: 5,\n * });\n *\n * // Create under a parent (link auto-created)\n * const comment = await Comment.create(perspective, { text: \"Great!\" }, {\n * parent: { model: Post, id: postId },\n * });\n *\n * // Create inside a transaction\n * await Ad4mModel.transaction(perspective, async (tx) => {\n * await Recipe.create(perspective, { name: \"Pasta\" }, { batchId: tx.batchId });\n * });\n * ```\n */\n static async create(perspective, data = {}, options) {\n const instance = new this(perspective);\n Object.assign(instance, data);\n // When a parent scope is provided without a caller-supplied batch, open a\n // new batch ourselves so that the instance creation and the parent\u2192child\n // link are committed atomically. If either step throws, commitBatch is\n // never reached and the batch is implicitly abandoned (rollback).\n if (options?.parent && !options?.batchId) {\n const batchId = await perspective.createBatch();\n await instance.save(batchId);\n const predicate = resolveParentPredicate(options.parent, this);\n const link = new Link({\n source: options.parent.id,\n predicate,\n target: instance.id,\n });\n await perspective.add(link, 'shared', batchId);\n await perspective.commitBatch(batchId);\n // Hydrate the instance now that the batch has been committed (mirrors the\n // behaviour of save() when it manages its own batch).\n await instance.get();\n return instance;\n }\n await instance.save(options?.batchId);\n // Create parent \u2192 child link if a parent scope was provided\n if (options?.parent) {\n const predicate = resolveParentPredicate(options.parent, this);\n const link = new Link({\n source: options.parent.id,\n predicate,\n target: instance.id,\n });\n await perspective.add(link, 'shared', options?.batchId);\n }\n return instance;\n }\n /**\n * Updates an existing model instance identified by `id`.\n *\n * Fetches the instance, applies the provided changes, calls `save()`,\n * and returns the refreshed instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to update\n * @param data - Property values to merge before saving\n * @returns The updated model instance\n *\n * @example\n * ```typescript\n * const recipe = await Recipe.update(perspective, recipeId, {\n * rating: 10,\n * });\n * ```\n */\n static async update(perspective, id, data) {\n const instance = new this(perspective, id);\n await instance.get();\n Object.assign(instance, data);\n await instance.save();\n return instance;\n }\n /**\n * Deletes an existing model instance identified by `id`.\n *\n * Also cleans up any incoming links that point to this instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to delete\n *\n * @example\n * ```typescript\n * await Recipe.delete(perspective, recipeId);\n * ```\n *\n * @deprecated Use the name `delete` \u2014 `remove` is preserved as an alias.\n */\n static async remove(perspective, id) {\n return this.delete(perspective, id);\n }\n /**\n * Deletes an existing model instance identified by `id`.\n *\n * Also cleans up any incoming links that point to this instance.\n *\n * @param perspective - The perspective containing the instance\n * @param id - The expression URI of the instance to delete\n *\n * @example\n * ```typescript\n * await Recipe.delete(perspective, recipeId);\n * ```\n */\n static async delete(perspective, id) {\n const instance = new this(perspective, id);\n await instance.delete();\n }\n /**\n * Registers this model's SHACL schema on the given perspective.\n *\n * This ensures the perspective knows about the model's shape\n * (properties, relations, constraints) so instances can be\n * created, queried, and validated.\n *\n * @param perspective - The perspective to register the model on\n *\n * @example\n * ```typescript\n * await Recipe.register(perspective);\n * // Now you can create / query Recipe instances on this perspective\n * ```\n */\n static async register(perspective) {\n await perspective.ensureSDNASubjectClass(this);\n }\n /**\n * Batch-registers multiple model classes on a perspective in a single RPC call.\n * This is significantly faster than calling `register()` on each model individually\n * because it eliminates N-1 round-trips and mutex acquisitions.\n *\n * @param perspective - The perspective to register the models on\n * @param models - Array of Ad4mModel subclasses to register\n *\n * @example\n * ```typescript\n * await Ad4mModel.registerAll(perspective, [Community, Channel, Message, Task]);\n * ```\n */\n static async registerAll(perspective, models) {\n await perspective.ensureSubjectClasses(models);\n }\n /**\n * Executes a set of model operations inside a single batch (transaction).\n *\n * All `save`, `update`, and `delete` calls made via the provided `batchId`\n * are buffered and flushed atomically when the callback completes.\n * If the callback throws, the batch is **not** committed, preventing\n * partial writes.\n *\n * @param perspective - The perspective to operate on\n * @param fn - Async callback that receives a `TransactionContext` object.\n * Pass `tx.batchId` to `save(tx.batchId)`, `update(tx.batchId)`,\n * `delete(tx.batchId)`, etc.\n * @returns The value returned by `fn`\n *\n * @example\n * ```typescript\n * await Ad4mModel.transaction(perspective, async (tx) => {\n * const recipe = new Recipe(perspective);\n * recipe.name = \"Spaghetti\";\n * await recipe.save(tx.batchId);\n *\n * const old = await Recipe.query(perspective).where({ name: \"Stale\" }).run();\n * for (const r of old) await r.delete(tx.batchId);\n * });\n * // All changes committed atomically here\n * ```\n */\n static async transaction(perspective, fn) {\n const batchId = await perspective.createBatch();\n const result = await fn({ batchId });\n await perspective.commitBatch(batchId);\n return result;\n }\n /**\n * Creates a query builder for fluent query construction.\n *\n * @param perspective - The perspective to query\n * @param query - Optional initial query parameters\n * @returns A new query builder instance\n *\n * @example\n * ```typescript\n * const recipes = await Recipe.query(perspective)\n * .where({ category: \"Dessert\" })\n * .order({ rating: \"DESC\" })\n * .limit(5)\n * .run();\n *\n * // With real-time updates\n * await Recipe.query(perspective)\n * .where({ status: \"cooking\" })\n * .subscribe(recipes => {\n * console.log(\"Currently cooking:\", recipes);\n * });\n * ```\n */\n static query(perspective, query) {\n return new ModelQueryBuilder(perspective, this, query);\n }\n /**\n * Creates an Ad4mModel class from a JSON Schema definition.\n *\n * @description\n * This method dynamically generates an Ad4mModel subclass from a JSON Schema,\n * enabling integration with systems that use JSON Schema for type definitions.\n *\n * The method follows a cascading approach for determining predicates:\n * 1. Explicit configuration in options parameter (highest precedence)\n * 2. x-ad4m metadata in the JSON Schema\n * 3. Inference from schema title and property names\n * 4. Error if no namespace can be determined\n *\n * @example\n * ```typescript\n * // With explicit configuration\n * const PersonClass = Ad4mModel.fromJSONSchema(schema, {\n * name: \"Person\",\n * namespace: \"person://\",\n * resolveLanguage: \"literal\"\n * });\n *\n * // With property mapping\n * const ContactClass = Ad4mModel.fromJSONSchema(schema, {\n * name: \"Contact\",\n * namespace: \"contact://\",\n * propertyMapping: {\n * \"name\": \"foaf://name\",\n * \"email\": \"foaf://mbox\"\n * }\n * });\n *\n * // With x-ad4m metadata in schema\n * const schema = {\n * \"title\": \"Product\",\n * \"x-ad4m\": { \"namespace\": \"product://\" },\n * \"properties\": {\n * \"name\": {\n * \"type\": \"string\",\n * \"x-ad4m\": { \"through\": \"product://title\" }\n * }\n * }\n * };\n * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: \"Product\" });\n * ```\n *\n * @param schema - JSON Schema definition\n * @param options - Configuration options\n * @returns Generated Ad4mModel subclass\n * @throws Error when namespace cannot be inferred\n */\n static fromJSONSchema(schema, options) {\n return buildModelFromJSONSchema(this, schema, options);\n }\n /**\n * Creates a fully functional Ad4mModel subclass from a SHACL shape.\n *\n * Unlike `fromJSONSchema()`, no predicate inference is required \u2014\n * `SHACLShape` already contains the exact predicate URI in `path` for\n * every property. The method reads each property's `path`, `maxCount`,\n * `writable`, and `resolveLanguage` directly and writes them to the\n * WeakMap metadata registries.\n *\n * Properties with `hasValue` (flag / type-discrimination markers) are\n * registered as hidden flag entries so that the SPARQL query builder emits\n * the fixed triple `?source <predicate> <value>` needed for type discrimination.\n * Properties without a `name` field are skipped.\n *\n * **Backward-compat:** Old Flux SHACL shapes (created before `sh:hasValue`\n * was persisted on property shapes) carry the flag value only in\n * `shape.constructor_actions` as the `target` of an `addLink` action.\n * This method recovers those values so that old perspectives are queried\n * with the correct type-discriminator triple.\n *\n * @param shape - SHACL node shape (as returned by `PerspectiveProxy.getAllShacl()`)\n * @param name - Class name to assign (e.g. \"Channel\")\n * @returns Generated Ad4mModel subclass, ready for querying\n */\n /**\n * Synthesise an `Ad4mModel` subclass from a SHACL shape.\n *\n * @param shape - The SHACL shape to synthesise from.\n * @param name - The model name (e.g. \"Channel\").\n * @param classResolver - Optional thunk factory. When provided, any collection\n * property that carries a `sh:class` URI will have its `target` wired up lazily:\n * `target: () => classResolver(localName)`. Because `target` is only called at\n * query time (inside `enrichShapeForIncludes` / `jsonToModelInstance`), the\n * resolver just needs to return the correct class by the time a query runs \u2014\n * making it safe to pass a closure over a registry object that is still being\n * populated (e.g. the `result` record inside `getModelClasses`).\n */\n static fromSHACL(shape, name, classResolver) {\n const DynamicModelClass = class extends this {\n };\n DynamicModelClass.className = name;\n DynamicModelClass.prototype.className = name;\n // Build a backward-compat fallback map: predicate \u2192 fixed-IRI-value from\n // constructor actions. Old SHACL stores (created before sh:hasValue was\n // persisted on the property shape) don't carry sh:hasValue on properties,\n // but the shape-level constructor_actions always contain an addLink action\n // with the fixed flag value as the target.\n const flagValueFromConstructor = new Map();\n for (const action of shape.constructor_actions ?? []) {\n if (action.action === 'addLink' &&\n typeof action.predicate === 'string' &&\n typeof action.target === 'string' &&\n action.target !== 'value' &&\n !action.target.startsWith('literal:')) {\n flagValueFromConstructor.set(action.predicate, action.target);\n }\n }\n for (const prop of shape.properties) {\n const resolvedHasValue = prop.hasValue ?? flagValueFromConstructor.get(prop.path);\n if (resolvedHasValue !== undefined) {\n const flagKey = prop.name ?? `_flag_${prop.path.replace(/[^a-zA-Z0-9_]/g, '_')}`;\n setPropertyRegistryEntry(DynamicModelClass, flagKey, {\n through: prop.path,\n required: true,\n initial: resolvedHasValue,\n flag: true,\n writable: false,\n readOnly: true,\n });\n continue;\n }\n // Skip properties without a declared name\n if (!prop.name)\n continue;\n const isCollection = prop.maxCount === undefined || prop.maxCount > 1;\n if (isCollection) {\n // Derive a lazy `target` thunk when a sh:class URI is present and a\n // classResolver was supplied. The thunk is evaluated at query time so\n // it is safe even if the target class hasn't been registered yet.\n let targetThunk;\n if (prop.class && classResolver) {\n const sep = Math.max(prop.class.lastIndexOf('#'), prop.class.lastIndexOf('/'));\n const localName = sep >= 0 ? prop.class.slice(sep + 1) : prop.class;\n targetThunk = () => classResolver(localName);\n }\n setRelationRegistryEntry(DynamicModelClass, prop.name, {\n predicate: prop.path,\n kind: 'hasMany',\n ...(targetThunk !== undefined && { target: targetThunk }),\n ...(prop.local !== undefined && { local: prop.local }),\n ...(prop.getter !== undefined && { getter: prop.getter }),\n });\n }\n else {\n setPropertyRegistryEntry(DynamicModelClass, prop.name, {\n through: prop.path,\n writable: prop.writable ?? true,\n ...(prop.resolveLanguage !== undefined && { resolveLanguage: prop.resolveLanguage }),\n ...(prop.local !== undefined && { local: prop.local }),\n });\n }\n }\n const ModelDecorator = Model$1({ name });\n ModelDecorator(DynamicModelClass);\n return DynamicModelClass;\n }\n}\nAd4mModel.classNamesByClass = new WeakMap();\n\nvar __classPrivateFieldSet$1 = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet$1 = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _Ad4mClient_baseUrl, _Ad4mClient_token, _Ad4mClient_apiClient, _Ad4mClient_agentClient, _Ad4mClient_expressionClient, _Ad4mClient_languageClient, _Ad4mClient_neighbourhoodClient, _Ad4mClient_perspectiveClient, _Ad4mClient_runtimeClient, _Ad4mClient_aiClient;\n/**\n * Client for the Ad4m interface wrapping WebSocket RPC calls\n * for convenient use in user facing code.\n *\n * Aggregates the six sub-clients:\n * AgentClient, ExpressionClient, LanguageClient,\n * NeighbourhoodClient, PerspectiveClient and RuntimeClient\n * for the respective functionality.\n */\nclass Ad4mClient {\n constructor(baseUrl, token, subscribe = true, options) {\n _Ad4mClient_baseUrl.set(this, void 0);\n _Ad4mClient_token.set(this, void 0);\n _Ad4mClient_apiClient.set(this, void 0);\n _Ad4mClient_agentClient.set(this, void 0);\n _Ad4mClient_expressionClient.set(this, void 0);\n _Ad4mClient_languageClient.set(this, void 0);\n _Ad4mClient_neighbourhoodClient.set(this, void 0);\n _Ad4mClient_perspectiveClient.set(this, void 0);\n _Ad4mClient_runtimeClient.set(this, void 0);\n _Ad4mClient_aiClient.set(this, void 0);\n __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_token, token, \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_neighbourhoodClient, new NeighbourhoodClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_aiClient, new AIClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldSet$1(this, _Ad4mClient_perspectiveClient, new PerspectiveClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setExpressionClient(__classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, \"f\"));\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setNeighbourhoodClient(__classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, \"f\"));\n __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\").setAIClient(__classPrivateFieldGet$1(this, _Ad4mClient_aiClient, \"f\"));\n __classPrivateFieldSet$1(this, _Ad4mClient_runtimeClient, new RuntimeClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\")), \"f\");\n // Register with AD4M DevTools if the bridge is installed (e.g. browser extension)\n try {\n const dt = globalThis.__AD4M_DEVTOOLS__;\n if (dt) {\n dt._client = this;\n dt._Ad4mModel = Ad4mModel;\n }\n }\n catch { }\n }\n get agent() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\");\n }\n get expression() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_expressionClient, \"f\");\n }\n get languages() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_languageClient, \"f\");\n }\n get neighbourhood() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_neighbourhoodClient, \"f\");\n }\n get perspective() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_perspectiveClient, \"f\");\n }\n get runtime() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_runtimeClient, \"f\");\n }\n get ai() {\n return __classPrivateFieldGet$1(this, _Ad4mClient_aiClient, \"f\");\n }\n /** Start event subscriptions (agent-updated, agent-status-changed, apps-changed).\n * Safe to call if subscriptions were deferred at construction (subscribe=false). */\n startSubscriptions() {\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAgentUpdated();\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAgentStatusChanged();\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").subscribeAppsChanged();\n }\n /** Close all event connections and clear in-memory caches */\n close() {\n __classPrivateFieldGet$1(this, _Ad4mClient_agentClient, \"f\").clearByDidCache();\n __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, \"f\").closeAll();\n }\n}\n_Ad4mClient_baseUrl = new WeakMap(), _Ad4mClient_token = new WeakMap(), _Ad4mClient_apiClient = new WeakMap(), _Ad4mClient_agentClient = new WeakMap(), _Ad4mClient_expressionClient = new WeakMap(), _Ad4mClient_languageClient = new WeakMap(), _Ad4mClient_neighbourhoodClient = new WeakMap(), _Ad4mClient_perspectiveClient = new WeakMap(), _Ad4mClient_runtimeClient = new WeakMap(), _Ad4mClient_aiClient = new WeakMap();\n\nvar ExceptionType;\n(function (ExceptionType) {\n ExceptionType[\"LanguageIsNotLoaded\"] = \"LANGUAGE_IS_NOT_LOADED\";\n ExceptionType[\"ExpressionIsNotVerified\"] = \"EXPRESSION_IS_NOT_VERIFIED\";\n ExceptionType[\"AgentIsUntrusted\"] = \"AGENT_IS_UNTRUSTED\";\n ExceptionType[\"CapabilityRequested\"] = \"CAPABILITY_REQUESTED\";\n ExceptionType[\"InstallNotificationRequest\"] = \"INSTALL_NOTIFICATION_REQUEST\";\n})(ExceptionType || (ExceptionType = {}));\n\n// Unique Language ID with option type\nclass LanguageRef {\n constructor(address, name) {\n this.address = address;\n this.name = name;\n }\n}\n\n// Expression address + unique Language ID = global expression URL\nclass ExpressionRef {\n constructor(lang, expr) {\n this.language = lang;\n this.expression = expr;\n }\n}\n// Creates unique expression URI like this:\n// expr:Qm3490gfwe489hf34:Qm90ghjoaw4iehioefwe4ort\nfunction exprRef2String(ref) {\n if (ref.language.address === 'did')\n return ref.expression.toString();\n else\n return `${ref.language.address}://${ref.expression}`;\n}\nfunction parseExprUrl(url) {\n if (url.startsWith(\"literal:\")) {\n const languageRef = new LanguageRef();\n languageRef.address = 'literal';\n languageRef.name = 'literal';\n const content = url.substring(8);\n return new ExpressionRef(languageRef, content);\n }\n const URIregexp = /^([^:^\\s]+):\\/\\/([\\s\\S]+)$/;\n const URImatches = URIregexp.exec(url);\n if (URImatches && URImatches.length == 3) {\n const language = URImatches[1];\n const expression = URImatches[2];\n const languageRef = new LanguageRef();\n languageRef.address = language;\n const ref = new ExpressionRef(languageRef, expression);\n return ref;\n }\n const DIDregexp = /^did:([^\\s]+)$/;\n const DIDmatches = DIDregexp.exec(url);\n if (DIDmatches && DIDmatches.length == 2) {\n const languageRef = new LanguageRef();\n languageRef.address = 'did';\n const ref = new ExpressionRef(languageRef, url);\n return ref;\n }\n throw new Error(\"Couldn't parse string as expression URL or DID: \" + url);\n}\n\nclass Icon {\n constructor(code) {\n this.code = code;\n }\n}\n\n/**\n * # AD4M Language \u2014 client-side types\n *\n * This file only contains the client-visible types that the AD4M REST\n * API exposes on top of a running Language \u2014 interaction metadata, online\n * agent records, and the telepresence-signal callback shape.\n *\n * **If you're authoring an AD4M Language**, you don't consume types from\n * here \u2014 use [`@coasys/ad4m-ldk`](https://www.npmjs.com/package/@coasys/ad4m-ldk)\n * (or the [Rust ALDK](https://crates.io/crates/ad4m-ldk)), which provide\n * the capability traits, typed runtime-import wrappers, and authoring\n * macros/helpers.\n *\n * The normative interface definition lives in\n * [`docs-src/ad4m-lang.wit`](https://github.com/coasys/ad4m/blob/dev/docs-src/ad4m-lang.wit).\n * The prose spec is\n * [`docs-src/language-interface-spec.md`](https://github.com/coasys/ad4m/blob/dev/docs-src/language-interface-spec.md).\n */\n// ----- Interaction metadata --------------------------------------------------\n//\n// Languages optionally publish a list of user-invocable actions per\n// Expression (\"interactions\"). The runtime surfaces these to UIs via\n// the API as first-class objects.\nclass InteractionParameter {\n}\nclass InteractionMeta {\n}\nclass InteractionCall {\n get parameters() {\n return JSON.parse(this.parametersStringified);\n }\n constructor(name, parameters) {\n this.name = name;\n this.parametersStringified = JSON.stringify(parameters);\n }\n}\n// ----- Telepresence ----------------------------------------------------------\nclass OnlineAgent {\n}\n\nclass LanguageHandle {\n}\n\nclass LanguageMeta {\n}\nclass LanguageMetaInput {\n constructor(name, description) {\n this.name = name;\n this.description = description;\n if (!this.description)\n this.description = \"\";\n }\n}\nclass LanguageMetaInternal {\n}\nclass LanguageExpression extends ExpressionGeneric() {\n}\nclass LanguageLanguageInput {\n}\n\nvar PerspectiveState;\n(function (PerspectiveState) {\n PerspectiveState[\"Private\"] = \"PRIVATE\";\n PerspectiveState[\"NeighboudhoodCreationInitiated\"] = \"NEIGHBOURHOOD_CREATION_INITIATED\";\n PerspectiveState[\"NeighbourhoodJoinInitiated\"] = \"NEIGHBOURHOOD_JOIN_INITIATED\";\n PerspectiveState[\"LinkLanguageFailedToInstall\"] = \"LINK_LANGUAGE_FAILED_TO_INSTALL\";\n PerspectiveState[\"LinkLanguageInstalledButNotSynced\"] = \"LINK_LANGUAGE_INSTALLED_BUT_NOT_SYNCED\";\n PerspectiveState[\"Synced\"] = \"SYNCED\";\n})(PerspectiveState || (PerspectiveState = {}));\n// This type is used in the REST interface to reference a mutable\n// prespective that is implemented locally by the Ad4m runtime.\n// The UUID is used in mutations to identify the perspective that gets mutated.\nclass PerspectiveHandle {\n constructor(uuid, name, state) {\n this.uuid = uuid;\n this.name = name;\n if (state) {\n this.state = state;\n }\n else {\n this.state = PerspectiveState.Private;\n }\n }\n}\n\n/**\n * WakerSubscriptionManager \u2014 manages live query subscriptions for the waker.\n *\n * Lives in core so it can be imported by both the plugin and integration tests\n * without ESM/CJS import issues.\n *\n * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts\n */\nclass WakerSubscriptionManager {\n constructor(options) {\n this.proxies = new Map();\n this.activeSubscriptions = new Map();\n this.debounceTimers = new Map();\n /** Per-subscription set of already-processed message addresses (for mention subs)\n * or serialized result hash (for channel-messages subs). */\n this.seenMessages = new Map();\n this.perspectiveClient = options.perspectiveClient;\n this.logger = options.logger;\n this.debounceMs = options.debounceMs ?? 2000;\n this.onWake = options.onWake;\n this.onPersist = options.onPersist;\n this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;\n this.previousSeenMessages = options.previousSeenMessages ?? {};\n }\n /**\n * Create a live SPARQL subscription.\n * If a subscription with the same id already exists, it is disposed first.\n */\n async subscribe(sub) {\n // Dispose existing subscription with same id if any\n this.dispose(sub.id, false);\n if (!this.QuerySubscriptionProxyCtor) {\n throw new Error(\"WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options\");\n }\n const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;\n this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);\n this.logger.info(`[waker] ${sub.id}: SPARQL query:\\n${sub.query}`);\n const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);\n proxy.isSPARQL = true;\n // Suppress unhandled rejection from proxy.initialized \u2014 QuerySubscriptionProxy\n // rejects this promise internally when subscribe() fails, and if nobody catches\n // it before the next microtask it crashes the process.\n if (proxy.initialized && typeof proxy.initialized.catch === \"function\") {\n proxy.initialized.catch(() => { });\n }\n try {\n await proxy.subscribe();\n await proxy.initialized;\n }\n catch (err) {\n const msg = err?.message ?? String(err);\n this.logger.warn(`[waker] ${sub.id}: subscription failed \u2014 ${msg}`);\n try {\n proxy.dispose();\n }\n catch { }\n // Remove from active state so it doesn't get persisted/retried\n this.activeSubscriptions.delete(sub.id);\n this.seenMessages.delete(sub.id);\n this.persist();\n return; // Don't throw \u2014 caller should not crash\n }\n this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);\n // Seed from persisted seen messages so we don't re-wake after restart\n const seen = new Set(this.previousSeenMessages[sub.id] ?? []);\n this.seenMessages.set(sub.id, seen);\n if (seen.size > 0) {\n this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);\n }\n proxy.onResult(async (result) => {\n this.logger.info(`[waker] ${sub.id}: onResult fired \u2014 type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);\n // Query engine can deliver non-array values (e.g. false) on disconnect/reconnect \u2014 ignore them\n if (!Array.isArray(result)) {\n this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);\n return;\n }\n if (sub.type === \"mention\") {\n // For mention subscriptions: track seen message addresses.\n // Only wake for messages we haven't seen before.\n const currentSeen = this.seenMessages.get(sub.id) ?? new Set();\n const newMessages = [];\n for (const item of result) {\n if (item && item.source && !currentSeen.has(item.source)) {\n newMessages.push(item.source);\n }\n }\n if (newMessages.length === 0) {\n this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);\n return;\n }\n this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);\n // Resolve parents per new message\n const mentions = [];\n for (const msgAddr of newMessages) {\n const parents = [];\n try {\n const parentQuery = `SELECT ?source WHERE { ?source <ad4m://has_child> <${msgAddr}> . }`;\n this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);\n const parentResult = await this.perspectiveClient.querySparql(sub.perspective, parentQuery);\n const bindings = parentResult?.results?.bindings;\n if (Array.isArray(bindings)) {\n for (const binding of bindings) {\n if (binding?.source?.value) {\n parents.push(binding.source.value);\n }\n }\n }\n }\n catch (err) {\n this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} \u2014 ${err?.message ?? err}`);\n }\n this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(\", \")}`);\n mentions.push({ address: msgAddr, parents });\n }\n // Mark all new messages as seen\n for (const addr of newMessages) {\n currentSeen.add(addr);\n }\n this.seenMessages.set(sub.id, currentSeen);\n // Debounce the wake callback\n const existing = this.debounceTimers.get(sub.id);\n if (existing)\n clearTimeout(existing);\n this.debounceTimers.set(sub.id, setTimeout(() => {\n this.onWake(sub, result, mentions);\n this.debounceTimers.delete(sub.id);\n this.persist();\n }, this.debounceMs));\n }\n else {\n // For channel-messages: always notify the agent on every subscription push.\n // No deduplication \u2014 the agent reads recent messages itself.\n this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);\n const existing = this.debounceTimers.get(sub.id);\n if (existing)\n clearTimeout(existing);\n this.debounceTimers.set(sub.id, setTimeout(() => {\n this.onWake(sub, result);\n this.debounceTimers.delete(sub.id);\n }, this.debounceMs));\n }\n });\n this.proxies.set(sub.id, proxy);\n this.activeSubscriptions.set(sub.id, sub);\n this.persist();\n this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);\n }\n /**\n * Dispose a single subscription.\n * @param persist \u2014 if false, skip calling onPersist (used during batch cleanup).\n */\n dispose(id, persist = true) {\n const proxy = this.proxies.get(id);\n if (proxy) {\n try {\n proxy.dispose();\n }\n catch {\n /* ignore */\n }\n this.proxies.delete(id);\n }\n const timer = this.debounceTimers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.debounceTimers.delete(id);\n }\n this.activeSubscriptions.delete(id);\n this.seenMessages.delete(id);\n if (persist)\n this.persist();\n }\n /** Dispose all active subscriptions. */\n disposeAll() {\n for (const [id] of this.proxies) {\n this.dispose(id, false);\n }\n }\n /** Get all active subscriptions. */\n getActive() {\n return Array.from(this.activeSubscriptions.values());\n }\n /** Check if a subscription exists. */\n has(id) {\n return this.activeSubscriptions.has(id);\n }\n persist() {\n if (this.onPersist) {\n const seen = {};\n for (const [id, set] of this.seenMessages) {\n seen[id] = Array.from(set);\n }\n this.onPersist(this.getActive(), seen);\n }\n }\n}\n\nclass PerspectiveDiff {\n}\nclass PerspectiveDiffExpression extends ExpressionGeneric() {\n}\n\nvar __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _SmartLiteral_perspective, _SmartLiteral_base;\nconst SMART_LITERAL_CONTENT_PREDICATE = \"smart_literal://content\";\nfunction makeRandomStringID(length) {\n let result = '';\n let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let charactersLength = characters.length;\n for (let i = 0; i < length; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nclass SmartLiteral {\n constructor(perspective, base) {\n _SmartLiteral_perspective.set(this, void 0);\n _SmartLiteral_base.set(this, void 0);\n __classPrivateFieldSet(this, _SmartLiteral_perspective, perspective, \"f\");\n __classPrivateFieldSet(this, _SmartLiteral_base, base, \"f\");\n }\n get base() {\n return __classPrivateFieldGet(this, _SmartLiteral_base, \"f\");\n }\n static async create(perspective, literal) {\n const base = Literal.from(makeRandomStringID(10)).toUrl();\n const smartLiteral = new SmartLiteral(perspective, base);\n await smartLiteral.set(literal);\n return smartLiteral;\n }\n static async isSmartLiteralBase(perspective, base) {\n let links = await perspective.get(new LinkQuery({\n source: base,\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n return links.length > 0;\n }\n static async getAllSmartLiterals(perspective) {\n let links = await perspective.get(new LinkQuery({\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n return links.map(link => new SmartLiteral(perspective, link.data.source));\n }\n async get() {\n let link = await __classPrivateFieldGet(this, _SmartLiteral_perspective, \"f\").getSingleTarget(new LinkQuery({\n source: __classPrivateFieldGet(this, _SmartLiteral_base, \"f\"),\n predicate: SMART_LITERAL_CONTENT_PREDICATE\n }));\n if (!link) {\n throw `No content for smart literal ${__classPrivateFieldGet(this, _SmartLiteral_base, \"f\")}`;\n }\n return Literal.fromUrl(link).get();\n }\n async set(content) {\n let literal = Literal.from(content);\n await __classPrivateFieldGet(this, _SmartLiteral_perspective, \"f\").setSingleTarget(new Link({\n source: __classPrivateFieldGet(this, _SmartLiteral_base, \"f\"),\n predicate: SMART_LITERAL_CONTENT_PREDICATE,\n target: literal.toUrl()\n }));\n }\n}\n_SmartLiteral_perspective = new WeakMap(), _SmartLiteral_base = new WeakMap();\n\n/**\n * Shared type definitions for the Ad4mModel system.\n *\n * Extracted into a standalone module so that utility files\n * (`query-utils.ts`, `decorators.ts`, etc.) can import types without\n * creating circular runtime dependencies on `Ad4mModel.ts`.\n */\n/** Type guard for IncludeProjection objects. */\nfunction isIncludeProjection(val) {\n return typeof val === 'object' && val !== null && 'from' in val;\n}\n\nclass Neighbourhood {\n constructor(linkLanguage, meta) {\n this.linkLanguage = linkLanguage;\n this.meta = meta;\n }\n}\nclass NeighbourhoodExpression extends ExpressionGeneric() {\n}\n\n// Placeholder for type definition string.\n// Previously generated by buildSchema; kept for backward compatibility.\nconst typeDefsString = \"\";\n\nclass ModelApi {\n}\nclass TokenizerSource {\n}\nclass LocalModel {\n}\nclass Model {\n}\nclass ModelApiInput {\n}\nclass TokenizerSourceInput {\n}\nclass LocalModelInput {\n}\nclass ModelInput {\n}\nclass VoiceActivityParamsInput {\n}\n\nexport { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };\n", "// Gets all non-builtin properties up the prototype chain.\nconst getAllProperties = object => {\n\tconst properties = new Set();\n\n\tdo {\n\t\tfor (const key of Reflect.ownKeys(object)) {\n\t\t\tproperties.add([object, key]);\n\t\t}\n\t} while ((object = Reflect.getPrototypeOf(object)) && object !== Object.prototype);\n\n\treturn properties;\n};\n\nexport default function autoBind(self, {include, exclude} = {}) {\n\tconst filter = key => {\n\t\tconst match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);\n\n\t\tif (include) {\n\t\t\treturn include.some(match); // eslint-disable-line unicorn/no-array-callback-reference\n\t\t}\n\n\t\tif (exclude) {\n\t\t\treturn !exclude.some(match); // eslint-disable-line unicorn/no-array-callback-reference\n\t\t}\n\n\t\treturn true;\n\t};\n\n\tfor (const [object, key] of getAllProperties(self.constructor.prototype)) {\n\t\tif (key === 'constructor' || !filter(key)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n\t\tif (descriptor && typeof descriptor.value === 'function') {\n\t\t\tself[key] = self[key].bind(self);\n\t\t}\n\t}\n\n\treturn self;\n}\n", "import type { RemoteHost, UserInfo } from '../types';\nimport type { Ad4mClient } from '@coasys/ad4m';\n\nconst DEFAULT_INDEX_URL = \"https://hosting.ad4m.dev\";\n\nfunction isAbsoluteUrl(value: string): boolean {\n try {\n // If this doesn't throw, it's an absolute URL\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\n// --- Public API ---\n\n/** Fetch available hosts from the central index API */\nexport async function fetchHosts(indexUrl?: string): Promise<RemoteHost[]> {\n const url = indexUrl || DEFAULT_INDEX_URL;\n const res = await fetch(`${url}/hosts`);\n if (!res.ok) throw new Error(`Failed to fetch hosts: ${res.status}`);\n const hosts: RemoteHost[] = await res.json();\n // Resolve relative profile image URLs against the index API base URL\n for (const host of hosts) {\n if (host.profilePicUrl && !isAbsoluteUrl(host.profilePicUrl)) {\n host.profilePicUrl = new URL(host.profilePicUrl, url).toString();\n }\n }\n return hosts;\n}\n\n/** Fetch current user info from the executor */\nexport async function fetchUserInfo(ad4mClient: Ad4mClient): Promise<UserInfo> {\n const info = await ad4mClient.agent.hostingUserInfo();\n return {\n email: info.email,\n remainingCredits: info.remainingCredits === \"unlimited\" ? Infinity : (parseFloat(info.remainingCredits) || 0),\n hotWalletAddress: info.hotWalletAddress || null,\n freeAccess: info.freeAccess,\n };\n}\n\n/** Trigger a payment request via the executor */\nexport async function requestPayment(\n ad4mClient: Ad4mClient,\n amountHOT: number\n): Promise<{ success: boolean; message: string }> {\n return ad4mClient.agent.requestPayment(amountHOT.toString());\n}\n", "import { isEmbedded, setLocal, getLocal, removeLocal, checkConnection, wsUrlToHttpBase } from './utils';\nimport { PostMessageWebSocket } from './PostMessageWebSocket';\nimport { Ad4mClient, VerificationRequestResult } from \"@coasys/ad4m\";\nimport autoBind from \"auto-bind\";\n\nimport { Ad4mConnectOptions, ConnectionStates, AuthStates, ConfigStates, RemoteHost, UserInfo } from './types';\nimport { fetchUserInfo, requestPayment } from './services/hostIndex';\n\nconst DEFAULT_PORT = 12000;\nconst DEFAULT_INDEX_URL = \"https://hosting.ad4m.dev\";\nconst CREDIT_POLL_INTERVAL_MS = 60000;\nconst DEFAULT_LOW_CREDIT_THRESHOLD = 10;\n\nexport default class Ad4mConnect extends EventTarget {\n options: Ad4mConnectOptions;\n embedded: boolean;\n port: number;\n url: string;\n token: string;\n connectionState: ConnectionStates = \"not-connected\";\n authState: AuthStates = \"unauthenticated\";\n ad4mClient?: Ad4mClient;\n /** HTTP base URL (normalizes legacy ws:// URLs from localStorage) */\n get baseUrl(): string {\n return wsUrlToHttpBase(this.url);\n }\n\n requestId?: string;\n requestedRestart: boolean = false;\n\n // Hosting state\n connectedHost: RemoteHost | null = null;\n userInfo: UserInfo | null = null;\n hostIndexUrl: string;\n lowCreditThreshold: number;\n private creditPollInterval: ReturnType<typeof setInterval> | null = null;\n\n private embeddedResolve?: (client: Ad4mClient) => void;\n private embeddedReject?: (error: Error) => void;\n\n constructor(options: Ad4mConnectOptions) {\n super();\n autoBind(this);\n \n this.options = options;\n this.port = options.port || parseInt(getLocal(\"ad4m-port\")) || DEFAULT_PORT\n this.url = options.url || getLocal(\"ad4m-url\") || `http://localhost:${this.port}`;\n this.token = getLocal(\"ad4m-token\") || '';\n this.embedded = isEmbedded();\n this.hostIndexUrl = options.hostIndexUrl || DEFAULT_INDEX_URL;\n this.lowCreditThreshold = options.lowCreditThreshold ?? DEFAULT_LOW_CREDIT_THRESHOLD;\n\n // Restore last connected host for UI pinning\n const lastHost = getLocal(\"ad4m-last-host\");\n if (lastHost) {\n try {\n const parsed = JSON.parse(lastHost);\n if (parsed && parsed.id && parsed.url && parsed.name) {\n this.connectedHost = {\n id: parsed.id,\n name: parsed.name,\n profilePicUrl: parsed.profilePicUrl || \"\",\n location: parsed.location || \"\",\n url: parsed.url,\n rates: parsed.rates || [],\n aiModels: parsed.aiModels || [],\n };\n }\n } catch { /* ignore corrupt data */ }\n }\n\n if (this.embedded) this.initializeEmbeddedMode();\n }\n\n // Core connection flow\n async connect(): Promise<Ad4mClient> {\n // In embedded mode, wait for postMessage from parent instead of connecting\n if (this.embedded) {\n console.log('[Ad4m Connect] Embedded mode - waiting for AD4M config via postMessage');\n \n return new Promise((resolve, reject) => {\n // The 30-second timeout only guards waiting for AD4M_CONFIG_ACK \u2014 the parent\n // acknowledging that it received our request and is alive. Once the ACK arrives\n // we know auth is in progress and we wait indefinitely for the actual AD4M_CONFIG\n // (the user may take several minutes to complete the auth flow).\n const ackTimeout = setTimeout(() => {\n window.removeEventListener('message', handleAck);\n reject(new Error('Timeout waiting for AD4M_CONFIG_ACK from parent window (is the app running inside we-web?)'));\n }, 30000);\n\n const handleAck = (event: MessageEvent) => {\n if (event.data?.type === 'AD4M_CONFIG_ACK' && event.source === window.parent) {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Received AD4M_CONFIG_ACK \u2014 parent is alive, waiting for config after auth');\n }\n };\n window.addEventListener('message', handleAck);\n\n // Store resolvers to call when AD4M_CONFIG arrives (via initializeEmbeddedMode listener)\n this.embeddedResolve = (client: Ad4mClient) => {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Successfully connected in embedded mode');\n resolve(client);\n };\n \n this.embeddedReject = (error: Error) => {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n reject(error);\n };\n \n // If we already have a client (message arrived before connect() was called)\n if (this.ad4mClient) {\n if (this.authState === 'authenticated') {\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n console.log('[Ad4m Connect] Client already initialized in embedded mode');\n resolve(this.ad4mClient);\n } else {\n // Auth already failed before connect() was called\n clearTimeout(ackTimeout);\n window.removeEventListener('message', handleAck);\n reject(new Error(`Embedded auth state: ${this.authState}`));\n }\n }\n });\n }\n\n // Standalone mode - connect directly\n try {\n await checkConnection(this.baseUrl);\n setLocal(\"ad4m-url\", this.url);\n this.ad4mClient = this.buildClient();\n await this.checkAuth();\n return this.ad4mClient;\n } catch (error) {\n console.error('[Ad4m Connect] Connection failed:', error);\n this.notifyConnectionChange(\"error\");\n throw error;\n }\n }\n\n private buildClient(): Ad4mClient {\n this.notifyConnectionChange(\"connecting\");\n\n // Close old client's WebSocket connections to avoid connection pool exhaustion\n if (this.ad4mClient && typeof this.ad4mClient.close === 'function') {\n this.ad4mClient.close();\n }\n\n // Defer subscriptions until auth is verified to avoid 403 spam\n this.ad4mClient = new Ad4mClient(this.baseUrl, this.token, false);\n this.notifyConnectionChange(\"connected\");\n\n return this.ad4mClient;\n }\n\n private async withTempClient<T>(wsUrl: string, callback: (client: Ad4mClient) => Promise<T>): Promise<T> {\n const baseUrl = wsUrlToHttpBase(wsUrl);\n const client = new Ad4mClient(baseUrl, undefined, false);\n try {\n return await callback(client);\n } finally {\n client.close();\n }\n }\n\n async checkAuth(): Promise<boolean> {\n try {\n console.log('[Ad4m Connect] Checking authentication status...');\n\n // isLocked may not exist on older executors (404). Treat errors\n // as \"not locked\" and fall through to the status check.\n let isLocked = false;\n try {\n isLocked = await this.ad4mClient.agent.isLocked();\n } catch (lockErr) {\n const msg = lockErr?.message || '';\n if (msg === \"Cannot extractByTags from a ciphered wallet. You must unlock first.\") {\n console.log('[Ad4m Connect] Agent wallet is locked (error path)');\n this.notifyAuthChange(\"locked\");\n return true;\n }\n // 404 / network error \u2192 assume not locked\n console.warn('[Ad4m Connect] isLocked check unavailable, assuming unlocked:', msg);\n }\n\n if (isLocked) {\n console.log('[Ad4m Connect] Agent wallet is locked');\n this.notifyAuthChange(\"locked\");\n } else {\n await this.ad4mClient.agent.status();\n this.ad4mClient.startSubscriptions();\n this.notifyAuthChange(\"authenticated\");\n }\n\n return true;\n } catch (error) {\n console.error('[Ad4m Connect] Authentication check failed:', error);\n \n // Clear token if it's invalid (signed by different agent)\n if (error.message === \"InvalidSignature\") {\n console.log('[Ad4m Connect] Clearing invalid token due to InvalidSignature');\n this.token = '';\n removeLocal('ad4m-token');\n }\n \n this.notifyAuthChange(\"unauthenticated\");\n return false;\n }\n }\n\n // Disconnect and clean up\n async disconnect(): Promise<void> {\n console.log('[Ad4m Connect] Disconnecting...');\n \n // Clear client reference\n this.ad4mClient = undefined;\n \n // Clear token\n this.token = '';\n removeLocal('ad4m-token');\n \n // Update auth state (will trigger authstatechange event)\n this.notifyAuthChange('unauthenticated');\n \n // Clear hosting state\n this.connectedHost = null;\n this.userInfo = null;\n this.stopCreditPolling();\n removeLocal('ad4m-last-host');\n\n // Update connection state\n this.notifyConnectionChange('not-connected');\n \n console.log('[Ad4m Connect] Disconnected successfully');\n }\n\n // Hosting \u2014 credit subscription & polling fallback\n\n /**\n * Subscribe to real-time credit updates.\n * Falls back to polling if the subscription is not supported by the executor.\n */\n startCreditSubscription(): void {\n if (!this.ad4mClient) return;\n\n try {\n this.ad4mClient.agent.addHostingUserInfoChangedListener((info) => {\n const userInfo: UserInfo = {\n email: info.email,\n remainingCredits: info.remainingCredits === 'unlimited' ? Infinity : (parseFloat(info.remainingCredits) || 0),\n hotWalletAddress: info.hotWalletAddress || null,\n freeAccess: info.freeAccess,\n };\n this.userInfo = userInfo;\n this.dispatchEvent(new CustomEvent('userinfochange', { detail: userInfo }));\n\n if (!userInfo.freeAccess && userInfo.remainingCredits <= 0) {\n this.dispatchEvent(new CustomEvent('creditdepleted'));\n }\n if (!userInfo.freeAccess && userInfo.remainingCredits <= this.lowCreditThreshold) {\n this.dispatchEvent(new CustomEvent('creditlow'));\n }\n });\n this.ad4mClient.agent.subscribeHostingUserInfoChanged();\n } catch (e) {\n console.warn('[Ad4m Connect] Subscription not available, falling back to polling:', e);\n }\n\n // Subscribe to compute log updates for real-time activity log\n try {\n this.ad4mClient.agent.addComputeLogUpdatedListener((entry) => {\n this.dispatchEvent(new CustomEvent('computelogentry', { detail: entry }));\n });\n this.ad4mClient.agent.subscribeComputeLogUpdated();\n } catch (e) {\n console.warn('[Ad4m Connect] Compute log subscription not available:', e);\n }\n\n // Always start polling as a safety-net (at a longer 60s interval)\n this.startCreditPolling();\n }\n\n startCreditPolling(): void {\n this.stopCreditPolling();\n\n const poll = async () => {\n try {\n if (!this.ad4mClient) return;\n const info = await fetchUserInfo(this.ad4mClient);\n this.userInfo = info;\n this.dispatchEvent(new CustomEvent('userinfochange', { detail: info }));\n\n if (!info.freeAccess && info.remainingCredits <= this.lowCreditThreshold) {\n this.dispatchEvent(new CustomEvent('creditlow'));\n }\n if (!info.freeAccess && info.remainingCredits <= 0) {\n this.dispatchEvent(new CustomEvent('creditdepleted'));\n }\n } catch (error) {\n console.error('[Ad4m Connect] Credit polling error:', error);\n }\n };\n\n // Immediate first poll, then every 30s\n poll();\n this.creditPollInterval = setInterval(poll, CREDIT_POLL_INTERVAL_MS);\n }\n\n stopCreditPolling(): void {\n if (this.creditPollInterval) {\n clearInterval(this.creditPollInterval);\n this.creditPollInterval = null;\n }\n }\n\n async requestTopUp(amountHOT: number): Promise<{ success: boolean; message: string }> {\n if (!this.ad4mClient) throw new Error('Not connected');\n return requestPayment(this.ad4mClient, amountHOT);\n }\n\n /** Fetch recent compute log entries. */\n async fetchComputeLog(since?: string, limit?: number): Promise<import('./types').ComputeLogEntryData[]> {\n if (!this.ad4mClient) throw new Error('Not connected');\n return this.ad4mClient.agent.computeLog(since, limit) as any;\n }\n\n /** Persist selected host after successful auth */\n setConnectedHost(host: RemoteHost): void {\n this.connectedHost = host;\n setLocal('ad4m-last-host', JSON.stringify({ id: host.id, url: host.url, name: host.name, location: host.location }));\n }\n\n // Embedded mode\n private initializeEmbeddedMode(): void {\n console.log('[Ad4m Connect] Running in embedded mode - waiting for AD4M config from parent');\n \n // Set up listener for AD4M_CONFIG from parent window\n window.addEventListener('message', async (event: MessageEvent) => {\n if (event.data?.type === 'AD4M_CONFIG') {\n // Security checks: verify sender\n if (event.source !== window.parent) {\n console.warn('[Ad4m Connect] Rejected AD4M_CONFIG from invalid source (not parent window)');\n return;\n }\n\n // Verify origin is in allowlist (if configured)\n if (this.options.allowedOrigins && this.options.allowedOrigins.length > 0) {\n if (!event.origin || !this.options.allowedOrigins.includes(event.origin)) {\n console.warn('[Ad4m Connect] Rejected AD4M_CONFIG from unauthorized origin:', event.origin);\n this.rejectEmbedded(new Error(`Unauthorized origin: ${event.origin}`));\n return;\n }\n }\n\n console.log('[Ad4m Connect] Received AD4M_CONFIG from parent:', { port: event.data.port, hasToken: !!event.data.token, proxy: !!event.data.proxy });\n \n // Validate and normalize token (optional but must be string if present)\n const { token: rawToken } = event.data;\n const normalizedToken = rawToken !== undefined && rawToken !== null && typeof rawToken === 'string' \n ? rawToken \n : '';\n\n // \u2500\u2500 Proxy mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Parent sends proxy: true when the host application will open the real\n // WebSocket to the AD4M daemon and proxy frames via postMessage.\n // The URL/port fields are not needed in this path.\n if (event.data.proxy) {\n try {\n this.token = normalizedToken;\n if (normalizedToken) {\n setLocal('ad4m-token', normalizedToken);\n } else {\n removeLocal('ad4m-token');\n }\n\n this.notifyConnectionChange('connecting');\n this.ad4mClient = new Ad4mClient(\n 'http://proxy', // URL ignored by PostMessageWebSocket\n normalizedToken,\n false, // defer subscriptions until auth confirmed\n { webSocketImpl: PostMessageWebSocket as unknown as new (url: string) => WebSocket }\n );\n this.notifyConnectionChange('connected');\n await this.checkAuth();\n } catch (error) {\n console.error('[Ad4m Connect] Failed to initialize proxy client from AD4M_CONFIG:', error);\n this.rejectEmbedded(error as Error);\n }\n return;\n }\n\n // \u2500\u2500 Direct mode (desktop / local where PNA is not an issue) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Validate and normalize port\n const { port: rawPort } = event.data;\n\n if (rawPort === undefined || rawPort === null) {\n const error = new Error('AD4M_CONFIG missing required field: port');\n console.error('[Ad4m Connect]', error.message);\n this.rejectEmbedded(error);\n return;\n }\n \n const parsedPort = parseInt(rawPort, 10);\n if (!Number.isFinite(parsedPort) || parsedPort <= 0) {\n const error = new Error(`AD4M_CONFIG invalid port: ${rawPort} (must be a positive integer)`);\n console.error('[Ad4m Connect]', error.message);\n this.rejectEmbedded(error);\n return;\n }\n \n try {\n // Set connection details from parent (after successful validation)\n this.port = parsedPort;\n this.token = normalizedToken;\n // Use the URL provided by the parent if valid (e.g. remote host), otherwise fall back to localhost\n const rawUrl = event.data.url;\n this.url = (rawUrl && typeof rawUrl === 'string' && rawUrl.startsWith('http'))\n ? rawUrl\n : `http://localhost:${parsedPort}`;\n \n // Store in localStorage for persistence (avoid storing undefined or stale credentials)\n setLocal('ad4m-port', parsedPort.toString());\n if (normalizedToken) {\n setLocal('ad4m-token', normalizedToken);\n } else {\n // Explicitly clear stale token when absent/invalid to prevent reuse on reload\n removeLocal('ad4m-token');\n }\n setLocal('ad4m-url', this.url);\n \n // Build the client with received credentials\n this.ad4mClient = this.buildClient();\n await this.checkAuth();\n } catch (error) {\n console.error('[Ad4m Connect] Failed to initialize from AD4M_CONFIG:', error);\n this.rejectEmbedded(error as Error);\n }\n }\n });\n \n // Request AD4M config from parent window\n console.log('[Ad4m Connect] Requesting AD4M config from parent window');\n // Determine the actual parent origin for postMessage targeting.\n // Prefer document.referrer (the real parent), validated against allowedOrigins.\n // Fall back to '*' only when no origin information is available.\n let parentOrigin = '*';\n const referrerOrigin = document.referrer ? new URL(document.referrer).origin : null;\n if (referrerOrigin && this.options.allowedOrigins?.includes(referrerOrigin)) {\n parentOrigin = referrerOrigin;\n } else if (this.options.allowedOrigins && this.options.allowedOrigins.length === 1) {\n parentOrigin = this.options.allowedOrigins[0];\n }\n window.parent.postMessage({ type: 'REQUEST_AD4M_CONFIG' }, parentOrigin);\n }\n\n // Local authentication\n private buildAppInfo() {\n return {\n appName: this.options.appInfo.name,\n appDesc: this.options.appInfo.description,\n appDomain: this.options.appInfo.url,\n appUrl: window.location.origin,\n appIconPath: this.options.appInfo.iconPath,\n };\n }\n\n async requestCapability(invalidateToken = false): Promise<string> {\n if (invalidateToken) {\n this.token = '';\n removeLocal('ad4m-token');\n this.notifyConfigChange(\"token\", this.token);\n }\n\n this.requestId = await this.ad4mClient.agent.requestCapability({\n appName: this.options.appInfo.name,\n appDesc: this.options.appInfo.description,\n appUrl: this.options.appInfo.url,\n appDomain: this.options.appInfo.url,\n appIconPath: this.options.appInfo.iconPath,\n capabilities: this.options.capabilities,\n });\n\n return this.requestId;\n }\n\n async verifyLocalAd4mCode(code: string): Promise<boolean> {\n if (!this.requestId) {\n console.error('[Ad4m Connect] Cannot verify code: requestId is missing. Call requestCapability() first to obtain a requestId.');\n return false;\n }\n\n try {\n const jwt = await this.ad4mClient.agent.generateJwt(this.requestId, code);\n this.token = jwt;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (error) {\n console.error('[Ad4m Connect] Code verification failed:', error);\n return false;\n }\n }\n\n // Remote authentication\n async isValidAd4mAPI(): Promise<boolean> {\n try {\n await this.withTempClient(this.url, async (client) => await client.runtime.info());\n return true;\n } catch (error) {\n console.error(\"[Ad4m Connect] Failed to verify AD4M API:\", error);\n return false;\n }\n }\n\n async isMultiUser(): Promise<boolean> {\n try {\n return await this.withTempClient(this.url, async (client) => await client.runtime.multiUserEnabled());\n } catch (error) {\n console.error(\"[Ad4m Connect] Failed to detect multi-user mode:\", error);\n // If multi-user query fails, assume single-user mode\n return false;\n }\n }\n\n async submitEmail(email: string): Promise<VerificationRequestResult> {\n try {\n return await this.withTempClient(this.url, async (client) => await client.agent.requestLoginVerification(email, this.buildAppInfo()));\n } catch (e) {\n const errorMessage = (e as Error).message || \"Failed to process email. Please try again.\";\n return { success: false, message: errorMessage, requiresPassword: false, isExistingUser: false };\n }\n }\n\n async verifyEmailCode(email: string, code: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => await client.agent.verifyEmailCode(email, code, \"login\"));\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Email code verification failed:\", e);\n return false;\n }\n }\n\n async loginWithPassword(email: string, password: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => await client.agent.loginUser(email, password));\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Password login failed:\", e);\n return false;\n }\n }\n\n async createAccount(email: string, password: string): Promise<boolean> {\n try {\n const token = await this.withTempClient(this.url, async (client) => {\n const result = await client.agent.createUser(email, password);\n // If creation successful, log in the new user\n if (result.success) return await client.agent.loginUser(email, password);\n // Otherwise, throw an error with the failure message\n else throw new Error(result.error || \"Failed to create account\");\n });\n\n this.token = token;\n setLocal(\"ad4m-token\", this.token);\n await this.connect();\n return true;\n } catch (e) {\n console.error(\"[Ad4m Connect] Account creation error:\", e);\n return false;\n }\n }\n\n // Private helpers\n private resolveEmbedded(client: Ad4mClient): void {\n if (this.embeddedResolve) {\n this.embeddedResolve(client);\n this.embeddedResolve = undefined;\n this.embeddedReject = undefined;\n }\n }\n\n private rejectEmbedded(error: Error): void {\n if (this.embeddedReject) {\n this.embeddedReject(error);\n this.embeddedResolve = undefined;\n this.embeddedReject = undefined;\n }\n }\n\n private notifyConnectionChange(value: ConnectionStates) {\n if (this.connectionState === value) return;\n this.connectionState = value;\n this.dispatchEvent(new CustomEvent(\"connectionstatechange\", { detail: value }));\n }\n\n private notifyAuthChange(value: AuthStates) {\n this.authState = value;\n this.dispatchEvent(new CustomEvent(\"authstatechange\", { detail: value }));\n\n // In embedded mode, handle connect() promise resolution/rejection\n if (this.embedded) {\n // Resolve when authenticated\n if (value === \"authenticated\") {\n this.resolveEmbedded(this.ad4mClient);\n }\n \n // Reject on failing auth states\n if (value === \"unauthenticated\" || value === \"locked\") {\n const errorMessage = value === \"locked\" \n ? \"Authentication failed: Agent is locked\"\n : \"Authentication failed: Unauthenticated\";\n this.rejectEmbedded(new Error(errorMessage));\n }\n }\n }\n\n private notifyConfigChange(type: ConfigStates, value: string) {\n this.dispatchEvent(new CustomEvent(\"configstatechange\", { detail: { type, value } }));\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,aAAsB;AACpC,SAAO,OAAO,WAAW,eAAe,OAAO,SAAS,OAAO;AACjE;AAEA,SAAS,wBAAiC;AACxC,MAAI;AACF,iBAAa,QAAQ,QAAQ,EAAE;AAC/B,iBAAa,WAAW,MAAM;AAAA,EAChC,SAAS,GAAP;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,SAAS,SAAS,KAAa,OAAqB;AACzD,MAAI,sBAAsB;AAAG,iBAAa,QAAQ,GAAG,WAAW,OAAO,KAAK;AAC9E;AAEO,SAAS,SAAS,KAA4B;AACnD,MAAI,sBAAsB;AAAG,WAAO,aAAa,QAAQ,GAAG,WAAW,KAAK;AAC5E,SAAO;AACT;AAEO,SAAS,YAAY,KAAmB;AAC7C,MAAI,sBAAsB;AAAG,iB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CAAC,CAAC;AAGxE,QAAI,KAAK,UAAU;AAEjB,UAAI,UAAU,iBAAiB;AAC7B,aAAK,gBAAgB,KAAK,UAAU;AAAA,MACtC;AAGA,UAAI,UAAU,qBAAqB,UAAU,UAAU;AACrD,cAAM,eAAe,UAAU,WAC3B,2CACA;AACJ,aAAK,eAAe,IAAI,MAAM,YAAY,CAAC;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,mBAAmB,MAAoB,OAAe;AAC5D,SAAK,cAAc,IAAI,YAAY,qBAAqB,EAAE,QAAQ,EAAE,MAAM,MAAM,EAAE,CAAC,CAAC;AAAA,EACtF;AACF;",
6
+ "names": ["code", "err", "result", "_QuerySubscriptionProxy_notifyCallbacks", "code", "_IDBCache_open", "_ExpressionClient_memCacheResult", "rank", "normalizedNs", "results", "totalCount", "ExceptionType", "PerspectiveState", "_a", "code"]
7
+ }