@fragno-dev/project-connector-fragment 0.0.0-stage → 0.0.1

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 (77) hide show
  1. package/LICENSE.md +16 -0
  2. package/README.md +285 -2
  3. package/bin/run.js +4 -0
  4. package/dist/browser/client/react.d.ts +174 -0
  5. package/dist/browser/client/react.d.ts.map +1 -0
  6. package/dist/browser/client/react.js +195 -0
  7. package/dist/browser/client/react.js.map +1 -0
  8. package/dist/browser/client/solid.d.ts +177 -0
  9. package/dist/browser/client/solid.d.ts.map +1 -0
  10. package/dist/browser/client/solid.js +130 -0
  11. package/dist/browser/client/solid.js.map +1 -0
  12. package/dist/browser/client/svelte.d.ts +177 -0
  13. package/dist/browser/client/svelte.d.ts.map +1 -0
  14. package/dist/browser/client/svelte.js +132 -0
  15. package/dist/browser/client/svelte.js.map +1 -0
  16. package/dist/browser/client/vanilla.d.ts +204 -0
  17. package/dist/browser/client/vanilla.d.ts.map +1 -0
  18. package/dist/browser/client/vanilla.js +160 -0
  19. package/dist/browser/client/vanilla.js.map +1 -0
  20. package/dist/browser/client/vue.d.ts +177 -0
  21. package/dist/browser/client/vue.d.ts.map +1 -0
  22. package/dist/browser/client/vue.js +128 -0
  23. package/dist/browser/client/vue.js.map +1 -0
  24. package/dist/browser/client-BCzNDSlW.d.ts +711 -0
  25. package/dist/browser/client-BCzNDSlW.d.ts.map +1 -0
  26. package/dist/browser/index.d.ts +504 -0
  27. package/dist/browser/index.d.ts.map +1 -0
  28. package/dist/browser/index.js +2 -0
  29. package/dist/browser/src-CSPQuoKz.js +2286 -0
  30. package/dist/browser/src-CSPQuoKz.js.map +1 -0
  31. package/dist/cli/authorization-browser.js +20 -0
  32. package/dist/cli/authorization-browser.js.map +1 -0
  33. package/dist/cli/cli.d.ts +6 -0
  34. package/dist/cli/cli.d.ts.map +1 -0
  35. package/dist/cli/cli.js +258 -0
  36. package/dist/cli/cli.js.map +1 -0
  37. package/dist/cli/definition.js +13 -0
  38. package/dist/cli/definition.js.map +1 -0
  39. package/dist/cli/index.js +14 -0
  40. package/dist/cli/index.js.map +1 -0
  41. package/dist/cli/project-connector-client.js +235 -0
  42. package/dist/cli/project-connector-client.js.map +1 -0
  43. package/dist/cli/project-connector-contracts.js +125 -0
  44. package/dist/cli/project-connector-contracts.js.map +1 -0
  45. package/dist/cli/routes.js +449 -0
  46. package/dist/cli/routes.js.map +1 -0
  47. package/dist/cli/schema.js +18 -0
  48. package/dist/cli/schema.js.map +1 -0
  49. package/dist/node/definition.d.ts +170 -0
  50. package/dist/node/definition.d.ts.map +1 -0
  51. package/dist/node/definition.js +13 -0
  52. package/dist/node/definition.js.map +1 -0
  53. package/dist/node/index.d.ts +456 -0
  54. package/dist/node/index.d.ts.map +1 -0
  55. package/dist/node/index.js +36 -0
  56. package/dist/node/index.js.map +1 -0
  57. package/dist/node/project-connector-client.d.ts +13 -0
  58. package/dist/node/project-connector-client.d.ts.map +1 -0
  59. package/dist/node/project-connector-client.js +235 -0
  60. package/dist/node/project-connector-client.js.map +1 -0
  61. package/dist/node/project-connector-contracts.d.ts +179 -0
  62. package/dist/node/project-connector-contracts.d.ts.map +1 -0
  63. package/dist/node/project-connector-contracts.js +125 -0
  64. package/dist/node/project-connector-contracts.js.map +1 -0
  65. package/dist/node/routes.d.ts +307 -0
  66. package/dist/node/routes.d.ts.map +1 -0
  67. package/dist/node/routes.js +449 -0
  68. package/dist/node/routes.js.map +1 -0
  69. package/dist/node/schema.d.ts +49 -0
  70. package/dist/node/schema.d.ts.map +1 -0
  71. package/dist/node/schema.js +18 -0
  72. package/dist/node/schema.js.map +1 -0
  73. package/dist/node/testing/project-connector-test-gateway.d.ts +63 -0
  74. package/dist/node/testing/project-connector-test-gateway.d.ts.map +1 -0
  75. package/dist/node/testing/project-connector-test-gateway.js +370 -0
  76. package/dist/node/testing/project-connector-test-gateway.js.map +1 -0
  77. package/package.json +111 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-CSPQuoKz.js","names":["extractPathParams","pathPattern","segments","split","filter","s","length","names","segment","startsWith","push","slice","buildPath","params","patternSegments","builtSegments","name","value","Error","encodeURIComponent","join","isBinaryRequestBody","body","ReadableStream","Blob","ArrayBuffer","isView","containsFileBody","value","File","FormData","Object","values","some","entry","appendFormDataValue","formData","key","append","name","JSON","stringify","prepareMultipartBody","entries","TypeError","prepareRouteRequestBody","contentType","prepareClientRequestBody","prepareInferredRequestBody","URLSearchParams","applyPreparedRequestBodyContentType","headers","preparedBody","delete","set","createRequestInitWithBody","method","options","requestInit","duplex","getMountRoute","opts","mountRoute","name","endsWith","slice","FragnoApiError","Error","status","code","constructor","message","name","toResponse","Response","json","FragnoApiValidationError","issues","FragnoApiValidationError","RequestInputContext","path","method","pathParams","searchParams","headers","body","request","parsedBody","inputSchema","shouldValidateInput","constructor","config","rawBody","fromRequest","state","fromSSRContext","URLSearchParams","Headers","query","formData","FormData","Error","isFormData","bodyStream","ReadableStream","isBodyStream","input","schema","valid","validateInput","#validateInput","Blob","result","validate","issues","value","ResponseStream","writer","encoder","abortSubscribers","responseReadable","aborted","abortPromise","closed","constructor","writable","readable","getWriter","TextEncoder","reader","getReader","push","cancel","ReadableStream","pull","controller","done","value","read","close","enqueue","abort","writeRaw","input","encode","write","JSON","stringify","sleep","ms","Promise","resolve","setTimeout","onAbort","listener","allSettled","map","subscriber","then","results","errors","result","status","reason","length","AggregateError","ResponseStream","mergeHeaders","headerSources","mergedHeaders","Headers","headerSource","key","value","entries","set","Array","isArray","Object","OutputContext","runJsonStreamCallback","constructor","options","error","message","code","initOrStatus","headers","Response","json","status","empty","defaultHeaders","object","jsonStream","cb","onError","readable","writable","TransformStream","stream","runStreamCallback","e","Error","console","close","Promise","resolve","catch","responseReadable","RequestOutputContext","outputSchema","resolveRouteFactories","context","routesOrFactories","routes","item","factoryRoutes","push","defineRoute","config","defineRoutes","_definition","create","fn","ctx","parseContentType","contentType","trimmed","trim","parts","split","map","part","mediaType","typeParts","length","type","subtype","toLowerCase","parameters","i","param","equalIndex","indexOf","key","slice","value","startsWith","endsWith","unwrapAtom","value","get","unwrapObject","params","Object","fromEntries","entries","map","key","isReadableAtom","lc","notify","off","subscribe","tasks","resolves","startTask","prevResolves","i","task","cb","endTask","promise","finally","t","allTasks","Promise","resolve","push","cleanTasks","cleanTasks","clean","Symbol","cleanStores","stores","process","env","NODE_ENV","Error","$store","mocked","clean","listenerQueue","lqIndex","QUEUE_ITEMS_PER_LISTENER","nanostoresGlobal","globalThis","epoch","atom","initialValue","listeners","$atom","get","lc","listen","value","init","listener","push","i","length","splice","index","indexOf","off","notify","oldValue","changedKey","runListenerQueue","set","newValue","subscribe","unbind","process","env","NODE_ENV","readonlyType","store","clean","START","STOP","SET","NOTIFY","MOUNT","UNMOUNT","REVERT_MUTATION","on","object","listener","eventKey","mutateStore","events","eventProps","reduceRight","event","l","shared","push","currentListeners","index","indexOf","splice","length","onStart","$store","runListeners","originListen","listen","arg","lc","starting","onStop","originOff","off","onSet","originSet","set","originSetKey","setKey","changed","changedValue","isAborted","abort","newValue","value","onNotify","originNotify","notify","oldValue","STORE_UNMOUNT_DELAY","onMount","initialize","payload","destroy","args","active","setTimeout","process","env","NODE_ENV","originClean","warned","warn","text","console","groupCollapsed","trace","groupEnd","atom","nanostoresGlobal","onMount","warn","computedStore","stores","cb","batched","Array","isArray","previousArgs","currentEpoch","set","epoch","args","map","$store","get","some","arg","i","value","then","t","process","env","NODE_ENV","asyncValue","$computed","undefined","timer","run","clearTimeout","setTimeout","unbinds","listen","unbind","computed","fn","atom","map","initial","$map","setKey","key","value","oldMap","notify","allTasks","stores","getStores","addStore","store","push","cleanStores","clientInitialData","hydrateFromWindow","window","__FRAGNO_INITIAL_DATA__","Map","console","warn","Array","from","entries","getInitialData","key","has","data","get","delete","listenToStores","listen","getFinalStoreValues","storesInitialValue","value","loading","set","FragnoClientError","Error","code","constructor","message","options","cause","name","FragnoClientFetchError","fromUnknownFetchError","error","FragnoClientFetchNetworkError","FragnoClientFetchAbortError","FragnoClientUnknownApiError","status","FragnoClientApiError","fromResponse","response","unknown","json","mergeFetcherConfigs","authorConfig","userConfig","type","authorOpts","options","userOpts","Object","keys","length","headers","mergeHeaders","author","user","merged","Headers","forEach","value","key","set","next","done","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientUnknownApiError","createAbortPromise","abortSignal","Promise","_","reject","abortHandler","aborted","addEventListener","once","parseNdjsonBuffer","buffer","options","lines","split","trailingBuffer","flush","pop","index","length","line","trim","jsonObject","JSON","parse","parseError","parseErrorStatus","cause","onItem","remainingLines","slice","stopped","join","handleNdjsonStreamingFirstItem","response","store","body","decoder","TextDecoder","reader","getReader","firstItem","items","releaseLock","done","value","race","read","decode","stream","push","streamingPromise","continueStreaming","error","setError","clientError","initialBuffer","appendItem","setData","createNanoEvents","emit","event","args","callbacks","events","i","length","on","cb","push","filter","map","onStart","onStop","atom","batched","startTask","createNanoEvents","defaultOnErrorRetry","retryCount","Math","random","nanoqueryFactory","isAppVisible","visibilityChangeSubscribe","reconnectChangeSubscribe","nanoquery","cache","Map","fetcher","globalFetcher","globalSettings","events","focus","emit","FOCUS","RECONNECT","_revalidateOnInterval","_errorInvalidateTimeouts","_runningFetches","rewrittenSettings","getCachedValueByKey","key","fromCache","get","cacheHit","expires","getNow","data","error","runFetcher","keyParts","store","settings","set","v","SET_CACHE","setAsLoading","prev","toSet","loading","promise","dedupeTime","cacheLifetime","Infinity","onErrorRetry","now","has","value","cachedValue","cachedError","created","notLoading","finishTask","clearTimeout","res","onError","timer","setTimeout","invalidateKeys","delete","createFetcherStore","keyInput","fetcherSettings","process","env","NODE_ENV","Error","fetcherStore","_","fetcherSymbol","invalidate","revalidate","revalidateKeys","mutate","mutateCache","fetch","resolve","Promise","r","unsub","listen","finally","keysInternalUnsub","prevKey","prevKeyParts","keyUnsub","keyStore","evtUnsubs","firstRun","getKeyStore","subscribe","currentKeys","newKey","currentKeyValue","handleNewListener","revalidateInterval","revalidateOnFocus","revalidateOnReconnect","runRefetcher","setInterval","push","on","cacheKeyChangeHandler","keySelector","testKeyAgainstSelector","INVALIDATE_KEYS","REVALIDATE_KEYS","full","originListen","listener","forEach","fn","clearInterval","iterOverCache","cb","keys","cached","createMutatorStore","mutator","opts","throttleCalls","newMutator","keysToInvalidate","keysToRevalidate","safeKeySet","k","lc","setKey","result","getCacheUpdater","shouldRevalidate","newVal","__unsafeOverruleSettings","console","warn","isSomeKey","$key","keysAsStoresToIndexes","setKeyStoreValue","some","join","i","length","keyOrStore","storesAsArray","$storeKeys","storeValues","partIndex","noop","selector","Array","isArray","includes","Date","getTime","Symbol","name","isServer","window","addEventListener","browserCompat","document","hidden","buildPath","extractPathParams","createRequestInitWithBody","prepareClientRequestBody","getMountRoute","RequestInputContext","RequestOutputContext","resolveRouteFactories","parseContentType","unwrapObject","addStore","FragnoClientApiError","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientFetchNetworkError","FragnoClientUnknownApiError","mergeFetcherConfigs","handleNdjsonStreamingFirstItem","computed","task","nanoquery","GET_HOOK_SYMBOL","Symbol","MUTATOR_HOOK_SYMBOL","STORE_SYMBOL","schemaAllowsUndefined","schema","validate","issues","assertBodyProvided","body","inputSchema","errorMessage","Error","mergeRequestHeaders","headerSources","result","hasHeaders","source","Headers","key","value","entries","Array","isArray","Object","buildUrl","config","params","baseUrl","mountRoute","path","pathParams","queryParams","normalizedPathParams","normalizedQueryParams","filteredQueryParams","fromEntries","filter","_","searchParams","URLSearchParams","toString","getCacheKey","method","pathParamValues","map","name","queryParamValues","keys","sort","v","isStreamingResponse","response","contentType","headers","get","subtype","isGetHook","hook","isMutatorHook","isStore","obj","ClientBuilder","publicConfig","fragmentConfig","fetcherConfig","cache","Map","createFetcherStore","createMutatorStore","invalidateKeys","constructor","cacheLifetime","Infinity","cacheEntries","createStore","input","factory","query","getFetcher","fetcher","defaultOptions","getFetcherOptions","#getFetcher","type","globalThis","fetch","bind","#getFetcherOptions","options","createHook","route","routes","find","r","outputSchema","createRouteQueryHook","createMutator","onInvalidate","createRouteQueryMutator","#createRouteQueryHook","String","fetcherOptions","useFetcherOnServer","useOnServer","callServerSideHandler","handler","fromSSRContext","executeQuery","window","url","error","fromUnknownFetchError","ok","fromResponse","store","args","isStreaming","json","getReader","cancel","items","setData","mutate","setError","set","onErrorRetry","dedupeTime","streamingPromise","#createRouteQueryMutator","invalidate","executeMutateQuery","preparedBody","bodyHeaders","requestOptions","mutatorStore","data","status","firstItem","loading","length","onError","console","mutateQuery","#invalidate","prefix","k","join","startsWith","createClientBuilder","definition","routesOrFactories","authorFetcherConfig","deps","services","serviceDeps","mergedFetcherConfig","z","projectConnectorHttpUrlSchema","url","refine","value","URL","protocol","username","password","projectConnectorConnectionStateSchema","discriminatedUnion","object","status","literal","connectedAccountId","string","min","errorCode","nullable","errorMessage","ProjectConnectorConnectionState","infer","projectConnectorConnectionNameSchema","regex","describe","projectConnectorNamedConnectionSchema","strictObject","projectId","providerConfigId","connectionName","projectConnectorConnectInputSchema","union","service","shape","returnUri","projectConnectorConnectionSchema","id","externalUserId","authorizationUrl","expiresAt","state","projectConnectorAccountSchema","projectConnectorNamedRequestSchema","request","projectConnectorNamedAccountSchema","account","projectConnectorAccountsSchema","accounts","array","cursor","hasNextPage","boolean","projectConnectorProviderConfigsSchema","providerConfigs","displayName","callbackUrl","effectiveScopes","proxyAvailable","Set","map","config","size","length","projectConnectorActionSchema","name","description","inputSchema","record","unknown","outputSchema","projectConnectorProviderActionsSchema","element","actions","projectConnectorStatusSchema","authenticated","projectConnectorProfileSchema","profile","kind","avatarUrl","email","metadata","fetchedAt","number","projectConnectorExecutionSchema","executionId","actionId","output","undefined","z","Connector","ConnectorError","ProjectConnector","ProjectApi","ProjectCallOptions","ProjectConnectorConfig","projectConnectorActionSchema","projectConnectorConnectionStateSchema","projectConnectorConnectInputSchema","projectConnectorExecutionSchema","projectConnectorHttpUrlSchema","projectConnectorProfileSchema","projectConnectorProviderConfigsSchema","ProjectConnectorConnectionState","projectConnectorConnectionRequestSchema","object","id","string","min","projectId","providerConfigId","externalUserId","service","connectionName","nullable","authorizationUrl","expiresAt","and","projectConnectorCallOptions","retries","projectConnectorDiscoveryEnvelopeSchema","success","literal","data","safeExtend","providerConfigs","array","shape","element","extend","actionIds","projectConnectorCatalogActionSchema","description","nullish","transform","ProjectConnectorSdk","Pick","connect","CreateProjectConnectorSdk","config","createOomolProjectConnectorSdk","fetch","fetchProjectConnectorWithoutRedirects","ProjectConnectorClientError","Error","constructor","code","status","name","ProjectConnectorClientConfig","baseUrl","apiKey","catalogApiKey","parseProjectConnectorApiBaseUrl","value","URL","parse","pathname","replace","search","hash","toString","parseProjectConnectorApiKey","regex","projectConnectorClientErrorFromKnownFailure","error","cause","console","warn","message","requestId","callProjectConnector","operation","Promise","T","knownFailure","parseProjectConnectorResponse","schema","ZodType","parsed","safeParse","input","RequestInfo","init","RequestInit","Response","response","globalThis","redirect","includes","body","cancel","fetchProjectConnectorProviderConfigs","signal","AbortSignal","timeout","method","headers","authorization","aborted","TypeError","payload","json","SyntaxError","failure","errorCode","ok","createProjectConnectorClient","createSdk","client","maxRetries","catalog","listProviderConfigs","discovery","map","displayName","callbackUrl","effectiveScopes","proxyAvailable","listProviderActions","find","actions","output","length","serviceActions","refine","Set","action","size","actionsById","Map","actionId","get","push","check","getConnectionRequest","crypto","randomUUID","authenticated","const","infer","request","oauth","returnUri","getProfile","accountId","profile","getUserProfile","execute","account","Record","result","executeRaw","connectedAccountId","executionId","confirmProjectConnectorRequest","expected","actual","Awaited","ReturnType","errorMessage","z","defineFragment","HookContext","HookFn","ProjectConnectorClientConfig","projectConnectorNamedConnectionSchema","ProjectConnectorConnectionReadinessChangedPayload","externalUserId","service","connection","output","ready","ProjectConnectorFragmentConfig","getExternalUserId","headers","Headers","Promise","allowedReturnUrls","url","URL","onConnectionReadinessChanged","payload","context","ProjectConnectorHooksMap","projectConnectorFragmentDefinition","extend","x","withDependencies","build","Cursor","z","defineRoutes","projectConnectorFragmentDefinition","projectConnectorAccountsSchema","projectConnectorNamedRequestSchema","projectConnectorNamedAccountSchema","projectConnectorStatusSchema","projectConnectorProviderConfigsSchema","projectConnectorProviderActionsSchema","projectConnectorConnectInputSchema","projectConnectorConnectionSchema","projectConnectorProfileSchema","projectConnectorExecutionSchema","ProjectConnectorConnectionState","projectConnectorRoutes","create","config","deps","defineRoute","method","path","outputSchema","errorCodes","handler","inputSchema","queryParameters","strictObject","input","record","string","unknown","createClientBuilder","FragnoPublicClientConfig","projectConnectorFragmentDefinition","ProjectConnectorFragmentConfig","projectConnectorRoutes","routes","const","createProjectConnectorFragment","config","fragnoConfig","FragnoPublicConfigWithDatabase","createProjectConnectorFragmentClients","builder","useProviderConfigs","createHook","useProviderActions","useStatus","useAccounts","useNamedAccount","useNamedConnectionRequest","useProfile","connect","createMutator","invalidate","refreshConnection","executeAction"],"sources":["../../../fragno/dist/api/internal/path.js","../../../fragno/dist/api/request-body.js","../../../fragno/dist/api/internal/route.js","../../../fragno/dist/api/error.js","../../../fragno/dist/api/request-input-context.js","../../../fragno/dist/api/internal/response-stream.js","../../../fragno/dist/api/request-output-context.js","../../../fragno/dist/api/route.js","../../../fragno/dist/util/content-type.js","../../../fragno/dist/util/nanostores.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/task/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/warn/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/computed/index.js","../../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/map/index.js","../../../fragno/dist/util/ssr.js","../../../fragno/dist/client/client-error.js","../../../fragno/dist/client/internal/fetcher-merge.js","../../../fragno/dist/client/internal/ndjson-streaming.js","../../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../../../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.3.0/node_modules/@nanostores/query/dist/nanoquery.js","../../../fragno/dist/client/client.js","../../src/project-connector-contracts.ts","../../src/project-connector-client.ts","../../src/definition.ts","../../src/routes.ts","../../src/index.ts"],"sourcesContent":["//#region src/api/internal/path.ts\n/**\n* Extract parameter names from a path pattern at runtime.\n* Examples:\n* - \"/users/:id\" => [\"id\"]\n* - \"/files/**\" => [\"**\"]\n* - \"/files/**:rest\" => [\"rest\"]\n*/\nfunction extractPathParams(pathPattern) {\n\tconst segments = pathPattern.split(\"/\").filter((s) => s.length > 0);\n\tconst names = [];\n\tfor (const segment of segments) {\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tnames.push(segment.slice(1));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tnames.push(\"**\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tnames.push(segment.slice(3));\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn names;\n}\n/**\n* Build a concrete path by replacing placeholders in a path pattern with values.\n*\n* Supports the same placeholder syntax as the matcher:\n* - Named parameter \":name\" is URL-encoded as a single segment\n* - Anonymous wildcard \"**\" inserts the remainder as-is (slashes preserved)\n* - Named wildcard \"**:name\" inserts the remainder from the named key\n*\n* Examples:\n* - buildPath(\"/users/:id\", { id: \"123\" }) => \"/users/123\"\n* - buildPath(\"/files/**\", { \"**\": \"a/b\" }) => \"/files/a/b\"\n* - buildPath(\"/files/**:rest\", { rest: \"a/b\" }) => \"/files/a/b\"\n*/\nfunction buildPath(pathPattern, params) {\n\tconst patternSegments = pathPattern.split(\"/\");\n\tconst builtSegments = [];\n\tfor (const segment of patternSegments) {\n\t\tif (segment.length === 0) {\n\t\t\tbuiltSegments.push(\"\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\":\")) {\n\t\t\tconst name = segment.slice(1);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path parameter :${name}`);\n\t\t\tbuiltSegments.push(encodeURIComponent(value));\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment === \"**\") {\n\t\t\tconst value = params[\"**\"];\n\t\t\tif (value === void 0) throw new Error(\"Missing value for path wildcard **\");\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.startsWith(\"**:\")) {\n\t\t\tconst name = segment.slice(3);\n\t\t\tconst value = params[name];\n\t\t\tif (value === void 0) throw new Error(`Missing value for path wildcard **:${name}`);\n\t\t\tbuiltSegments.push(value);\n\t\t\tcontinue;\n\t\t}\n\t\tbuiltSegments.push(segment);\n\t}\n\treturn builtSegments.join(\"/\");\n}\n//#endregion\nexport { buildPath, extractPathParams };\n\n//# sourceMappingURL=path.js.map","//#region src/api/request-body.ts\nconst isBinaryRequestBody = (body) => body instanceof ReadableStream || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body);\nconst containsFileBody = (value) => {\n\tif (value instanceof File || value instanceof Blob || value instanceof FormData) return true;\n\treturn typeof value === \"object\" && value !== null && Object.values(value).some((entry) => entry instanceof File || entry instanceof Blob || entry instanceof FormData);\n};\nconst appendFormDataValue = (formData, key, value) => {\n\tif (value instanceof File) formData.append(key, value, value.name);\n\telse if (value instanceof Blob) formData.append(key, value);\n\telse if (value !== void 0 && value !== null) formData.append(key, typeof value === \"string\" ? value : JSON.stringify(value));\n};\nconst prepareMultipartBody = (body) => {\n\tif (body instanceof FormData) return body;\n\tconst formData = new FormData();\n\tif (body instanceof File) {\n\t\tformData.append(\"file\", body, body.name);\n\t\treturn formData;\n\t}\n\tif (body instanceof Blob) {\n\t\tformData.append(\"file\", body);\n\t\treturn formData;\n\t}\n\tif (typeof body === \"object\" && body !== null) {\n\t\tfor (const [key, value] of Object.entries(body)) appendFormDataValue(formData, key, value);\n\t\treturn formData;\n\t}\n\tthrow new TypeError(\"Multipart routes require FormData, File, Blob, or an object body.\");\n};\nconst prepareRouteRequestBody = (body, contentType = \"application/json\") => {\n\tif (body === void 0) return {\n\t\tbody: void 0,\n\t\tcontentType: void 0\n\t};\n\tswitch (contentType) {\n\t\tcase \"application/json\": return {\n\t\t\tbody: JSON.stringify(body),\n\t\t\tcontentType\n\t\t};\n\t\tcase \"multipart/form-data\": return {\n\t\t\tbody: prepareMultipartBody(body),\n\t\t\tcontentType: null\n\t\t};\n\t\tcase \"application/octet-stream\":\n\t\t\tif (!isBinaryRequestBody(body)) throw new TypeError(\"Octet-stream routes require Blob, ArrayBuffer, ArrayBufferView, or ReadableStream bodies.\");\n\t\t\treturn {\n\t\t\t\tbody,\n\t\t\t\tcontentType\n\t\t\t};\n\t\tdefault: throw new TypeError(\"Unsupported route content type.\");\n\t}\n};\nconst prepareClientRequestBody = (body, contentType) => {\n\tif (body === void 0) return {\n\t\tbody: void 0,\n\t\tcontentType: void 0\n\t};\n\tif (contentType === \"application/octet-stream\") {\n\t\tif (!isBinaryRequestBody(body)) throw new TypeError(\"Octet-stream routes require Blob, ArrayBuffer, ArrayBufferView, or ReadableStream bodies.\");\n\t\treturn {\n\t\t\tbody,\n\t\t\tcontentType\n\t\t};\n\t}\n\tif (body instanceof FormData || body instanceof File || body instanceof Blob) return {\n\t\tbody: prepareMultipartBody(body),\n\t\tcontentType: null\n\t};\n\tif (containsFileBody(body)) return {\n\t\tbody: prepareMultipartBody(body),\n\t\tcontentType: null\n\t};\n\treturn {\n\t\tbody: JSON.stringify(body),\n\t\tcontentType: \"application/json\"\n\t};\n};\nconst prepareInferredRequestBody = (body) => {\n\tif (body === void 0) return {\n\t\tbody: void 0,\n\t\tcontentType: void 0\n\t};\n\tif (typeof body === \"string\" || body instanceof URLSearchParams || body instanceof FormData || isBinaryRequestBody(body)) return {\n\t\tbody,\n\t\tcontentType: null\n\t};\n\treturn {\n\t\tbody: JSON.stringify(body),\n\t\tcontentType: \"application/json\"\n\t};\n};\nconst applyPreparedRequestBodyContentType = (headers, preparedBody) => {\n\tif (preparedBody.contentType === null) headers.delete(\"content-type\");\n\telse if (preparedBody.contentType !== void 0) headers.set(\"content-type\", preparedBody.contentType);\n};\nconst createRequestInitWithBody = (method, headers, body, options = {}) => {\n\tconst requestInit = {\n\t\t...options,\n\t\tmethod,\n\t\theaders,\n\t\tbody\n\t};\n\tif (body instanceof ReadableStream) requestInit.duplex = \"half\";\n\treturn requestInit;\n};\n//#endregion\nexport { applyPreparedRequestBodyContentType, createRequestInitWithBody, prepareClientRequestBody, prepareInferredRequestBody, prepareRouteRequestBody };\n\n//# sourceMappingURL=request-body.js.map","//#region src/api/internal/route.ts\nfunction getMountRoute(opts) {\n\tconst mountRoute = opts.mountRoute ?? `/api/${opts.name}`;\n\tif (mountRoute.endsWith(\"/\")) return mountRoute.slice(0, -1);\n\treturn mountRoute;\n}\n//#endregion\nexport { getMountRoute };\n\n//# sourceMappingURL=route.js.map","//#region src/api/error.ts\nvar FragnoApiError = class extends Error {\n\t#status;\n\t#code;\n\tconstructor({ message, code }, status) {\n\t\tsuper(message);\n\t\tthis.name = \"FragnoApiError\";\n\t\tthis.#status = status;\n\t\tthis.#code = code;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\nvar FragnoApiValidationError = class extends FragnoApiError {\n\tissues;\n\tconstructor(message, issues) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tcode: \"FRAGNO_VALIDATION_ERROR\"\n\t\t}, 400);\n\t\tthis.name = \"FragnoApiValidationError\";\n\t\tthis.issues = issues;\n\t}\n\ttoResponse() {\n\t\treturn Response.json({\n\t\t\tmessage: this.message,\n\t\t\tissues: this.issues,\n\t\t\tcode: this.code\n\t\t}, { status: this.status });\n\t}\n};\n//#endregion\nexport { FragnoApiError, FragnoApiValidationError };\n\n//# sourceMappingURL=error.js.map","import { FragnoApiValidationError } from \"./error.js\";\n//#region src/api/request-input-context.ts\nvar RequestInputContext = class RequestInputContext {\n\t#path;\n\t#method;\n\t#pathParams;\n\t#searchParams;\n\t#headers;\n\t#body;\n\t#request;\n\t#parsedBody;\n\t#inputSchema;\n\t#shouldValidateInput;\n\tconstructor(config) {\n\t\tthis.#path = config.path;\n\t\tthis.#method = config.method;\n\t\tthis.#pathParams = config.pathParams;\n\t\tthis.#searchParams = config.searchParams;\n\t\tthis.#headers = config.headers;\n\t\tthis.#body = config.rawBody;\n\t\tthis.#request = config.request;\n\t\tthis.#parsedBody = config.parsedBody;\n\t\tthis.#inputSchema = config.inputSchema;\n\t\tthis.#shouldValidateInput = config.shouldValidateInput ?? true;\n\t}\n\t/**\n\t* Create a RequestContext from a Request object for server-side handling\n\t*/\n\tstatic async fromRequest(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.state.pathParams,\n\t\t\tsearchParams: config.state.searchParams,\n\t\t\theaders: config.state.headers,\n\t\t\trequest: config.request,\n\t\t\tparsedBody: config.state.body,\n\t\t\trawBody: config.rawBody,\n\t\t\tinputSchema: config.inputSchema,\n\t\t\tshouldValidateInput: config.shouldValidateInput\n\t\t});\n\t}\n\t/**\n\t* Create a RequestContext for server-side rendering contexts (no Request object)\n\t*/\n\tstatic fromSSRContext(config) {\n\t\treturn new RequestInputContext({\n\t\t\tmethod: config.method,\n\t\t\tpath: config.path,\n\t\t\tpathParams: config.pathParams,\n\t\t\tsearchParams: config.searchParams ?? new URLSearchParams(),\n\t\t\theaders: config.headers ?? new Headers(),\n\t\t\tparsedBody: \"body\" in config ? config.body : void 0,\n\t\t\tinputSchema: \"inputSchema\" in config ? config.inputSchema : void 0,\n\t\t\tshouldValidateInput: false\n\t\t});\n\t}\n\t/**\n\t* The HTTP method as string (e.g., `GET`, `POST`)\n\t*/\n\tget method() {\n\t\treturn this.#method;\n\t}\n\t/**\n\t* The matched route path (e.g., `/users/:id`)\n\t* @remarks `string`\n\t*/\n\tget path() {\n\t\treturn this.#path;\n\t}\n\t/**\n\t* Extracted path parameters as object (e.g., `{ id: '123' }`)\n\t* @remarks `Record<string, string>`\n\t*/\n\tget pathParams() {\n\t\treturn this.#pathParams;\n\t}\n\t/**\n\t* [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object for query parameters\n\t* @remarks `URLSearchParams`\n\t*/\n\tget query() {\n\t\treturn this.#searchParams;\n\t}\n\t/**\n\t* [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object for request headers\n\t* @remarks `Headers`\n\t*/\n\tget headers() {\n\t\treturn this.#headers;\n\t}\n\tget rawBody() {\n\t\treturn this.#body;\n\t}\n\tget request() {\n\t\treturn this.#request;\n\t}\n\t/**\n\t* Access the request body as FormData.\n\t*\n\t* Use this method when handling file uploads or multipart form submissions.\n\t* The request must have been sent with Content-Type: multipart/form-data.\n\t*\n\t* @throws Error if the request body is not FormData\n\t*\n\t* @example\n\t* ```typescript\n\t* defineRoute({\n\t* method: \"POST\",\n\t* path: \"/upload\",\n\t* async handler(ctx, res) {\n\t* const formData = ctx.formData();\n\t* const file = formData.get(\"file\") as File;\n\t* const description = formData.get(\"description\") as string;\n\t* // ... process file\n\t* }\n\t* });\n\t* ```\n\t*/\n\tformData() {\n\t\tif (!(this.#parsedBody instanceof FormData)) throw new Error(\"Request body is not FormData. Ensure the request was sent with Content-Type: multipart/form-data.\");\n\t\treturn this.#parsedBody;\n\t}\n\t/**\n\t* Check if the request body is FormData.\n\t*\n\t* Useful for routes that accept both JSON and FormData payloads.\n\t*\n\t* @example\n\t* ```typescript\n\t* defineRoute({\n\t* method: \"POST\",\n\t* path: \"/upload\",\n\t* async handler(ctx, res) {\n\t* if (ctx.isFormData()) {\n\t* const formData = ctx.formData();\n\t* // handle file upload\n\t* } else {\n\t* const json = await ctx.input.valid();\n\t* // handle JSON payload\n\t* }\n\t* }\n\t* });\n\t* ```\n\t*/\n\tisFormData() {\n\t\treturn this.#parsedBody instanceof FormData;\n\t}\n\t/**\n\t* Access the request body as a ReadableStream (application/octet-stream).\n\t*\n\t* @throws Error if the request body is not a ReadableStream\n\t*/\n\tbodyStream() {\n\t\tif (!(this.#parsedBody instanceof ReadableStream)) throw new Error(\"Request body is not a ReadableStream. Ensure the request was sent with Content-Type: application/octet-stream.\");\n\t\treturn this.#parsedBody;\n\t}\n\t/**\n\t* Check if the request body is a ReadableStream.\n\t*/\n\tisBodyStream() {\n\t\treturn this.#parsedBody instanceof ReadableStream;\n\t}\n\t/**\n\t* Input validation context (only if inputSchema is defined)\n\t* @remarks `InputContext`\n\t*/\n\tget input() {\n\t\tif (!this.#inputSchema) return;\n\t\treturn {\n\t\t\tschema: this.#inputSchema,\n\t\t\tvalid: async () => {\n\t\t\t\tif (!this.#shouldValidateInput) return this.#parsedBody;\n\t\t\t\treturn this.#validateInput();\n\t\t\t}\n\t\t};\n\t}\n\tasync #validateInput() {\n\t\tif (!this.#inputSchema) throw new Error(\"No input schema defined for this route\");\n\t\tif (this.#parsedBody instanceof FormData || this.#parsedBody instanceof Blob) throw new Error(\"Schema validation is only supported for JSON data, not FormData or Blob\");\n\t\tif (this.#parsedBody instanceof ReadableStream) throw new Error(\"Schema validation is only supported for JSON data, not FormData, Blob, or ReadableStream\");\n\t\tconst result = await this.#inputSchema[\"~standard\"].validate(this.#parsedBody);\n\t\tif (result.issues) throw new FragnoApiValidationError(\"Validation failed\", result.issues);\n\t\treturn result.value;\n\t}\n};\n//#endregion\nexport { RequestInputContext };\n\n//# sourceMappingURL=request-input-context.js.map","//#region src/api/internal/response-stream.ts\nvar ResponseStream = class {\n\t#writer;\n\t#encoder;\n\t#abortSubscribers = [];\n\t#responseReadable;\n\t#aborted = false;\n\t#abortPromise;\n\t#closed = false;\n\t/**\n\t* Whether the stream has been aborted.\n\t*/\n\tget aborted() {\n\t\treturn this.#aborted;\n\t}\n\t/**\n\t* Whether the stream has been closed normally.\n\t*/\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\t/**\n\t* The readable stream that the response is piped to.\n\t*/\n\tget responseReadable() {\n\t\treturn this.#responseReadable;\n\t}\n\tconstructor(writable, readable) {\n\t\tthis.#writer = writable.getWriter();\n\t\tthis.#encoder = new TextEncoder();\n\t\tconst reader = readable.getReader();\n\t\tthis.#abortSubscribers.push(async () => {\n\t\t\tawait reader.cancel();\n\t\t});\n\t\tthis.#responseReadable = new ReadableStream({\n\t\t\tasync pull(controller) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t},\n\t\t\tcancel: () => this.abort()\n\t\t});\n\t}\n\tasync writeRaw(input) {\n\t\ttry {\n\t\t\tif (typeof input === \"string\") input = this.#encoder.encode(input);\n\t\t\tawait this.#writer.write(input);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\tasync write(input) {\n\t\tawait this.writeRaw(JSON.stringify(input) + \"\\n\");\n\t}\n\tsleep(ms) {\n\t\treturn new Promise((resolve) => {\n\t\t\tsetTimeout(resolve, ms);\n\t\t});\n\t}\n\tasync close() {\n\t\ttry {\n\t\t\tawait this.#writer.close();\n\t\t} catch {} finally {\n\t\t\tthis.#closed = true;\n\t\t}\n\t}\n\tonAbort(listener) {\n\t\tthis.#abortSubscribers.push(listener);\n\t}\n\t/**\n\t* Abort the stream.\n\t* You can call this method when stream is aborted by external event.\n\t*/\n\tabort() {\n\t\tif (!this.#abortPromise) {\n\t\t\tthis.#aborted = true;\n\t\t\tthis.#abortPromise = Promise.allSettled(this.#abortSubscribers.map(async (subscriber) => subscriber())).then((results) => {\n\t\t\t\tconst errors = [];\n\t\t\t\tfor (const result of results) if (result.status === \"rejected\") errors.push(result.reason);\n\t\t\t\tif (errors.length > 0) throw new AggregateError(errors, \"Failed to abort response stream.\");\n\t\t\t});\n\t\t}\n\t\treturn this.#abortPromise;\n\t}\n};\n//#endregion\nexport { ResponseStream };\n\n//# sourceMappingURL=response-stream.js.map","import { ResponseStream } from \"./internal/response-stream.js\";\n//#region src/api/request-output-context.ts\n/**\n* Utility function to merge headers from multiple sources.\n* Later headers override earlier ones.\n*/\nfunction mergeHeaders(...headerSources) {\n\tconst mergedHeaders = new Headers();\n\tfor (const headerSource of headerSources) {\n\t\tif (!headerSource) continue;\n\t\tif (headerSource instanceof Headers) for (const [key, value] of headerSource.entries()) mergedHeaders.set(key, value);\n\t\telse if (Array.isArray(headerSource)) for (const [key, value] of headerSource) mergedHeaders.set(key, value);\n\t\telse for (const [key, value] of Object.entries(headerSource)) mergedHeaders.set(key, value);\n\t}\n\treturn mergedHeaders;\n}\nvar OutputContext = class {\n\t#runJsonStreamCallback;\n\tconstructor(options = {}) {\n\t\tthis.#runJsonStreamCallback = options.runJsonStreamCallback;\n\t}\n\t/**\n\t* Creates an error response.\n\t*\n\t* Shortcut for `throw new FragnoApiError(...)`\n\t*/\n\terror = ({ message, code }, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: 500,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json({\n\t\t\tmessage,\n\t\t\tcode\n\t\t}, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tempty = (initOrStatus, headers) => {\n\t\tconst defaultHeaders = {};\n\t\tif (typeof initOrStatus === \"undefined\") {\n\t\t\tconst mergedHeaders = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 201,\n\t\t\t\theaders: mergedHeaders\n\t\t\t});\n\t\t}\n\t\tif (typeof initOrStatus === \"number\") {\n\t\t\tconst mergedHeaders = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: initOrStatus,\n\t\t\t\theaders: mergedHeaders\n\t\t\t});\n\t\t}\n\t\tconst mergedHeaders = mergeHeaders(defaultHeaders, initOrStatus.headers, headers);\n\t\treturn new Response(null, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjson = (object, initOrStatus, headers) => {\n\t\tif (typeof initOrStatus === \"undefined\") return Response.json(object, {\n\t\t\tstatus: 200,\n\t\t\theaders\n\t\t});\n\t\tif (typeof initOrStatus === \"number\") return Response.json(object, {\n\t\t\tstatus: initOrStatus,\n\t\t\theaders\n\t\t});\n\t\tconst mergedHeaders = mergeHeaders(initOrStatus.headers, headers);\n\t\treturn Response.json(object, {\n\t\t\tstatus: initOrStatus.status,\n\t\t\theaders: mergedHeaders\n\t\t});\n\t};\n\tjsonStream = (cb, { onError, headers } = {}) => {\n\t\tconst defaultHeaders = {\n\t\t\t\"content-type\": \"application/x-ndjson; charset=utf-8\",\n\t\t\t\"transfer-encoding\": \"chunked\",\n\t\t\t\"cache-control\": \"no-cache\"\n\t\t};\n\t\tconst { readable, writable } = new TransformStream();\n\t\tconst stream = new ResponseStream(writable, readable);\n\t\tconst runStreamCallback = async () => {\n\t\t\ttry {\n\t\t\t\tawait cb(stream);\n\t\t\t} catch (e) {\n\t\t\t\tif (e === void 0) {} else if (e instanceof Error && onError) await onError(e, stream);\n\t\t\t\telse console.error(e);\n\t\t\t} finally {\n\t\t\t\tawait stream.close();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\tPromise.resolve(this.#runJsonStreamCallback ? this.#runJsonStreamCallback(runStreamCallback) : runStreamCallback()).catch(async (error) => {\n\t\t\t\tconsole.error(error);\n\t\t\t\tawait stream.close();\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconsole.error(error);\n\t\t\tstream.close();\n\t\t}\n\t\treturn new Response(stream.responseReadable, {\n\t\t\tstatus: 200,\n\t\t\theaders: mergeHeaders(defaultHeaders, headers)\n\t\t});\n\t};\n};\nvar RequestOutputContext = class extends OutputContext {\n\t#outputSchema;\n\tconstructor(outputSchema, options) {\n\t\tsuper(options);\n\t\tthis.#outputSchema = outputSchema;\n\t}\n};\n//#endregion\nexport { OutputContext, RequestOutputContext };\n\n//# sourceMappingURL=request-output-context.js.map","//#region src/api/route.ts\n/**\n* Helper to resolve route factories into routes\n* @internal\n*/\nfunction resolveRouteFactories(context, routesOrFactories) {\n\tconst routes = [];\n\tfor (const item of routesOrFactories) if (typeof item === \"function\") {\n\t\tconst factoryRoutes = item(context);\n\t\troutes.push(...factoryRoutes);\n\t} else routes.push(item);\n\treturn routes;\n}\nfunction defineRoute(config) {\n\treturn config;\n}\nfunction defineRoutes(_definition) {\n\treturn { create: (fn) => {\n\t\treturn (ctx) => {\n\t\t\treturn fn({\n\t\t\t\t...ctx,\n\t\t\t\tdefineRoute\n\t\t\t});\n\t\t};\n\t} };\n}\n//#endregion\nexport { defineRoute, defineRoutes, resolveRouteFactories };\n\n//# sourceMappingURL=route.js.map","//#region src/util/content-type.ts\n/**\n* Parses a content-type header string into its components\n*\n* @param contentType - The content-type header value to parse\n* @returns A ParsedContentType object or null if the input is invalid\n*\n* @example\n* ```ts\n* const { type, subtype, mediaType, parameters }\n* = parseContentType(\"application/json; charset=utf-8\");\n* console.assert(type === \"application\");\n* console.assert(subtype === \"json\");\n* console.assert(mediaType === \"application/json\");\n* console.assert(parameters[\"charset\"] === \"utf-8\");\n*/\nfunction parseContentType(contentType) {\n\tif (!contentType || typeof contentType !== \"string\") return null;\n\tconst trimmed = contentType.trim();\n\tif (!trimmed) return null;\n\tconst parts = trimmed.split(\";\").map((part) => part.trim());\n\tconst mediaType = parts[0];\n\tif (!mediaType) return null;\n\tconst typeParts = mediaType.split(\"/\");\n\tif (typeParts.length !== 2) return null;\n\tconst [type, subtype] = typeParts.map((part) => part.trim().toLowerCase());\n\tif (!type || !subtype) return null;\n\tconst parameters = {};\n\tfor (let i = 1; i < parts.length; i++) {\n\t\tconst param = parts[i];\n\t\tconst equalIndex = param.indexOf(\"=\");\n\t\tif (equalIndex > 0) {\n\t\t\tconst key = param.slice(0, equalIndex).trim().toLowerCase();\n\t\t\tlet value = param.slice(equalIndex + 1).trim();\n\t\t\tif (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) value = value.slice(1, -1);\n\t\t\tif (key) parameters[key] = value;\n\t\t}\n\t}\n\treturn {\n\t\ttype,\n\t\tsubtype,\n\t\tmediaType: `${type}/${subtype}`,\n\t\tparameters\n\t};\n}\n//#endregion\nexport { parseContentType };\n\n//# sourceMappingURL=content-type.js.map","//#region src/util/nanostores.ts\n/**\n* Normalizes a value that could be a plain value, an Atom, or a Vue Ref to a plain value.\n*/\nfunction unwrapAtom(value) {\n\tif (value && typeof value === \"object\" && \"get\" in value && typeof value.get === \"function\") return value.get();\n\treturn value;\n}\n/**\n* Normalizes an object where values can be plain values, Atoms, or Vue Refs.\n* Returns a new object with all values normalized to plain values.\n*/\nfunction unwrapObject(params) {\n\tif (!params) return;\n\treturn Object.fromEntries(Object.entries(params).map(([key, value]) => [key, unwrapAtom(value)]));\n}\nfunction isReadableAtom(value) {\n\tif (!value) return false;\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"get\" in value) || typeof value.get !== \"function\") return false;\n\tif (!(\"lc\" in value) || typeof value.lc !== \"number\") return false;\n\tif (!(\"notify\" in value) || typeof value.notify !== \"function\") return false;\n\tif (!(\"off\" in value) || typeof value.off !== \"function\") return false;\n\tif (!(\"subscribe\" in value) || typeof value.subscribe !== \"function\") return false;\n\tif (!(\"value\" in value)) return false;\n\treturn true;\n}\n//#endregion\nexport { isReadableAtom, unwrapAtom, unwrapObject };\n\n//# sourceMappingURL=nanostores.js.map","let tasks = 0\nlet resolves = []\n\nexport function startTask() {\n tasks += 1\n return () => {\n tasks -= 1\n if (tasks === 0) {\n let prevResolves = resolves\n resolves = []\n for (let i of prevResolves) i()\n }\n }\n}\n\nexport function task(cb) {\n let endTask = startTask()\n let promise = cb().finally(endTask)\n promise.t = true\n return promise\n}\n\nexport function allTasks() {\n if (tasks === 0) {\n return Promise.resolve()\n } else {\n return new Promise(resolve => {\n resolves.push(resolve)\n })\n }\n}\n\nexport function cleanTasks() {\n tasks = 0\n}\n","import { cleanTasks } from '../task/index.js'\n\nexport const clean = Symbol('clean')\n\nexport const cleanStores = (...stores) => {\n if (process.env.NODE_ENV === 'production') {\n throw new Error(\n 'cleanStores() can be used only during development or tests'\n )\n }\n cleanTasks()\n for (let $store of stores) {\n if ($store) {\n if ($store.mocked) delete $store.mocked\n if ($store[clean]) $store[clean]()\n }\n }\n}\n","import { clean } from '../clean-stores/index.js'\n\nlet listenerQueue = []\nlet lqIndex = 0\nconst QUEUE_ITEMS_PER_LISTENER = 4\n// Use globalThis.nanostoresGlobal to store epoch so all module instances share\n// the same counter. This fixes issues when Nano Store is bundled separately\n// in different parts of an application (e.g., tree-shaking separates core\n// from React), causing each bundle to have its own epoch instance.\nexport const nanostoresGlobal = (globalThis.nanostoresGlobal ||= { epoch: 0 })\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const atom = initialValue => {\n let listeners = []\n let $atom = {\n get() {\n if (!$atom.lc) {\n $atom.listen(() => {})()\n }\n return $atom.value\n },\n init: initialValue,\n lc: 0,\n listen(listener) {\n $atom.lc = listeners.push(listener)\n\n return () => {\n for (\n let i = lqIndex + QUEUE_ITEMS_PER_LISTENER;\n i < listenerQueue.length;\n ) {\n if (listenerQueue[i] === listener) {\n listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER)\n } else {\n i += QUEUE_ITEMS_PER_LISTENER\n }\n }\n\n let index = listeners.indexOf(listener)\n if (~index) {\n listeners.splice(index, 1)\n if (!--$atom.lc) $atom.off()\n }\n }\n },\n notify(oldValue, changedKey) {\n nanostoresGlobal.epoch++\n let runListenerQueue = !listenerQueue.length\n for (let listener of listeners) {\n listenerQueue.push(listener, $atom.value, oldValue, changedKey)\n }\n\n if (runListenerQueue) {\n for (\n lqIndex = 0;\n lqIndex < listenerQueue.length;\n lqIndex += QUEUE_ITEMS_PER_LISTENER\n ) {\n listenerQueue[lqIndex](\n listenerQueue[lqIndex + 1],\n listenerQueue[lqIndex + 2],\n listenerQueue[lqIndex + 3]\n )\n }\n listenerQueue.length = 0\n }\n },\n /* It will be called on last listener unsubscribing.\n We will redefine it in onMount and onStop. */\n off() {},\n set(newValue) {\n let oldValue = $atom.value\n if (oldValue !== newValue) {\n $atom.value = newValue\n $atom.notify(oldValue)\n }\n },\n subscribe(listener) {\n let unbind = $atom.listen(listener)\n listener($atom.value)\n return unbind\n },\n value: initialValue\n }\n\n if (process.env.NODE_ENV !== 'production') {\n $atom[clean] = () => {\n listeners = []\n $atom.lc = 0\n $atom.off()\n }\n }\n\n return $atom\n}\n\nexport const readonlyType = store => store\n","import { clean } from '../clean-stores/index.js'\n\nconst START = 0\nconst STOP = 1\nconst SET = 2\nconst NOTIFY = 3\nconst MOUNT = 5\nconst UNMOUNT = 6\nconst REVERT_MUTATION = 10\n\nexport let on = (object, listener, eventKey, mutateStore) => {\n object.events = object.events || {}\n if (!object.events[eventKey + REVERT_MUTATION]) {\n object.events[eventKey + REVERT_MUTATION] = mutateStore(eventProps => {\n // eslint-disable-next-line no-sequences\n object.events[eventKey].reduceRight((event, l) => (l(event), event), {\n shared: {},\n ...eventProps\n })\n })\n }\n object.events[eventKey] = object.events[eventKey] || []\n object.events[eventKey].push(listener)\n return () => {\n let currentListeners = object.events[eventKey]\n let index = currentListeners.indexOf(listener)\n currentListeners.splice(index, 1)\n if (!currentListeners.length) {\n delete object.events[eventKey]\n object.events[eventKey + REVERT_MUTATION]()\n delete object.events[eventKey + REVERT_MUTATION]\n }\n }\n}\n\nexport let onStart = ($store, listener) =>\n on($store, listener, START, runListeners => {\n let originListen = $store.listen\n $store.listen = arg => {\n if (!$store.lc && !$store.starting) {\n $store.starting = true\n runListeners()\n delete $store.starting\n }\n return originListen(arg)\n }\n return () => {\n $store.listen = originListen\n }\n })\n\nexport let onStop = ($store, listener) =>\n on($store, listener, STOP, runListeners => {\n let originOff = $store.off\n $store.off = () => {\n runListeners()\n originOff()\n }\n return () => {\n $store.off = originOff\n }\n })\n\nexport let onSet = ($store, listener) =>\n on($store, listener, SET, runListeners => {\n let originSet = $store.set\n let originSetKey = $store.setKey\n if ($store.setKey) {\n $store.setKey = (changed, changedValue) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({\n abort,\n changed,\n newValue: { ...$store.value, [changed]: changedValue }\n })\n if (!isAborted) return originSetKey(changed, changedValue)\n }\n }\n $store.set = newValue => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, newValue })\n if (!isAborted) return originSet(newValue)\n }\n return () => {\n $store.set = originSet\n $store.setKey = originSetKey\n }\n })\n\nexport let onNotify = ($store, listener) =>\n on($store, listener, NOTIFY, runListeners => {\n let originNotify = $store.notify\n $store.notify = (oldValue, changed) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, changed, oldValue })\n if (!isAborted) return originNotify(oldValue, changed)\n }\n return () => {\n $store.notify = originNotify\n }\n })\n\nexport const STORE_UNMOUNT_DELAY = 1000\n\nexport let onMount = ($store, initialize) => {\n let listener = payload => {\n let destroy = initialize(payload)\n if (destroy) $store.events[UNMOUNT].push(destroy)\n }\n return on($store, listener, MOUNT, runListeners => {\n let originListen = $store.listen\n $store.listen = (...args) => {\n if (!$store.lc && !$store.active) {\n $store.active = true\n runListeners()\n }\n return originListen(...args)\n }\n\n let originOff = $store.off\n $store.events[UNMOUNT] = []\n $store.off = () => {\n originOff()\n setTimeout(() => {\n if ($store.active && !$store.lc) {\n $store.active = false\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n }\n }, STORE_UNMOUNT_DELAY)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n let originClean = $store[clean]\n $store[clean] = () => {\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n $store.active = false\n originClean()\n }\n }\n\n return () => {\n $store.listen = originListen\n $store.off = originOff\n }\n })\n}\n","let warned = {}\n\nexport function warn(text) {\n if (!warned[text]) {\n warned[text] = true\n if (typeof console !== 'undefined' && console.warn) {\n console.groupCollapsed('Nano Stores: ' + text)\n console.trace('Source of deprecated call')\n console.groupEnd()\n }\n }\n}\n","import { atom, nanostoresGlobal } from '../atom/index.js'\nimport { onMount } from '../lifecycle/index.js'\nimport { warn } from '../warn/index.js'\n\nlet computedStore = (stores, cb, batched) => {\n if (!Array.isArray(stores)) stores = [stores]\n\n let previousArgs\n let currentEpoch\n let set = () => {\n if (currentEpoch === nanostoresGlobal.epoch) return\n currentEpoch = nanostoresGlobal.epoch\n let args = stores.map($store => $store.get())\n if (!previousArgs || args.some((arg, i) => arg !== previousArgs[i])) {\n previousArgs = args\n let value = cb(...args)\n if (value && value.then && value.t) {\n if (process.env.NODE_ENV !== 'production') {\n warn(\n 'Use @nanostores/async for async computed. We will remove Promise support in computed() in Nano Stores 2.0'\n )\n }\n value.then(asyncValue => {\n if (previousArgs === args) {\n // Prevent a stale set\n $computed.set(asyncValue)\n }\n })\n } else {\n $computed.set(value)\n currentEpoch = nanostoresGlobal.epoch\n }\n }\n }\n let $computed = atom(undefined)\n let get = $computed.get\n $computed.get = () => {\n set()\n return get()\n }\n\n let timer\n let run = batched\n ? () => {\n clearTimeout(timer)\n timer = setTimeout(set)\n }\n : set\n\n onMount($computed, () => {\n let unbinds = stores.map($store => $store.listen(run))\n set()\n return () => {\n for (let unbind of unbinds) unbind()\n }\n })\n\n return $computed\n}\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const computed = (stores, fn) => computedStore(stores, fn)\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const batched = (stores, fn) => computedStore(stores, fn, true)\n","import { atom } from '../atom/index.js'\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const map = (initial = {}) => {\n let $map = atom(initial)\n\n $map.setKey = function (key, value) {\n let oldMap = $map.value\n if (typeof value === 'undefined' && key in $map.value) {\n $map.value = { ...$map.value }\n delete $map.value[key]\n $map.notify(oldMap, key)\n } else if ($map.value[key] !== value) {\n $map.value = {\n ...$map.value,\n [key]: value\n }\n $map.notify(oldMap, key)\n }\n }\n\n return $map\n}\n","import { allTasks } from \"nanostores\";\n//#region src/util/ssr.ts\nlet stores = [];\nfunction getStores() {\n\treturn stores;\n}\nfunction addStore(store) {\n\tstores.push(store);\n}\nfunction cleanStores() {\n\tstores = [];\n}\nlet clientInitialData;\nfunction hydrateFromWindow() {\n\tif (window?.__FRAGNO_INITIAL_DATA__) {\n\t\tclientInitialData = new Map(window.__FRAGNO_INITIAL_DATA__);\n\t\tdelete window.__FRAGNO_INITIAL_DATA__;\n\t\tconsole.warn(\"hydrateFromWindow\", { clientInitialData: Array.from(clientInitialData.entries()) });\n\t}\n}\nfunction getInitialData(key) {\n\tif (clientInitialData?.has(key)) {\n\t\tconst data = clientInitialData.get(key);\n\t\tclientInitialData.delete(key);\n\t\treturn data;\n\t}\n}\nfunction listenToStores() {\n\tfor (const store of getStores()) store.listen(() => {});\n}\nasync function getFinalStoreValues() {\n\tlistenToStores();\n\tawait allTasks();\n\tconst stores = getStores();\n\tconst storesInitialValue = /* @__PURE__ */ new Map();\n\tfor (const store of stores) {\n\t\tconst value = store.get();\n\t\tif (!value || !store.key || value.loading) continue;\n\t\tstoresInitialValue.set(store.key, value.data);\n\t}\n\treturn storesInitialValue;\n}\n//#endregion\nexport { addStore, cleanStores, getFinalStoreValues, getInitialData, getStores, hydrateFromWindow };\n\n//# sourceMappingURL=ssr.js.map","//#region src/client/client-error.ts\n/**\n* Base error class for all Fragno client errors.\n*/\nvar FragnoClientError = class extends Error {\n\t#code;\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, { cause: options.cause });\n\t\tthis.name = \"FragnoClientError\";\n\t\tthis.#code = code;\n\t}\n\tget code() {\n\t\treturn this.#code;\n\t}\n};\nvar FragnoClientFetchError = class extends FragnoClientError {\n\tconstructor(message, code, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientFetchError\";\n\t}\n\tstatic fromUnknownFetchError(error) {\n\t\tif (!(error instanceof Error)) return new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t\tif (error.name === \"AbortError\") return new FragnoClientFetchAbortError(\"Request was aborted\", { cause: error });\n\t\treturn new FragnoClientFetchNetworkError(\"Network request failed\", { cause: error });\n\t}\n};\n/**\n* Error thrown when a network request fails (e.g., no internet connection, DNS failure).\n*/\nvar FragnoClientFetchNetworkError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Network request failed\", options = {}) {\n\t\tsuper(message, \"NETWORK_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchNetworkError\";\n\t}\n};\n/**\n* Error thrown when a request is aborted (e.g., user cancels request, timeout).\n*/\nvar FragnoClientFetchAbortError = class extends FragnoClientFetchError {\n\tconstructor(message = \"Request was aborted\", options = {}) {\n\t\tsuper(message, \"ABORT_ERROR\", options);\n\t\tthis.name = \"FragnoClientFetchAbortError\";\n\t}\n};\n/**\n* Error thrown when the API result is unexpected, e.g. no json is returned.\n*/\nvar FragnoClientUnknownApiError = class extends FragnoClientError {\n\t#status;\n\tconstructor(message = \"Unknown API error\", status, options = {}) {\n\t\tsuper(message, \"UNKNOWN_API_ERROR\", options);\n\t\tthis.name = \"FragnoClientUnknownApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n};\nvar FragnoClientApiError = class FragnoClientApiError extends FragnoClientError {\n\t#status;\n\tconstructor({ message, code }, status, options = {}) {\n\t\tsuper(message, code, options);\n\t\tthis.name = \"FragnoClientApiError\";\n\t\tthis.#status = status;\n\t}\n\tget status() {\n\t\treturn this.#status;\n\t}\n\t/**\n\t* The error code returned by the API.\n\t*\n\t* The type is `TErrorCode` (the set of known error codes for this route), but may also be a string\n\t* for forward compatibility with future error codes.\n\t*/\n\tget code() {\n\t\treturn super.code;\n\t}\n\tstatic async fromResponse(response) {\n\t\tconst unknown = await response.json();\n\t\tconst status = response.status;\n\t\tif (!(\"message\" in unknown || \"code\" in unknown)) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\tif (!(typeof unknown.message === \"string\" && typeof unknown.code === \"string\")) return new FragnoClientUnknownApiError(\"Unknown API error\", status);\n\t\treturn new FragnoClientApiError({\n\t\t\tmessage: unknown.message,\n\t\t\tcode: unknown.code\n\t\t}, status);\n\t}\n};\n//#endregion\nexport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError };\n\n//# sourceMappingURL=client-error.js.map","//#region src/client/internal/fetcher-merge.ts\n/**\n* Merge two fetcher configurations, with user config taking precedence.\n* If user provides a custom function, it takes full precedence.\n* Otherwise, deep merge RequestInit options.\n*/\nfunction mergeFetcherConfigs(authorConfig, userConfig) {\n\tif (userConfig?.type === \"function\") return userConfig;\n\tif (!userConfig && authorConfig?.type === \"function\") return authorConfig;\n\tconst authorOpts = authorConfig?.type === \"options\" ? authorConfig.options : {};\n\tconst userOpts = userConfig?.type === \"options\" ? userConfig.options : {};\n\tif (Object.keys(authorOpts).length === 0 && Object.keys(userOpts).length === 0) return;\n\treturn {\n\t\ttype: \"options\",\n\t\toptions: {\n\t\t\t...authorOpts,\n\t\t\t...userOpts,\n\t\t\theaders: mergeHeaders(authorOpts.headers, userOpts.headers)\n\t\t}\n\t};\n}\n/**\n* Merge headers from author and user configs.\n* User headers override author headers.\n*/\nfunction mergeHeaders(author, user) {\n\tif (!author && !user) return;\n\tconst merged = new Headers(author);\n\tnew Headers(user).forEach((value, key) => {\n\t\tmerged.set(key, value);\n\t});\n\tif (merged.keys().next().done) return;\n\treturn merged;\n}\n//#endregion\nexport { mergeFetcherConfigs };\n\n//# sourceMappingURL=fetcher-merge.js.map","import { FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientUnknownApiError } from \"../client-error.js\";\n//#region src/client/internal/ndjson-streaming.ts\n/**\n* Creates a promise that rejects when the abort signal is triggered\n*/\nfunction createAbortPromise(abortSignal) {\n\treturn new Promise((_, reject) => {\n\t\tconst abortHandler = () => {\n\t\t\treject(new FragnoClientFetchAbortError(\"Operation was aborted\"));\n\t\t};\n\t\tif (abortSignal.aborted) abortHandler();\n\t\telse abortSignal.addEventListener(\"abort\", abortHandler, { once: true });\n\t});\n}\nconst parseNdjsonBuffer = (buffer, options) => {\n\tconst lines = buffer.split(\"\\n\");\n\tconst trailingBuffer = options.flush ? \"\" : lines.pop() ?? \"\";\n\tfor (let index = 0; index < lines.length; index += 1) {\n\t\tconst line = lines[index];\n\t\tif (!line.trim()) continue;\n\t\tlet jsonObject;\n\t\ttry {\n\t\t\tjsonObject = JSON.parse(line);\n\t\t} catch (parseError) {\n\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", options.parseErrorStatus, { cause: parseError });\n\t\t}\n\t\tif (options.onItem(jsonObject) === false) {\n\t\t\tconst remainingLines = lines.slice(index + 1);\n\t\t\treturn {\n\t\t\t\tstopped: true,\n\t\t\t\tbuffer: remainingLines.length > 0 ? `${remainingLines.join(\"\\n\")}\\n${trailingBuffer}` : trailingBuffer\n\t\t\t};\n\t\t}\n\t}\n\treturn {\n\t\tstopped: false,\n\t\tbuffer: trailingBuffer\n\t};\n};\n/**\n* Handles NDJSON streaming responses by returning the first item from the fetcher\n* and then continuing to stream updates via the store's mutate method.\n*\n* This makes it so that we can wait until the first chunk before updating the store, if we did\n* not do this, `loading` would briefly be false before the first item would be populated in the\n* result.\n*\n* @param response - The fetch Response object containing the NDJSON stream\n* @param store - The fetcher store to update with streaming data\n* @param abortSignal - Optional AbortSignal to cancel the streaming operation\n* @returns A promise that resolves to an object containing the first item and a streaming promise\n*/\nasync function handleNdjsonStreamingFirstItem(response, store, options = {}) {\n\tif (!response.body) throw new FragnoClientFetchError(\"Streaming response has no body\", \"NO_BODY\");\n\tconst { abortSignal } = options;\n\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\tconst decoder = new TextDecoder();\n\tconst reader = response.body.getReader();\n\tlet buffer = \"\";\n\tlet firstItem = null;\n\tconst items = [];\n\ttry {\n\t\twhile (firstItem === null) {\n\t\t\tif (abortSignal?.aborted) {\n\t\t\t\treader.releaseLock();\n\t\t\t\tthrow new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\t}\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\tbuffer = parseNdjsonBuffer(buffer, {\n\t\t\t\tparseErrorStatus: 500,\n\t\t\t\tonItem: (jsonObject) => {\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tfirstItem = jsonObject;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}).buffer;\n\t\t\tif (firstItem !== null) {\n\t\t\t\tconst streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);\n\t\t\t\treturn {\n\t\t\t\t\tfirstItem,\n\t\t\t\t\titems,\n\t\t\t\t\tstreamingPromise\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (firstItem === null) {\n\t\t\treader.releaseLock();\n\t\t\tthrow new FragnoClientUnknownApiError(\"NDJSON stream contained no valid items\", 500);\n\t\t}\n\t\treader.releaseLock();\n\t\tthrow new FragnoClientFetchError(\"Unexpected end of stream processing\", \"NO_BODY\");\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {\n\t\t\tstore?.setError(error);\n\t\t\tthrow error;\n\t\t}\n\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 500, { cause: error });\n\t\tstore?.setError(clientError);\n\t\tthrow clientError;\n\t}\n}\n/**\n* Continues streaming the remaining items in the background\n*/\nasync function continueStreaming(reader, decoder, initialBuffer, items, store, abortSignal) {\n\tlet buffer = initialBuffer;\n\tconst appendItem = (jsonObject) => {\n\t\titems.push(jsonObject);\n\t\tstore?.setData([...items]);\n\t};\n\ttry {\n\t\twhile (true) {\n\t\t\tbuffer = parseNdjsonBuffer(buffer, {\n\t\t\t\tparseErrorStatus: 400,\n\t\t\t\tonItem: appendItem\n\t\t\t}).buffer;\n\t\t\tif (abortSignal?.aborted) throw new FragnoClientFetchAbortError(\"Operation was aborted\");\n\t\t\tconst { done, value } = await (abortSignal ? Promise.race([reader.read(), createAbortPromise(abortSignal)]) : reader.read());\n\t\t\tif (done) {\n\t\t\t\tparseNdjsonBuffer(buffer, {\n\t\t\t\t\tflush: true,\n\t\t\t\t\tparseErrorStatus: 400,\n\t\t\t\t\tonItem: appendItem\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientFetchError || error instanceof FragnoClientUnknownApiError) {\n\t\t\tstore?.setError(error);\n\t\t\tthrow error;\n\t\t}\n\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 400, { cause: error });\n\t\tstore?.setError(clientError);\n\t\tthrow clientError;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn items;\n}\n//#endregion\nexport { handleNdjsonStreamingFirstItem };\n\n//# sourceMappingURL=ndjson-streaming.js.map","export let createNanoEvents = () => ({\n emit(event, ...args) {\n for (\n let callbacks = this.events[event] || [],\n i = 0,\n length = callbacks.length;\n i < length;\n i++\n ) {\n callbacks[i](...args)\n }\n },\n events: {},\n on(event, cb) {\n ;(this.events[event] ||= []).push(cb)\n return () => {\n this.events[event] = this.events[event]?.filter(i => cb !== i)\n }\n }\n})\n","import { map, onStart, onStop, atom, batched, startTask } from 'nanostores';\nimport { createNanoEvents } from 'nanoevents';\n\nfunction defaultOnErrorRetry({ retryCount }) {\n return ~~((Math.random() + 0.5) * (1 << (retryCount < 8 ? retryCount : 8))) * 2e3;\n}\nconst nanoqueryFactory = ([\n isAppVisible,\n visibilityChangeSubscribe,\n reconnectChangeSubscribe\n]) => {\n const nanoquery = ({\n cache = /* @__PURE__ */ new Map(),\n fetcher: globalFetcher,\n ...globalSettings\n } = {}) => {\n const events = createNanoEvents();\n let focus = true;\n visibilityChangeSubscribe(() => {\n focus = isAppVisible();\n focus && events.emit(FOCUS);\n });\n reconnectChangeSubscribe(() => events.emit(RECONNECT));\n const _revalidateOnInterval = /* @__PURE__ */ new Map(), _errorInvalidateTimeouts = /* @__PURE__ */ new Map(), _runningFetches = /* @__PURE__ */ new Map();\n let rewrittenSettings = {};\n const getCachedValueByKey = (key) => {\n const fromCache = cache.get(key);\n if (!fromCache)\n return [];\n const cacheHit = (fromCache.expires || 0) > getNow();\n return cacheHit ? [fromCache.data, fromCache.error] : [];\n };\n const runFetcher = async ([key, keyParts], store, settings) => {\n if (!focus)\n return;\n const set = (v) => {\n if (store.key === key) {\n store.set(v);\n events.emit(SET_CACHE, key, v, true);\n }\n };\n const setAsLoading = (prev) => {\n const toSet = prev === void 0 ? {} : { data: prev };\n set({\n ...toSet,\n ...loading,\n promise: _runningFetches.get(key)\n });\n };\n let {\n dedupeTime = 4e3,\n cacheLifetime = Infinity,\n fetcher,\n onErrorRetry = defaultOnErrorRetry\n } = {\n ...settings,\n ...rewrittenSettings\n };\n if (cacheLifetime < dedupeTime)\n cacheLifetime = dedupeTime;\n const now = getNow();\n if (_runningFetches.has(key)) {\n if (!store.value.loading)\n setAsLoading(getCachedValueByKey(key)[0]);\n return;\n }\n let cachedValue, cachedError;\n const fromCache = cache.get(key);\n if (fromCache?.data !== void 0 || fromCache?.error) {\n [cachedValue, cachedError] = getCachedValueByKey(key);\n if ((fromCache.created || 0) + dedupeTime > now) {\n if (store.value.data != cachedValue || store.value.error != cachedError) {\n set({ ...notLoading, data: cachedValue, error: cachedError });\n }\n return;\n }\n }\n const finishTask = startTask();\n try {\n clearTimeout(_errorInvalidateTimeouts.get(key));\n const promise = fetcher(...keyParts);\n _runningFetches.set(key, promise);\n setAsLoading(cachedValue);\n const res = await promise;\n cache.set(key, {\n data: res,\n created: getNow(),\n expires: getNow() + cacheLifetime\n });\n set({ data: res, ...notLoading });\n } catch (error) {\n settings.onError?.(error);\n const retryCount = (cache.get(key)?.retryCount || 0) + 1;\n cache.set(key, {\n error,\n created: getNow(),\n expires: getNow() + cacheLifetime,\n retryCount\n });\n if (onErrorRetry) {\n const timer = onErrorRetry({\n error,\n key,\n retryCount\n });\n if (timer)\n _errorInvalidateTimeouts.set(\n key,\n setTimeout(() => {\n invalidateKeys(key);\n cache.set(key, { retryCount });\n }, timer)\n );\n }\n set({ data: store.value.data, error, ...notLoading });\n } finally {\n finishTask();\n _runningFetches.delete(key);\n }\n };\n const createFetcherStore = (keyInput, {\n fetcher = globalFetcher,\n ...fetcherSettings\n } = {}) => {\n if (process.env.NODE_ENV !== \"production\" && !fetcher) {\n throw new Error(\n \"You need to set up either global fetcher of fetcher in createFetcherStore\"\n );\n }\n const fetcherStore = map({\n ...notLoading\n }), settings = { ...globalSettings, ...fetcherSettings, fetcher };\n fetcherStore._ = fetcherSymbol;\n fetcherStore.invalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n invalidateKeys(key);\n }\n };\n fetcherStore.revalidate = () => {\n const { key } = fetcherStore;\n if (key) {\n revalidateKeys(key);\n }\n };\n fetcherStore.mutate = (data) => {\n const { key } = fetcherStore;\n if (key) {\n mutateCache(key, data);\n }\n };\n fetcherStore.fetch = async () => {\n let resolve;\n const promise = new Promise((r) => resolve = r);\n const unsub = fetcherStore.listen(({ error, data }) => {\n if (error !== void 0)\n resolve({ error });\n if (data !== void 0)\n resolve({ data });\n });\n return promise.finally(unsub);\n };\n let keysInternalUnsub, prevKey, prevKeyParts, keyUnsub, keyStore;\n let evtUnsubs = [];\n onStart(fetcherStore, () => {\n const firstRun = !keysInternalUnsub;\n [keyStore, keysInternalUnsub] = getKeyStore(keyInput);\n keyUnsub = keyStore.subscribe((currentKeys) => {\n if (currentKeys) {\n const [newKey, keyParts] = currentKeys;\n fetcherStore.key = newKey;\n runFetcher([newKey, keyParts], fetcherStore, settings);\n prevKey = newKey;\n prevKeyParts = keyParts;\n } else {\n fetcherStore.key = prevKey = prevKeyParts = void 0;\n fetcherStore.set({ ...notLoading });\n }\n });\n const currentKeyValue = keyStore.get();\n if (currentKeyValue) {\n [prevKey, prevKeyParts] = currentKeyValue;\n if (firstRun)\n handleNewListener();\n }\n const {\n revalidateInterval = 0,\n revalidateOnFocus,\n revalidateOnReconnect\n } = settings;\n const runRefetcher = () => {\n if (prevKey)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n if (revalidateInterval > 0) {\n _revalidateOnInterval.set(\n keyInput,\n setInterval(runRefetcher, revalidateInterval)\n );\n }\n if (revalidateOnFocus)\n evtUnsubs.push(events.on(FOCUS, runRefetcher));\n if (revalidateOnReconnect)\n evtUnsubs.push(events.on(RECONNECT, runRefetcher));\n const cacheKeyChangeHandler = (keySelector) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector)) {\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n }\n };\n evtUnsubs.push(\n events.on(INVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(REVALIDATE_KEYS, cacheKeyChangeHandler),\n events.on(SET_CACHE, (keySelector, data, full) => {\n if (prevKey && testKeyAgainstSelector(prevKey, keySelector) && fetcherStore.value !== data && fetcherStore.value.data !== data) {\n fetcherStore.set(\n full ? data : { data, ...notLoading }\n );\n }\n })\n );\n });\n const handleNewListener = () => {\n if (prevKey && prevKeyParts)\n runFetcher([prevKey, prevKeyParts], fetcherStore, settings);\n };\n const originListen = fetcherStore.listen;\n fetcherStore.listen = (listener) => {\n const unsub = originListen(listener);\n listener(fetcherStore.value);\n handleNewListener();\n return unsub;\n };\n onStop(fetcherStore, () => {\n fetcherStore.value = { ...notLoading };\n keysInternalUnsub?.();\n evtUnsubs.forEach((fn) => fn());\n evtUnsubs = [];\n keyUnsub?.();\n clearInterval(_revalidateOnInterval.get(keyInput));\n });\n return fetcherStore;\n };\n const iterOverCache = (keySelector, cb) => {\n for (const key of cache.keys()) {\n if (testKeyAgainstSelector(key, keySelector))\n cb(key);\n }\n };\n const invalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n cache.delete(key);\n });\n events.emit(INVALIDATE_KEYS, keySelector);\n };\n const revalidateKeys = (keySelector) => {\n iterOverCache(keySelector, (key) => {\n const cached = cache.get(key);\n if (cached) {\n cache.set(key, { ...cached, created: -Infinity });\n }\n });\n events.emit(REVALIDATE_KEYS, keySelector);\n };\n const mutateCache = (keySelector, data) => {\n iterOverCache(keySelector, (key) => {\n if (data === void 0)\n cache.delete(key);\n else {\n cache.set(key, {\n data,\n created: getNow(),\n expires: getNow() + (globalSettings.cacheLifetime ?? 8e3)\n });\n }\n });\n events.emit(SET_CACHE, keySelector, data);\n };\n function createMutatorStore(mutator, opts) {\n const { throttleCalls, onError } = opts ?? {\n throttleCalls: true,\n onError: globalSettings?.onError\n };\n const mutate = async (data) => {\n if (throttleCalls && store.value?.loading)\n return;\n const newMutator = rewrittenSettings.fetcher ?? mutator;\n const keysToInvalidate = [], keysToRevalidate = [];\n const safeKeySet = (k, v) => {\n if (store.lc) {\n store.setKey(k, v);\n }\n };\n try {\n store.set({\n error: void 0,\n data: void 0,\n mutate,\n ...loading\n });\n const result = await newMutator({\n data,\n invalidate: (key) => {\n keysToInvalidate.push(key);\n },\n revalidate: (key) => {\n keysToRevalidate.push(key);\n },\n getCacheUpdater: (key, shouldRevalidate = true) => [\n (newVal) => {\n mutateCache(key, newVal);\n if (shouldRevalidate) {\n keysToRevalidate.push(key);\n }\n },\n cache.get(key)?.data\n ]\n });\n safeKeySet(\"data\", result);\n return result;\n } catch (error) {\n onError?.(error);\n safeKeySet(\"error\", error);\n store.setKey(\"error\", error);\n } finally {\n safeKeySet(\"loading\", false);\n keysToInvalidate.forEach(invalidateKeys);\n keysToRevalidate.forEach(revalidateKeys);\n }\n };\n const store = map({\n mutate,\n ...notLoading\n });\n onStop(\n store,\n () => store.set({ mutate, ...notLoading })\n );\n store.mutate = mutate;\n return store;\n }\n const __unsafeOverruleSettings = (data) => {\n if (process.env.NODE_ENV !== \"test\") {\n console.warn(\n `You should only use __unsafeOverruleSettings in test environment`\n );\n }\n rewrittenSettings = data;\n };\n return [\n createFetcherStore,\n createMutatorStore,\n { __unsafeOverruleSettings, invalidateKeys, revalidateKeys, mutateCache }\n ];\n };\n function isSomeKey(key) {\n return typeof key === \"string\" || typeof key === \"number\" || key === true;\n }\n const getKeyStore = (keys) => {\n if (isSomeKey(keys))\n return [\n atom([\"\" + keys, [keys]]),\n () => {\n }\n ];\n const keyParts = [];\n const $key = atom(null);\n const keysAsStoresToIndexes = /* @__PURE__ */ new Map();\n const setKeyStoreValue = () => {\n if (keyParts.some((v) => v === null || v === void 0 || v === false)) {\n $key.set(null);\n } else {\n $key.set([keyParts.join(\"\"), keyParts]);\n }\n };\n for (let i = 0; i < keys.length; i++) {\n const keyOrStore = keys[i];\n if (isSomeKey(keyOrStore)) {\n keyParts.push(keyOrStore);\n } else {\n keyParts.push(null);\n keysAsStoresToIndexes.set(keyOrStore, i);\n }\n }\n const storesAsArray = [...keysAsStoresToIndexes.keys()];\n const $storeKeys = batched(storesAsArray, (...storeValues) => {\n for (let i = 0; i < storeValues.length; i++) {\n const store = storesAsArray[i], partIndex = keysAsStoresToIndexes.get(store);\n keyParts[partIndex] = store._ === fetcherSymbol ? store.value && \"data\" in store.value ? store.key : null : storeValues[i];\n }\n setKeyStoreValue();\n });\n setKeyStoreValue();\n return [$key, $storeKeys.subscribe(noop)];\n };\n function noop() {\n }\n const FOCUS = 1, RECONNECT = 2, INVALIDATE_KEYS = 3, REVALIDATE_KEYS = 4, SET_CACHE = 5;\n const testKeyAgainstSelector = (key, selector) => {\n if (Array.isArray(selector))\n return selector.includes(key);\n else if (typeof selector === \"function\")\n return selector(key);\n else\n return key === selector;\n };\n const getNow = () => (/* @__PURE__ */ new Date()).getTime();\n const fetcherSymbol = Symbol();\n const loading = { loading: true }, notLoading = { loading: false };\n return nanoquery;\n};\n\nconst subscribe = (name, fn) => {\n const isServer = typeof window === \"undefined\";\n if (!isServer) {\n addEventListener(name, fn);\n }\n};\nconst browserCompat = [\n () => !document.hidden,\n (cb) => subscribe(\"visibilitychange\", cb),\n (cb) => subscribe(\"online\", cb)\n];\n\nconst nanoquery = nanoqueryFactory(browserCompat);\n\nexport { nanoquery, defaultOnErrorRetry as onErrorRetry };\n","import { buildPath, extractPathParams } from \"../api/internal/path.js\";\nimport { createRequestInitWithBody, prepareClientRequestBody } from \"../api/request-body.js\";\nimport { getMountRoute } from \"../api/internal/route.js\";\nimport { RequestInputContext } from \"../api/request-input-context.js\";\nimport { RequestOutputContext } from \"../api/request-output-context.js\";\nimport { resolveRouteFactories } from \"../api/route.js\";\nimport { parseContentType } from \"../util/content-type.js\";\nimport { unwrapObject } from \"../util/nanostores.js\";\nimport { addStore } from \"../util/ssr.js\";\nimport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError } from \"./client-error.js\";\nimport { mergeFetcherConfigs } from \"./internal/fetcher-merge.js\";\nimport { handleNdjsonStreamingFirstItem } from \"./internal/ndjson-streaming.js\";\nimport { computed, task } from \"nanostores\";\nimport { nanoquery } from \"@nanostores/query\";\n//#region src/client/client.ts\n/**\n* Symbols used to identify hook types\n*/\nconst GET_HOOK_SYMBOL = Symbol(\"fragno-get-hook\");\nconst MUTATOR_HOOK_SYMBOL = Symbol(\"fragno-mutator-hook\");\nconst STORE_SYMBOL = Symbol(\"fragno-store\");\nasync function schemaAllowsUndefined(schema) {\n\ttry {\n\t\treturn !(await schema[\"~standard\"].validate(void 0)).issues;\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function assertBodyProvided(body, inputSchema, errorMessage) {\n\tif (typeof body !== \"undefined\" || inputSchema === void 0) return;\n\tif (await schemaAllowsUndefined(inputSchema)) return;\n\tthrow new Error(errorMessage);\n}\n/**\n* Merge request headers from multiple sources.\n* Returns undefined if there are no headers to merge.\n* @internal\n*/\nfunction mergeRequestHeaders(...headerSources) {\n\tconst result = {};\n\tlet hasHeaders = false;\n\tfor (const source of headerSources) {\n\t\tif (!source) continue;\n\t\tif (source instanceof Headers) for (const [key, value] of source.entries()) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t\telse if (Array.isArray(source)) for (const [key, value] of source) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t\telse for (const [key, value] of Object.entries(source)) {\n\t\t\tresult[key] = value;\n\t\t\thasHeaders = true;\n\t\t}\n\t}\n\treturn hasHeaders ? result : void 0;\n}\n/**\n* @internal\n*/\nfunction buildUrl(config, params) {\n\tconst { baseUrl = \"\", mountRoute, path } = config;\n\tconst { pathParams, queryParams } = params ?? {};\n\tconst normalizedPathParams = unwrapObject(pathParams);\n\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\treturn `${baseUrl}${mountRoute}${buildPath(path, normalizedPathParams ?? {})}${searchParams.toString() ? `?${searchParams.toString()}` : \"\"}`;\n}\n/**\n* This method returns an array, which can be passed directly to nanostores.\n*\n* The returned array is always: path, pathParams (In order they appear in the path), queryParams (In alphabetical order)\n* Missing pathParams are replaced with \"<missing>\".\n* Atoms with undefined values are wrapped in computed atoms that map undefined to \"\" to avoid nanoquery treating the key as incomplete.\n* @param path\n* @param params\n* @returns\n* @internal\n*/\nfunction getCacheKey(method, path, params) {\n\tif (!params) return [method, path];\n\tconst { pathParams, queryParams } = params;\n\tconst pathParamValues = extractPathParams(path).map((name) => pathParams?.[name] ?? \"<missing>\");\n\tconst queryParamValues = queryParams ? Object.keys(queryParams).sort().map((key) => {\n\t\tconst value = queryParams[key];\n\t\tif (value && typeof value === \"object\" && \"get\" in value) return computed(value, (v) => v ?? \"\");\n\t\treturn value ?? \"\";\n\t}) : [];\n\treturn [\n\t\tmethod,\n\t\tpath,\n\t\t...pathParamValues,\n\t\t...queryParamValues\n\t];\n}\nfunction isStreamingResponse(response) {\n\tconst contentType = parseContentType(response.headers.get(\"content-type\"));\n\tif (!contentType) return false;\n\tif (!(response.headers.get(\"transfer-encoding\") === \"chunked\")) return false;\n\tif (contentType.subtype === \"octet-stream\") return \"octet-stream\";\n\tif (contentType.subtype === \"x-ndjson\") return \"ndjson\";\n\treturn false;\n}\n/**\n* @internal\n*/\nfunction isGetHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && GET_HOOK_SYMBOL in hook && hook[GET_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isMutatorHook(hook) {\n\treturn typeof hook === \"object\" && hook !== null && MUTATOR_HOOK_SYMBOL in hook && hook[MUTATOR_HOOK_SYMBOL] === true;\n}\n/**\n* @internal\n*/\nfunction isStore(obj) {\n\treturn typeof obj === \"object\" && obj !== null && STORE_SYMBOL in obj && obj[STORE_SYMBOL] === true;\n}\nvar ClientBuilder = class {\n\t#publicConfig;\n\t#fragmentConfig;\n\t#fetcherConfig;\n\t#cache = /* @__PURE__ */ new Map();\n\t#createFetcherStore;\n\t#createMutatorStore;\n\t#invalidateKeys;\n\tconstructor(publicConfig, fragmentConfig) {\n\t\tthis.#publicConfig = publicConfig;\n\t\tthis.#fragmentConfig = fragmentConfig;\n\t\tthis.#fetcherConfig = publicConfig.fetcherConfig;\n\t\tconst [createFetcherStore, createMutatorStore, { invalidateKeys }] = nanoquery({\n\t\t\tcache: this.#cache,\n\t\t\tcacheLifetime: Infinity\n\t\t});\n\t\tthis.#createFetcherStore = createFetcherStore;\n\t\tthis.#createMutatorStore = createMutatorStore;\n\t\tthis.#invalidateKeys = invalidateKeys;\n\t}\n\tget cacheEntries() {\n\t\treturn Object.fromEntries(this.#cache.entries());\n\t}\n\tcreateStore(input) {\n\t\tif (typeof input === \"function\") return {\n\t\t\tfactory: input,\n\t\t\t[STORE_SYMBOL]: true\n\t\t};\n\t\treturn {\n\t\t\tobj: input,\n\t\t\t[STORE_SYMBOL]: true\n\t\t};\n\t}\n\t/**\n\t* Build a URL for a custom backend call using the configured baseUrl and mountRoute.\n\t* Useful for fragment authors who need to make custom fetch calls.\n\t*/\n\tbuildUrl(path, params) {\n\t\treturn buildUrl({\n\t\t\tbaseUrl: this.#publicConfig.baseUrl ?? \"\",\n\t\t\tmountRoute: getMountRoute({\n\t\t\t\tname: this.#fragmentConfig.name,\n\t\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t\t}),\n\t\t\tpath\n\t\t}, {\n\t\t\tpathParams: params?.path,\n\t\t\tqueryParams: params?.query\n\t\t});\n\t}\n\t/**\n\t* Get the configured fetcher function for custom backend calls.\n\t* Returns fetch with merged options applied.\n\t*/\n\tgetFetcher() {\n\t\treturn {\n\t\t\tfetcher: this.#getFetcher(),\n\t\t\tdefaultOptions: this.#getFetcherOptions()\n\t\t};\n\t}\n\t#getFetcher() {\n\t\tif (this.#fetcherConfig?.type === \"function\") return this.#fetcherConfig.fetcher;\n\t\treturn globalThis.fetch.bind(globalThis);\n\t}\n\t#getFetcherOptions() {\n\t\tif (this.#fetcherConfig?.type === \"options\") return this.#fetcherConfig.options;\n\t}\n\tcreateHook(path, options) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.path === path && r.method === \"GET\" && r.outputSchema !== void 0);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is not a GET route with an output schema.`);\n\t\treturn this.#createRouteQueryHook(route, options);\n\t}\n\tcreateMutator(method, path, onInvalidate) {\n\t\tconst route = this.#fragmentConfig.routes.find((r) => r.method !== \"GET\" && r.path === path && r.method === method);\n\t\tif (!route) throw new Error(`Route '${path}' not found or is a GET route with an input and output schema.`);\n\t\treturn this.#createRouteQueryMutator(route, onInvalidate);\n\t}\n\t#createRouteQueryHook(route, options = {}) {\n\t\tif (route.method !== \"GET\") throw new Error(`Only GET routes are supported for hooks. Route '${route.path}' is a ${String(route.method)} route.`);\n\t\tif (!route.outputSchema) throw new Error(`Output schema is required for GET routes. Route '${route.path}' has no output schema.`);\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute({\n\t\t\tname: this.#fragmentConfig.name,\n\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t});\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tconst useFetcherOnServer = this.#fetcherConfig?.type === \"function\" && this.#fetcherConfig.useOnServer;\n\t\tasync function callServerSideHandler(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tconst normalizedPathParams = unwrapObject(pathParams);\n\t\t\tconst normalizedQueryParams = unwrapObject(queryParams) ?? {};\n\t\t\tconst filteredQueryParams = Object.fromEntries(Object.entries(normalizedQueryParams).filter(([_, value]) => value !== void 0));\n\t\t\tconst searchParams = new URLSearchParams(filteredQueryParams);\n\t\t\treturn await route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tmethod: route.method,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: normalizedPathParams,\n\t\t\t\tsearchParams\n\t\t\t}), new RequestOutputContext(route.outputSchema));\n\t\t}\n\t\tasync function executeQuery(params) {\n\t\t\tconst { pathParams, queryParams } = params ?? {};\n\t\t\tif (typeof window === \"undefined\" && !useFetcherOnServer) return task(async () => callServerSideHandler({\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t}));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams,\n\t\t\t\tqueryParams\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = fetcherOptions ? await fetcher(url, fetcherOptions) : await fetcher(url);\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\treturn {\n\t\t\troute,\n\t\t\tstore: (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst key = getCacheKey(route.method, route.path, {\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst store = this.#createFetcherStore(key, {\n\t\t\t\t\tfetcher: async () => {\n\t\t\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\t\t\tpathParams: path,\n\t\t\t\t\t\t\tqueryParams: query\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\t\t\tif (!isStreaming) return response.json();\n\t\t\t\t\t\tif (typeof window === \"undefined\" && !useFetcherOnServer) {\n\t\t\t\t\t\t\tif (response.body) await response.body.getReader().cancel();\n\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\t\t\tconst { items } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\t\t\t\tstore.mutate(value);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\t\t\t\tstore.set({\n\t\t\t\t\t\t\t\t\t\t...store.get(),\n\t\t\t\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn items;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t\t\t},\n\t\t\t\t\tonErrorRetry: options?.onErrorRetry,\n\t\t\t\t\tdedupeTime: Infinity\n\t\t\t\t});\n\t\t\t\tif (typeof window === \"undefined\") addStore(store);\n\t\t\t\treturn store;\n\t\t\t},\n\t\t\tquery: async (args) => {\n\t\t\t\tconst { path, query } = args ?? {};\n\t\t\t\tconst response = await executeQuery({\n\t\t\t\t\tpathParams: path,\n\t\t\t\t\tqueryParams: query\n\t\t\t\t});\n\t\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\t\tif (!isStreaming) return await response.json();\n\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\t\treturn await streamingPromise;\n\t\t\t\t}\n\t\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\t\tthrow new Error(\"Unreachable\");\n\t\t\t},\n\t\t\t[GET_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#createRouteQueryMutator(route, onInvalidate = (invalidate, params) => {\n\t\tinvalidate(\"GET\", route.path, params);\n\t}) {\n\t\tconst method = route.method;\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute({\n\t\t\tname: this.#fragmentConfig.name,\n\t\t\tmountRoute: this.#publicConfig.mountRoute\n\t\t});\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tconst useFetcherOnServer = this.#fetcherConfig?.type === \"function\" && this.#fetcherConfig.useOnServer;\n\t\tasync function executeMutateQuery({ body, path, query }) {\n\t\t\tif (typeof window === \"undefined\" && !useFetcherOnServer) return task(async () => route.handler(RequestInputContext.fromSSRContext({\n\t\t\t\tinputSchema: route.inputSchema,\n\t\t\t\tmethod,\n\t\t\t\tpath: route.path,\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tsearchParams: new URLSearchParams(query),\n\t\t\t\tbody\n\t\t\t}), new RequestOutputContext(route.outputSchema)));\n\t\t\tconst url = buildUrl({\n\t\t\t\tbaseUrl,\n\t\t\t\tmountRoute,\n\t\t\t\tpath: route.path\n\t\t\t}, {\n\t\t\t\tpathParams: path,\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tconst preparedBody = prepareClientRequestBody(body, route.contentType);\n\t\t\t\tconst bodyHeaders = preparedBody.contentType === void 0 || preparedBody.contentType === null ? void 0 : { \"Content-Type\": preparedBody.contentType };\n\t\t\t\tconst headers = mergeRequestHeaders(fetcherOptions?.headers, bodyHeaders);\n\t\t\t\tconst requestOptions = createRequestInitWithBody(method, headers ?? {}, preparedBody.body, fetcherOptions);\n\t\t\t\tresponse = await fetcher(url, requestOptions);\n\t\t\t} catch (error) {\n\t\t\t\tthrow FragnoClientFetchError.fromUnknownFetchError(error);\n\t\t\t}\n\t\t\tif (!response.ok) throw await FragnoClientApiError.fromResponse(response);\n\t\t\treturn response;\n\t\t}\n\t\tconst mutatorStore = this.#createMutatorStore(async ({ data }) => {\n\t\t\tif (typeof window === \"undefined\") {}\n\t\t\tconst { body, path, query } = data;\n\t\t\tawait assertBodyProvided(body, route.inputSchema, \"Body is required.\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tonInvalidate(this.#invalidate.bind(this), {\n\t\t\t\tpathParams: path ?? {},\n\t\t\t\tqueryParams: query\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return await response.json();\n\t\t\tif (typeof window === \"undefined\") return [];\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\tsetData: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\tsetError: (value) => {\n\t\t\t\t\t\tmutatorStore.set({\n\t\t\t\t\t\t\t...mutatorStore.get(),\n\t\t\t\t\t\t\terror: value\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn [firstItem];\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported.\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t}, { onError: (error) => {\n\t\t\tconsole.error(\"Error in mutatorStore\", error);\n\t\t} });\n\t\tconst mutateQuery = (async (data) => {\n\t\t\tconst { body, path, query } = data;\n\t\t\tawait assertBodyProvided(body, route.inputSchema, \"Body is required for mutateQuery\");\n\t\t\tconst response = await executeMutateQuery({\n\t\t\t\tbody,\n\t\t\t\tpath,\n\t\t\t\tquery\n\t\t\t});\n\t\t\tif (response.status === 201 || response.status === 204) return;\n\t\t\tconst isStreaming = isStreamingResponse(response);\n\t\t\tif (!isStreaming) return await response.json();\n\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\tconst { streamingPromise } = await handleNdjsonStreamingFirstItem(response);\n\t\t\t\treturn await streamingPromise;\n\t\t\t}\n\t\t\tif (isStreaming === \"octet-stream\") throw new Error(\"Octet-stream streaming is not supported for mutations\");\n\t\t\tthrow new Error(\"Unreachable\");\n\t\t});\n\t\treturn {\n\t\t\troute,\n\t\t\tmutateQuery,\n\t\t\tmutatorStore,\n\t\t\t[MUTATOR_HOOK_SYMBOL]: true\n\t\t};\n\t}\n\t#invalidate(method, path, params) {\n\t\tconst prefix = getCacheKey(method, path, {\n\t\t\tpathParams: params?.pathParams,\n\t\t\tqueryParams: params?.queryParams\n\t\t}).map((k) => typeof k === \"string\" ? k : k.get()).join(\"\");\n\t\tthis.#invalidateKeys((key) => key.startsWith(prefix));\n\t}\n};\n/**\n* Create a client builder for fragments using the new fragment definition API.\n* This is the same as createClientBuilder but works with FragmentDefinition.\n*/\nfunction createClientBuilder(definition, publicConfig, routesOrFactories, authorFetcherConfig) {\n\tconst routes = resolveRouteFactories({\n\t\tconfig: {},\n\t\tdeps: {},\n\t\tservices: {},\n\t\tserviceDeps: {}\n\t}, routesOrFactories);\n\tconst fragmentConfig = {\n\t\tname: definition.name,\n\t\troutes\n\t};\n\tconst mountRoute = getMountRoute({\n\t\tname: definition.name,\n\t\tmountRoute: publicConfig.mountRoute\n\t});\n\tconst mergedFetcherConfig = mergeFetcherConfigs(authorFetcherConfig, publicConfig.fetcherConfig);\n\treturn new ClientBuilder({\n\t\t...publicConfig,\n\t\tmountRoute,\n\t\tfetcherConfig: mergedFetcherConfig\n\t}, fragmentConfig);\n}\n//#endregion\nexport { ClientBuilder, FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError, buildUrl, createClientBuilder, getCacheKey, isGetHook, isMutatorHook, isStore };\n\n//# sourceMappingURL=client.js.map","import { z } from \"zod\";\n\n/** Only HTTP(S) URLs can be used as OAuth return destinations. */\nexport const projectConnectorHttpUrlSchema = z.url().refine((value) => {\n const url = new URL(value);\n return (url.protocol === \"https:\" || url.protocol === \"http:\") && !url.username && !url.password;\n}, \"Expected an HTTP(S) URL without embedded credentials\");\n\n/** A connection becomes usable only after the gateway confirms its account ID. */\nexport const projectConnectorConnectionStateSchema = z.discriminatedUnion(\"status\", [\n z.object({ status: z.literal(\"initiated\") }),\n z.object({ status: z.literal(\"connected\"), connectedAccountId: z.string().min(1) }),\n z.object({\n status: z.literal(\"failed\"),\n errorCode: z.string().nullable(),\n errorMessage: z.string().nullable(),\n }),\n z.object({ status: z.literal(\"expired\") }),\n]);\n\n/** Persisted connection lifecycle; provider credentials never enter this fragment. */\nexport type ProjectConnectorConnectionState = z.infer<typeof projectConnectorConnectionStateSchema>;\n\n/** Mirrors the gateway's alias rule so invalid names fail here with a usable message. */\nconst projectConnectorConnectionNameSchema = z\n .string()\n .regex(\n /^[a-z0-9][a-z0-9_-]*$/,\n \"Connection names may only contain lowercase letters, digits, underscores, and hyphens, and must start with a letter or digit\",\n )\n .describe(\"Lowercase letters, digits, underscores, and hyphens; starts with a letter or digit.\");\n\n/** Named selectors preserve exact source identity; user ownership comes only from authentication. */\nexport const projectConnectorNamedConnectionSchema = z.strictObject({\n projectId: z.string().min(1),\n providerConfigId: z.string().min(1),\n connectionName: projectConnectorConnectionNameSchema,\n});\n\n/** Select exactly one provider and name every connection explicitly. */\nexport const projectConnectorConnectInputSchema = z.union([\n z.strictObject({\n service: z.string().regex(/^[a-z0-9_-]+$/),\n connectionName: projectConnectorNamedConnectionSchema.shape.connectionName,\n returnUri: projectConnectorHttpUrlSchema,\n }),\n z.strictObject({\n providerConfigId: projectConnectorNamedConnectionSchema.shape.providerConfigId,\n connectionName: projectConnectorNamedConnectionSchema.shape.connectionName,\n returnUri: projectConnectorHttpUrlSchema,\n }),\n]);\n\n/** Public connection request projection, including its verified lifecycle. */\nexport const projectConnectorConnectionSchema = z.object({\n id: z.string(),\n projectId: z.string(),\n providerConfigId: z.string(),\n externalUserId: z.string(),\n service: z.string(),\n connectionName: projectConnectorNamedConnectionSchema.shape.connectionName,\n authorizationUrl: projectConnectorHttpUrlSchema,\n expiresAt: z.string(),\n state: projectConnectorConnectionStateSchema,\n});\n\n/** Stored account selectors bind actions to a specific product user and provider. */\nexport const projectConnectorAccountSchema = z.object({\n id: z.string(),\n projectId: z.string(),\n providerConfigId: z.string(),\n externalUserId: z.string(),\n service: z.string(),\n connectionName: projectConnectorNamedConnectionSchema.shape.connectionName,\n});\n\n/** Missing named requests remain JSON results rather than empty HTTP responses. */\nexport const projectConnectorNamedRequestSchema = z.strictObject({\n request: projectConnectorConnectionSchema.nullable(),\n});\n\n/** Missing named accounts remain JSON results rather than empty HTTP responses. */\nexport const projectConnectorNamedAccountSchema = z.strictObject({\n account: projectConnectorAccountSchema.nullable(),\n});\n\n/** Account pagination is owned by the fragment rather than the provider gateway. */\nexport const projectConnectorAccountsSchema = z.object({\n accounts: z.array(projectConnectorAccountSchema),\n cursor: z.string().nullable(),\n hasNextPage: z.boolean(),\n});\n\n/** Project-scoped OAuth provider overview excludes action IDs and credentials. */\nexport const projectConnectorProviderConfigsSchema = z\n .object({\n projectId: z.string().min(1),\n providerConfigs: z.array(\n z.object({\n id: z.string().min(1),\n service: z.string().min(1),\n displayName: z.string(),\n callbackUrl: projectConnectorHttpUrlSchema,\n effectiveScopes: z.array(z.string().min(1)),\n proxyAvailable: z.boolean(),\n }),\n ),\n })\n .refine(\n ({ providerConfigs }) =>\n new Set(providerConfigs.map((config) => config.id)).size === providerConfigs.length,\n \"Provider configuration IDs must be unique\",\n );\n\n/** Authoritative catalog contracts describe action values, not a provider's execution permissions. */\nexport const projectConnectorActionSchema = z.object({\n id: z.string().min(1),\n service: z.string().min(1),\n name: z.string(),\n description: z.string().nullable(),\n inputSchema: z.record(z.string(), z.unknown()),\n outputSchema: z.record(z.string(), z.unknown()),\n});\n\n/** Only actions allowed by this exact project OAuth configuration are included. */\nexport const projectConnectorProviderActionsSchema = z.object({\n projectId: projectConnectorProviderConfigsSchema.shape.projectId,\n providerConfigId: projectConnectorProviderConfigsSchema.shape.providerConfigs.element.shape.id,\n actions: z.array(projectConnectorActionSchema),\n});\n\n/** Project authentication does not imply that an individual provider account is usable. */\nexport const projectConnectorStatusSchema = z.object({ authenticated: z.literal(true) });\n\n/** Read-only provider identity associated with one verified account. */\nexport const projectConnectorProfileSchema = z.object({\n connectedAccountId: z.string(),\n externalUserId: z.string(),\n service: z.string(),\n profile: z.object({\n id: z.string(),\n kind: z.string(),\n username: z.string().nullable(),\n displayName: z.string().nullable(),\n avatarUrl: z.string().nullable(),\n email: z.string().nullable(),\n metadata: z.record(z.string(), z.unknown()),\n }),\n fetchedAt: z.number(),\n});\n\n/** Action output stays opaque; execution IDs support upstream troubleshooting. */\nexport const projectConnectorExecutionSchema = z.object({\n executionId: z.string(),\n actionId: z.string(),\n output: z.unknown().refine((value) => value !== undefined, \"Expected action output\"),\n});\n","import { z } from \"zod\";\n\nimport {\n Connector,\n ConnectorError,\n ProjectConnector,\n type ProjectApi,\n type ProjectCallOptions,\n type ProjectConnectorConfig,\n} from \"@oomol-lab/connector\";\n\nimport {\n projectConnectorActionSchema,\n projectConnectorConnectionStateSchema,\n type projectConnectorConnectInputSchema,\n projectConnectorExecutionSchema,\n projectConnectorHttpUrlSchema,\n projectConnectorProfileSchema,\n projectConnectorProviderConfigsSchema,\n type ProjectConnectorConnectionState,\n} from \"./project-connector-contracts\";\n\nconst projectConnectorConnectionRequestSchema = z\n .object({\n id: z.string().min(1),\n projectId: z.string().min(1),\n providerConfigId: z.string().min(1),\n externalUserId: z.string().min(1),\n service: z.string().min(1),\n connectionName: z.string().nullable(),\n authorizationUrl: projectConnectorHttpUrlSchema,\n expiresAt: z.string(),\n })\n .and(projectConnectorConnectionStateSchema);\n\nconst projectConnectorCallOptions = { retries: 0 } satisfies ProjectCallOptions;\nconst projectConnectorDiscoveryEnvelopeSchema = z.object({\n success: z.literal(true),\n data: projectConnectorProviderConfigsSchema.safeExtend({\n providerConfigs: z.array(\n projectConnectorProviderConfigsSchema.shape.providerConfigs.element.extend({\n actionIds: z.array(z.string().min(1)),\n }),\n ),\n }),\n});\n\nconst projectConnectorCatalogActionSchema = projectConnectorActionSchema.extend({\n description: z\n .string()\n .nullish()\n .transform((description) => description ?? null),\n});\n\ntype ProjectConnectorSdk = Pick<\n ProjectApi,\n \"getConnectionRequest\" | \"getUserProfile\" | \"executeRaw\"\n> & {\n readonly connect: Pick<ProjectApi[\"connect\"], \"oauth\">;\n};\n\ntype CreateProjectConnectorSdk = (config: ProjectConnectorConfig) => ProjectConnectorSdk;\n\nfunction createOomolProjectConnectorSdk(config: ProjectConnectorConfig): ProjectConnectorSdk {\n return new ProjectConnector({\n ...config,\n // The wrapper also avoids the SDK calling native Workers fetch with a transport receiver.\n fetch: fetchProjectConnectorWithoutRedirects,\n });\n}\n\n/** A safe SDK failure exposes its code, never its raw response data or project API key. */\nexport class ProjectConnectorClientError extends Error {\n constructor(\n readonly code: string,\n readonly status: number,\n ) {\n super(`Project Connector request failed: ${code} (HTTP ${status})`);\n this.name = \"ProjectConnectorClientError\";\n }\n}\n\n/** Server-only gateway credentials; null catalogApiKey disables action discovery, not account operations. */\nexport type ProjectConnectorClientConfig = {\n baseUrl: string;\n apiKey: string;\n catalogApiKey: string | null;\n};\n\nfunction parseProjectConnectorApiBaseUrl(value: string): string {\n const baseUrl = new URL(projectConnectorHttpUrlSchema.parse(value));\n const pathname = baseUrl.pathname.replace(/\\/+$/, \"\");\n if (baseUrl.search || baseUrl.hash || pathname !== \"/v1\") {\n throw new Error(\"Project Connector baseUrl must be an origin followed by /v1\");\n }\n baseUrl.pathname = pathname;\n return baseUrl.toString().replace(/\\/$/, \"\");\n}\n\nfunction parseProjectConnectorApiKey(value: string): string {\n return z\n .string()\n .min(1)\n .regex(/^[^\\s]+$/)\n .parse(value);\n}\n\nfunction projectConnectorClientErrorFromKnownFailure(\n error: unknown,\n): ProjectConnectorClientError | null {\n if (error instanceof ProjectConnectorClientError) {\n return error;\n }\n if (error instanceof ConnectorError) {\n // The SDK wraps transport rejections as network errors; retain our safe redirect diagnosis.\n if (error.cause instanceof ProjectConnectorClientError) {\n return error.cause;\n }\n // Callers only see the code; the gateway's message (e.g. which input field it rejected) stays in\n // server logs. Gateway messages never contain the project API key.\n console.warn(\"Project Connector gateway request failed\", {\n code: error.code,\n status: error.status,\n message: error.message,\n requestId: error.requestId,\n });\n return new ProjectConnectorClientError(error.code, error.status);\n }\n return null;\n}\n\nasync function callProjectConnector<T>(operation: () => Promise<T>): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n const knownFailure = projectConnectorClientErrorFromKnownFailure(error);\n if (knownFailure) {\n throw knownFailure;\n }\n throw error;\n }\n}\n\nfunction parseProjectConnectorResponse<T>(schema: z.ZodType<T>, value: unknown): T {\n const parsed = schema.safeParse(value);\n if (!parsed.success) {\n throw new ProjectConnectorClientError(\"invalid_response\", 502);\n }\n return parsed.data;\n}\n\nasync function fetchProjectConnectorWithoutRedirects(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n): Promise<Response> {\n // Workers rejects redirect: \"error\" before sending the request. Manual mode keeps credentials\n // on the original host; reject redirects before interpreting the response body.\n const response = await globalThis.fetch(input, { ...init, redirect: \"manual\" });\n if ([301, 302, 303, 307, 308].includes(response.status)) {\n await response.body?.cancel();\n throw new ProjectConnectorClientError(\"unexpected_redirect\", response.status);\n }\n return response;\n}\n\nasync function fetchProjectConnectorProviderConfigs(\n config: Pick<ProjectConnectorClientConfig, \"baseUrl\" | \"apiKey\">,\n) {\n // The SDK has no discovery method; redirects must not forward the project key elsewhere.\n const signal = AbortSignal.timeout(30_000);\n let response: Response;\n try {\n response = await fetchProjectConnectorWithoutRedirects(\n `${config.baseUrl}/saas/oauth/provider-configs`,\n {\n method: \"GET\",\n headers: { authorization: `Bearer ${config.apiKey}` },\n signal,\n },\n );\n } catch (cause) {\n if (signal.aborted) {\n throw new ProjectConnectorClientError(\"client_timeout\", 0);\n }\n if (cause instanceof TypeError) {\n throw new ProjectConnectorClientError(\"client_network_error\", 0);\n }\n throw cause;\n }\n let payload: unknown;\n try {\n payload = await response.json();\n } catch (cause) {\n if (signal.aborted) {\n throw new ProjectConnectorClientError(\"client_timeout\", 0);\n }\n if (cause instanceof TypeError) {\n throw new ProjectConnectorClientError(\"client_network_error\", 0);\n }\n if (!(cause instanceof SyntaxError)) {\n throw cause;\n }\n payload = null;\n }\n const failure = z.object({ errorCode: z.string().min(1) }).safeParse(payload);\n if (!response.ok || failure.success) {\n throw new ProjectConnectorClientError(\n failure.success\n ? failure.data.errorCode\n : response.status === 429\n ? \"rate_limited\"\n : \"provider_error\",\n response.status,\n );\n }\n return parseProjectConnectorResponse(projectConnectorDiscoveryEnvelopeSchema, payload).data;\n}\n\n/** Project Connector adapter with retries disabled and project keys confined to server requests. */\nexport function createProjectConnectorClient(\n config: ProjectConnectorClientConfig,\n createSdk: CreateProjectConnectorSdk = createOomolProjectConnectorSdk,\n) {\n const apiKey = parseProjectConnectorApiKey(config.apiKey);\n const baseUrl = parseProjectConnectorApiBaseUrl(config.baseUrl);\n const client = createSdk({ apiKey, baseUrl, maxRetries: 0 });\n // Project credentials and catalog credentials have different authority; never substitute one for the other.\n const catalog =\n config.catalogApiKey === null\n ? null\n : new Connector({\n apiKey: parseProjectConnectorApiKey(config.catalogApiKey),\n baseUrl,\n maxRetries: 0,\n fetch: fetchProjectConnectorWithoutRedirects,\n }).catalog;\n\n return {\n async listProviderConfigs() {\n const discovery = await fetchProjectConnectorProviderConfigs({ apiKey, baseUrl });\n return {\n projectId: discovery.projectId,\n providerConfigs: discovery.providerConfigs.map((config) => ({\n id: config.id,\n service: config.service,\n displayName: config.displayName,\n callbackUrl: config.callbackUrl,\n effectiveScopes: config.effectiveScopes,\n proxyAvailable: config.proxyAvailable,\n })),\n };\n },\n async listProviderActions(providerConfigId: string) {\n const discovery = await fetchProjectConnectorProviderConfigs({ apiKey, baseUrl });\n const config = discovery.providerConfigs.find((config) => config.id === providerConfigId);\n if (!config) {\n return null;\n }\n const actions: z.output<typeof projectConnectorActionSchema>[] = [];\n if (config.actionIds.length > 0) {\n if (!catalog) {\n throw new ProjectConnectorClientError(\"catalog_not_configured\", 503);\n }\n const serviceActions = parseProjectConnectorResponse(\n z\n .array(projectConnectorCatalogActionSchema)\n .refine(\n (actions) => new Set(actions.map((action) => action.id)).size === actions.length,\n \"Catalog action IDs must be unique\",\n ),\n await callProjectConnector(() =>\n catalog.actions(config.service, projectConnectorCallOptions),\n ),\n );\n const actionsById = new Map(serviceActions.map((action) => [action.id, action]));\n // Fetching the service catalog never expands this configuration's allowlist.\n for (const actionId of new Set(config.actionIds)) {\n const action = actionsById.get(actionId);\n if (!action) {\n throw new ProjectConnectorClientError(\"action_not_found\", 502);\n }\n if (action.service !== config.service) {\n throw new ProjectConnectorClientError(\"action_identity_mismatch\", 502);\n }\n actions.push(action);\n }\n }\n return {\n projectId: discovery.projectId,\n providerConfigId: config.id,\n actions,\n };\n },\n async check() {\n // The project API has no health endpoint. An authenticated lookup of a fresh,\n // nonexistent request must return connection_request_not_found, not Unauthorized.\n try {\n await client.getConnectionRequest(\n `fragno-check-${crypto.randomUUID()}`,\n projectConnectorCallOptions,\n );\n } catch (error) {\n const knownFailure = projectConnectorClientErrorFromKnownFailure(error);\n if (knownFailure?.status === 404 && knownFailure.code === \"connection_request_not_found\") {\n return { authenticated: true as const };\n }\n if (knownFailure) {\n throw knownFailure;\n }\n throw error;\n }\n throw new ProjectConnectorClientError(\"unexpected_health_response\", 502);\n },\n async connect(\n externalUserId: string,\n input: z.infer<typeof projectConnectorConnectInputSchema>,\n ) {\n const request = await callProjectConnector(() =>\n client.connect.oauth(\n externalUserId,\n {\n ...(\"providerConfigId\" in input\n ? { providerConfigId: input.providerConfigId }\n : { service: input.service }),\n connectionName: input.connectionName,\n returnUri: input.returnUri,\n },\n projectConnectorCallOptions,\n ),\n );\n return parseProjectConnectorResponse(projectConnectorConnectionRequestSchema, request);\n },\n async getConnectionRequest(requestId: string) {\n const request = await callProjectConnector(() =>\n client.getConnectionRequest(requestId, projectConnectorCallOptions),\n );\n return parseProjectConnectorResponse(projectConnectorConnectionRequestSchema, request);\n },\n async getProfile(accountId: string) {\n const profile = await callProjectConnector(() =>\n client.getUserProfile(accountId, projectConnectorCallOptions),\n );\n return parseProjectConnectorResponse(projectConnectorProfileSchema, profile);\n },\n async execute(\n account: { externalUserId: string; providerConfigId: string; id: string },\n actionId: string,\n input: Record<string, unknown>,\n ) {\n const result = await callProjectConnector(() =>\n client.executeRaw(account.externalUserId, actionId, input, {\n providerConfigId: account.providerConfigId,\n connectedAccountId: account.id,\n retries: 0,\n }),\n );\n return parseProjectConnectorResponse(projectConnectorExecutionSchema, {\n executionId: result.executionId,\n actionId: result.actionId,\n output: result.data,\n });\n },\n };\n}\n\n/** Pins the SDK response to the saved project, provider, user, and request identity. */\nexport function confirmProjectConnectorRequest(\n expected: {\n id: string;\n projectId: string;\n providerConfigId: string;\n externalUserId: string;\n service: string;\n connectionName: string;\n },\n actual: Awaited<\n ReturnType<ReturnType<typeof createProjectConnectorClient>[\"getConnectionRequest\"]>\n >,\n): ProjectConnectorConnectionState {\n if (\n actual.id !== expected.id ||\n actual.projectId !== expected.projectId ||\n actual.providerConfigId !== expected.providerConfigId ||\n actual.externalUserId !== expected.externalUserId ||\n actual.service !== expected.service ||\n actual.connectionName !== expected.connectionName\n ) {\n throw new ProjectConnectorClientError(\"connection_identity_mismatch\", 502);\n }\n if (actual.status === \"initiated\" || actual.status === \"expired\") {\n return { status: actual.status };\n }\n if (actual.status === \"connected\") {\n return { status: \"connected\", connectedAccountId: actual.connectedAccountId };\n }\n return { status: \"failed\", errorCode: actual.errorCode, errorMessage: actual.errorMessage };\n}\n","import type { z } from \"zod\";\n\nimport { defineFragment } from \"@fragno-dev/core\";\nimport { withDatabase, type HookContext, type HookFn } from \"@fragno-dev/db\";\n\nimport {\n createProjectConnectorClient,\n type ProjectConnectorClientConfig,\n} from \"./project-connector-client\";\nimport type { projectConnectorNamedConnectionSchema } from \"./project-connector-contracts\";\nimport { projectConnectorSchema } from \"./schema\";\n\nexport interface ProjectConnectorConnectionReadinessChangedPayload {\n externalUserId: string;\n /** Provider service of the named connection's configuration, e.g. gmail. */\n service: string;\n connection: z.output<typeof projectConnectorNamedConnectionSchema>;\n /** Whether a confirmed account exists under this name. */\n ready: boolean;\n}\n\n/** Integrators own authentication and restrict OAuth return URLs; project keys remain server-only. */\nexport type ProjectConnectorFragmentConfig = ProjectConnectorClientConfig & {\n getExternalUserId: (headers: Headers) => string | null | Promise<string | null>;\n allowedReturnUrls: (url: URL) => boolean;\n /**\n * Fires when a write changes whether a named connection has a confirmed account: not ready when\n * the first request for the name starts, ready when a refresh confirms its first account, and not\n * ready for a name left without an account when a refresh moves its account ID to another name.\n * The gateway does not report consent or revocation, so both are noticed only through refresh.\n */\n onConnectionReadinessChanged?: (\n payload: ProjectConnectorConnectionReadinessChangedPayload,\n context: HookContext,\n ) => Promise<void> | void;\n};\n\ntype ProjectConnectorHooksMap = {\n onConnectionReadinessChanged: HookFn<ProjectConnectorConnectionReadinessChangedPayload>;\n};\n\n/** OOMOL Project Connector dependencies and scoped account persistence. */\nexport const projectConnectorFragmentDefinition = defineFragment<ProjectConnectorFragmentConfig>(\n \"project-connector-fragment\",\n)\n .extend(withDatabase(projectConnectorSchema))\n .withDependencies(({ config }) => ({\n projectConnector: createProjectConnectorClient(config),\n }))\n .provideHooks<ProjectConnectorHooksMap>(({ defineHook, config }) => ({\n onConnectionReadinessChanged: defineHook(async function (payload) {\n await config.onConnectionReadinessChanged?.(payload, this);\n }),\n }))\n .build();\n","import { decodeCursor, type Cursor } from \"@fragno-dev/db/cursor\";\nimport { z } from \"zod\";\n\nimport { defineRoutes } from \"@fragno-dev/core\";\n\nimport { projectConnectorFragmentDefinition } from \"./definition\";\nimport {\n confirmProjectConnectorRequest,\n ProjectConnectorClientError,\n} from \"./project-connector-client\";\nimport {\n projectConnectorAccountsSchema,\n projectConnectorNamedConnectionSchema,\n projectConnectorNamedRequestSchema,\n projectConnectorNamedAccountSchema,\n projectConnectorStatusSchema,\n projectConnectorProviderConfigsSchema,\n projectConnectorProviderActionsSchema,\n projectConnectorConnectInputSchema,\n projectConnectorConnectionSchema,\n projectConnectorProfileSchema,\n projectConnectorExecutionSchema,\n type ProjectConnectorConnectionState,\n} from \"./project-connector-contracts\";\nimport { projectConnectorSchema } from \"./schema\";\n\nfunction serializeProjectConnectorRequest(\n saved: Omit<z.output<typeof projectConnectorConnectionSchema>, \"id\"> & {\n id: { toString(): string };\n },\n): z.output<typeof projectConnectorConnectionSchema> {\n return {\n id: saved.id.toString(),\n projectId: saved.projectId,\n providerConfigId: saved.providerConfigId,\n externalUserId: saved.externalUserId,\n service: saved.service,\n connectionName: saved.connectionName,\n authorizationUrl: saved.authorizationUrl,\n expiresAt: saved.expiresAt,\n state: saved.state,\n };\n}\n\n/** Authenticated routes never accept a product user ID or account binding from the browser. */\nexport const projectConnectorRoutes = defineRoutes(projectConnectorFragmentDefinition).create(\n ({ config, deps, defineRoute }) => [\n defineRoute({\n method: \"GET\",\n path: \"/provider-configs\",\n outputSchema: projectConnectorProviderConfigsSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers }, { json, error }) {\n if (!(await config.getExternalUserId(headers))) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n try {\n return json(await deps.projectConnector.listProviderConfigs());\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/provider-configs/:providerConfigId/actions\",\n outputSchema: projectConnectorProviderActionsSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"PROVIDER_CONFIG_NOT_FOUND\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers, pathParams }, { json, error }) {\n if (!(await config.getExternalUserId(headers))) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n try {\n const actions = await deps.projectConnector.listProviderActions(\n pathParams.providerConfigId,\n );\n if (!actions) {\n return error(\n {\n code: \"PROVIDER_CONFIG_NOT_FOUND\",\n message: \"Provider configuration not found\",\n },\n 404,\n );\n }\n return json(actions);\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/status\",\n outputSchema: projectConnectorStatusSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers }, { json, error }) {\n if (!(await config.getExternalUserId(headers))) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n try {\n return json(await deps.projectConnector.check());\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/connection-requests\",\n inputSchema: projectConnectorConnectInputSchema,\n outputSchema: projectConnectorConnectionSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"RETURN_URI_NOT_ALLOWED\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers, input }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n const body = await input.valid();\n if (!config.allowedReturnUrls(new URL(body.returnUri))) {\n return error(\n { code: \"RETURN_URI_NOT_ALLOWED\", message: \"OAuth return URL is not allowed\" },\n 400,\n );\n }\n try {\n const remote = await deps.projectConnector.connect(externalUserId, body);\n if (\n remote.externalUserId !== externalUserId ||\n remote.connectionName !== body.connectionName ||\n (\"providerConfigId\" in body\n ? remote.providerConfigId !== body.providerConfigId\n : remote.service !== body.service)\n ) {\n throw new ProjectConnectorClientError(\"connection_identity_mismatch\", 502);\n }\n const connection = {\n id: remote.id,\n projectId: remote.projectId,\n providerConfigId: remote.providerConfigId,\n externalUserId,\n service: remote.service,\n connectionName: remote.connectionName,\n authorizationUrl: remote.authorizationUrl,\n expiresAt: remote.expiresAt,\n state: { status: \"initiated\" as const },\n };\n const named = {\n projectId: remote.projectId,\n providerConfigId: remote.providerConfigId,\n connectionName: body.connectionName,\n };\n await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findFirst(\"connectedAccount\", (b) =>\n b.whereIndex(\"idx_account_named_connection\", (eb) =>\n eb.and(\n eb(\"externalUserId\", \"=\", externalUserId),\n eb(\"projectId\", \"=\", named.projectId),\n eb(\"providerConfigId\", \"=\", named.providerConfigId),\n eb(\"connectionName\", \"=\", named.connectionName),\n ),\n ),\n ),\n )\n .mutate(({ forSchema, retrieveResult: [account] }) => {\n const uow = forSchema(projectConnectorSchema);\n uow.create(\"connectionRequest\", connection);\n // Another attempt leaves a name that already has a confirmed account ready.\n if (!account) {\n uow.triggerHook(\"onConnectionReadinessChanged\", {\n externalUserId,\n service: remote.service,\n connection: named,\n ready: false,\n });\n }\n })\n .execute();\n return json(connection);\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/connection-requests/by-name\",\n queryParameters: [\"projectId\", \"providerConfigId\", \"connectionName\"],\n outputSchema: projectConnectorNamedRequestSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"INVALID_SELECTOR\", \"CONNECTION_AMBIGUOUS\"],\n handler: async function ({ headers, query }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n const selector = projectConnectorNamedConnectionSchema.safeParse({\n projectId: query.get(\"projectId\"),\n providerConfigId: query.get(\"providerConfigId\"),\n connectionName: query.get(\"connectionName\"),\n });\n if (!selector.success) {\n return error(\n { code: \"INVALID_SELECTOR\", message: \"Invalid named connection selector\" },\n 400,\n );\n }\n const [page] = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findWithCursor(\"connectionRequest\", (b) =>\n b\n .whereIndex(\"idx_request_named_connection\", (eb) =>\n eb.and(\n eb(\"externalUserId\", \"=\", externalUserId),\n eb(\"projectId\", \"=\", selector.data.projectId),\n eb(\"providerConfigId\", \"=\", selector.data.providerConfigId),\n eb(\"connectionName\", \"=\", selector.data.connectionName),\n ),\n )\n .orderByIndex(\"idx_request_named_connection\", \"asc\")\n .pageSize(2),\n ),\n )\n .execute();\n if (page.items.length > 1) {\n return error(\n {\n code: \"CONNECTION_AMBIGUOUS\",\n message: \"Project Connector named connection matches multiple OAuth requests.\",\n },\n 409,\n );\n }\n const [saved] = page.items;\n return json({ request: saved ? serializeProjectConnectorRequest(saved) : null });\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/connection-requests/:requestId/refresh\",\n outputSchema: projectConnectorConnectionSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"REQUEST_NOT_FOUND\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers, pathParams }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n let confirmed: ProjectConnectorConnectionState | null = null;\n try {\n const result = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema)\n .findFirst(\"connectionRequest\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", pathParams.requestId)),\n )\n // Confirmation supplies the account ID later; acquire owned IDs in the single read phase.\n .find(\"connectedAccount\", (b) =>\n b\n .whereIndex(\"idx_account_external_user_id\", (eb) =>\n eb(\"externalUserId\", \"=\", externalUserId),\n )\n .select([\"id\", \"projectId\", \"providerConfigId\", \"service\", \"connectionName\"]),\n ),\n )\n .afterRetrieve(async (_uow, [saved]) => {\n // OCC retries must not reuse a confirmation prepared for an older snapshot.\n confirmed = null;\n if (\n !saved ||\n saved.externalUserId !== externalUserId ||\n saved.state.status !== \"initiated\"\n ) {\n return;\n }\n const remote = await deps.projectConnector.getConnectionRequest(saved.id.toString());\n confirmed = confirmProjectConnectorRequest(\n { ...saved, id: saved.id.toString() },\n remote,\n );\n })\n .mutate(({ forSchema, retrieveResult: [saved, accounts] }) => {\n if (!saved || saved.externalUserId !== externalUserId) {\n return null;\n }\n const state = confirmed ?? saved.state;\n const uow = forSchema(projectConnectorSchema);\n if (saved.state.status === \"initiated\" && state.status !== \"initiated\") {\n uow.update(\"connectionRequest\", saved.id, (b) => b.set({ state }).check());\n if (state.status === \"connected\") {\n const existing = accounts.find(\n (account) => account.id.toString() === state.connectedAccountId,\n );\n // Reauthorization replaces only the same owned account ID, not other accounts sharing its name.\n if (existing) {\n uow.delete(\"connectedAccount\", existing.id, (b) => b.check());\n }\n // An incoming ID belonging to another user must fail the create, never replace their binding.\n uow.create(\"connectedAccount\", {\n id: state.connectedAccountId,\n projectId: saved.projectId,\n providerConfigId: saved.providerConfigId,\n externalUserId: saved.externalUserId,\n service: saved.service,\n connectionName: saved.connectionName,\n });\n const sameName =\n (named: (typeof accounts)[number] | typeof saved) =>\n (account: (typeof accounts)[number]) =>\n account.projectId === named.projectId &&\n account.providerConfigId === named.providerConfigId &&\n account.connectionName === named.connectionName;\n // Reauthorization can move the account to this name, leaving its old name without one.\n if (\n existing &&\n !sameName(saved)(existing) &&\n !accounts.some((account) => account !== existing && sameName(existing)(account))\n ) {\n uow.triggerHook(\"onConnectionReadinessChanged\", {\n externalUserId,\n service: existing.service,\n connection: {\n projectId: existing.projectId,\n providerConfigId: existing.providerConfigId,\n connectionName: existing.connectionName,\n },\n ready: false,\n });\n }\n const wasReady = accounts.some(sameName(saved));\n if (!wasReady) {\n uow.triggerHook(\"onConnectionReadinessChanged\", {\n externalUserId,\n service: saved.service,\n connection: {\n projectId: saved.projectId,\n providerConfigId: saved.providerConfigId,\n connectionName: saved.connectionName,\n },\n ready: true,\n });\n }\n }\n }\n return serializeProjectConnectorRequest({ ...saved, state });\n })\n .execute();\n if (!result) {\n return error(\n { code: \"REQUEST_NOT_FOUND\", message: \"Connection request not found\" },\n 404,\n );\n }\n return json(result);\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/accounts\",\n queryParameters: [\"cursor\"],\n outputSchema: projectConnectorAccountsSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"INVALID_CURSOR\"],\n handler: async function ({ headers, query }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n let cursor: Cursor | null = null;\n const rawCursor = query.get(\"cursor\");\n if (rawCursor) {\n try {\n cursor = decodeCursor(rawCursor);\n const accountId = cursor.indexValues[\"id\"];\n if (\n cursor.indexName !== \"idx_account_external_user_id\" ||\n cursor.orderDirection !== \"asc\" ||\n cursor.pageSize !== 25 ||\n cursor.indexValues[\"externalUserId\"] !== externalUserId ||\n typeof accountId !== \"string\" ||\n accountId.length === 0\n ) {\n throw new Error(\"Account cursor does not match this user or query\");\n }\n } catch {\n return error({ code: \"INVALID_CURSOR\", message: \"Invalid account cursor\" }, 400);\n }\n }\n const [page] = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findWithCursor(\"connectedAccount\", (b) => {\n const ordered = b\n .whereIndex(\"idx_account_external_user_id\", (eb) =>\n eb(\"externalUserId\", \"=\", externalUserId),\n )\n .orderByIndex(\"idx_account_external_user_id\", \"asc\")\n .pageSize(25);\n return cursor ? ordered.after(cursor) : ordered;\n }),\n )\n .execute();\n return json({\n accounts: page.items.map((account) => ({\n id: account.id.toString(),\n projectId: account.projectId,\n providerConfigId: account.providerConfigId,\n externalUserId: account.externalUserId,\n service: account.service,\n connectionName: account.connectionName,\n })),\n cursor: page.cursor?.encode() ?? null,\n hasNextPage: page.hasNextPage,\n });\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/accounts/by-name\",\n queryParameters: [\"projectId\", \"providerConfigId\", \"connectionName\"],\n outputSchema: projectConnectorNamedAccountSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"INVALID_SELECTOR\", \"CONNECTION_AMBIGUOUS\"],\n handler: async function ({ headers, query }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n const selector = projectConnectorNamedConnectionSchema.safeParse({\n projectId: query.get(\"projectId\"),\n providerConfigId: query.get(\"providerConfigId\"),\n connectionName: query.get(\"connectionName\"),\n });\n if (!selector.success) {\n return error(\n { code: \"INVALID_SELECTOR\", message: \"Invalid named connection selector\" },\n 400,\n );\n }\n const [page] = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findWithCursor(\"connectedAccount\", (b) =>\n b\n .whereIndex(\"idx_account_named_connection\", (eb) =>\n eb.and(\n eb(\"externalUserId\", \"=\", externalUserId),\n eb(\"projectId\", \"=\", selector.data.projectId),\n eb(\"providerConfigId\", \"=\", selector.data.providerConfigId),\n eb(\"connectionName\", \"=\", selector.data.connectionName),\n ),\n )\n .orderByIndex(\"idx_account_named_connection\", \"asc\")\n .pageSize(2),\n ),\n )\n .execute();\n if (page.items.length > 1) {\n return error(\n {\n code: \"CONNECTION_AMBIGUOUS\",\n message: \"Project Connector named connection matches multiple confirmed accounts.\",\n },\n 409,\n );\n }\n const [account] = page.items;\n return json({\n account: account\n ? {\n id: account.id.toString(),\n projectId: account.projectId,\n providerConfigId: account.providerConfigId,\n externalUserId: account.externalUserId,\n service: account.service,\n connectionName: account.connectionName,\n }\n : null,\n });\n },\n }),\n defineRoute({\n method: \"GET\",\n path: \"/accounts/:accountId/profile\",\n outputSchema: projectConnectorProfileSchema,\n errorCodes: [\"UNAUTHENTICATED\", \"ACCOUNT_NOT_FOUND\", \"PROJECT_CONNECTOR_ERROR\"],\n handler: async function ({ headers, pathParams }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n const [account] = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findFirst(\"connectedAccount\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", pathParams.accountId)),\n ),\n )\n .execute();\n if (!account || account.externalUserId !== externalUserId) {\n return error({ code: \"ACCOUNT_NOT_FOUND\", message: \"Connected account not found\" }, 404);\n }\n try {\n const profile = await deps.projectConnector.getProfile(account.id.toString());\n if (\n profile.connectedAccountId !== account.id.toString() ||\n profile.externalUserId !== externalUserId ||\n profile.service !== account.service\n ) {\n throw new ProjectConnectorClientError(\"account_identity_mismatch\", 502);\n }\n return json(profile);\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/accounts/:accountId/actions/:actionId\",\n inputSchema: z.strictObject({ input: z.record(z.string(), z.unknown()) }),\n outputSchema: projectConnectorExecutionSchema,\n errorCodes: [\n \"UNAUTHENTICATED\",\n \"ACCOUNT_NOT_FOUND\",\n \"ACTION_SERVICE_MISMATCH\",\n \"PROJECT_CONNECTOR_ERROR\",\n ],\n handler: async function ({ headers, pathParams, input }, { json, error }) {\n const externalUserId = await config.getExternalUserId(headers);\n if (!externalUserId) {\n return error({ code: \"UNAUTHENTICATED\", message: \"Authentication required\" }, 401);\n }\n const body = await input.valid();\n const [account] = await this.handlerTx()\n .retrieve(({ forSchema }) =>\n forSchema(projectConnectorSchema).findFirst(\"connectedAccount\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", pathParams.accountId)),\n ),\n )\n .execute();\n if (!account || account.externalUserId !== externalUserId) {\n return error({ code: \"ACCOUNT_NOT_FOUND\", message: \"Connected account not found\" }, 404);\n }\n if (\n !pathParams.actionId.startsWith(`${account.service}.`) ||\n !/^[a-z0-9_-]+\\.[a-z0-9_-]+$/.test(pathParams.actionId)\n ) {\n return error(\n {\n code: \"ACTION_SERVICE_MISMATCH\",\n message: \"Action must belong to the connected account service\",\n },\n 400,\n );\n }\n try {\n return json(\n await deps.projectConnector.execute(\n { ...account, id: account.id.toString() },\n pathParams.actionId,\n body.input,\n ),\n );\n } catch (cause) {\n if (!(cause instanceof ProjectConnectorClientError)) {\n throw cause;\n }\n return error({ code: \"PROJECT_CONNECTOR_ERROR\", message: cause.message }, 502);\n }\n },\n }),\n ],\n);\n","import { createClientBuilder, type FragnoPublicClientConfig } from \"@fragno-dev/core/client\";\n\nimport { instantiate } from \"@fragno-dev/core\";\nimport type { FragnoPublicConfigWithDatabase } from \"@fragno-dev/db\";\n\nimport {\n projectConnectorFragmentDefinition,\n type ProjectConnectorFragmentConfig,\n} from \"./definition\";\nimport { projectConnectorRoutes } from \"./routes\";\n\nconst routes = [projectConnectorRoutes] as const;\n\n/** Creates a project-scoped connector with integrator-owned user authentication. */\nexport function createProjectConnectorFragment(\n config: ProjectConnectorFragmentConfig,\n fragnoConfig: FragnoPublicConfigWithDatabase,\n) {\n return instantiate(projectConnectorFragmentDefinition)\n .withConfig(config)\n .withRoutes(routes)\n .withOptions(fragnoConfig)\n .build();\n}\n\n/** Discover project OAuth configurations and select only server-verified accounts for actions. */\nexport function createProjectConnectorFragmentClients(fragnoConfig: FragnoPublicClientConfig = {}) {\n const builder = createClientBuilder(projectConnectorFragmentDefinition, fragnoConfig, routes);\n return {\n useProviderConfigs: builder.createHook(\"/provider-configs\"),\n useProviderActions: builder.createHook(\"/provider-configs/:providerConfigId/actions\"),\n useStatus: builder.createHook(\"/status\"),\n useAccounts: builder.createHook(\"/accounts\"),\n useNamedAccount: builder.createHook(\"/accounts/by-name\"),\n useNamedConnectionRequest: builder.createHook(\"/connection-requests/by-name\"),\n useProfile: builder.createHook(\"/accounts/:accountId/profile\"),\n connect: builder.createMutator(\"POST\", \"/connection-requests\", (invalidate) => {\n invalidate(\"GET\", \"/connection-requests/by-name\", {});\n }),\n refreshConnection: builder.createMutator(\n \"POST\",\n \"/connection-requests/:requestId/refresh\",\n (invalidate) => {\n invalidate(\"GET\", \"/accounts\", {});\n invalidate(\"GET\", \"/accounts/by-name\", {});\n invalidate(\"GET\", \"/connection-requests/by-name\", {});\n },\n ),\n executeAction: builder.createMutator(\"POST\", \"/accounts/:accountId/actions/:actionId\"),\n };\n}\n"],"x_google_ignoreList":[10,11,12,13,14,15,16,21,22],"mappings":";;;;;;;;;;;;;AAQA,SAASA,kBAAkBC,aAAa;CACvC,MAAMC,WAAWD,YAAYE,MAAM,GAAG,CAAC,CAACC,QAAQC,MAAMA,EAAEC,SAAS,CAAC;CAClE,MAAMC,QAAQ,CAAA;CACd,KAAK,MAAMC,WAAWN,UAAU;EAC/B,IAAIM,QAAQC,WAAW,GAAG,GAAG;GAC5BF,MAAMG,KAAKF,QAAQG,MAAM,CAAC,CAAC;GAC3B;EACD;EACA,IAAIH,YAAY,MAAM;GACrBD,MAAMG,KAAK,IAAI;GACf;EACD;EACA,IAAIF,QAAQC,WAAW,KAAK,GAAG;GAC9BF,MAAMG,KAAKF,QAAQG,MAAM,CAAC,CAAC;GAC3B;EACD;CACD;CACA,OAAOJ;AACR;;;;;;;;;;;;;;AAcA,SAASK,UAAUX,aAAaY,QAAQ;CACvC,MAAMC,kBAAkBb,YAAYE,MAAM,GAAG;CAC7C,MAAMY,gBAAgB,CAAA;CACtB,KAAK,MAAMP,WAAWM,iBAAiB;EACtC,IAAIN,QAAQF,WAAW,GAAG;GACzBS,cAAcL,KAAK,EAAE;GACrB;EACD;EACA,IAAIF,QAAQC,WAAW,GAAG,GAAG;GAC5B,MAAMO,OAAOR,QAAQG,MAAM,CAAC;GAC5B,MAAMM,QAAQJ,OAAOG;GACrB,IAAIC,UAAU,KAAK,GAAG,MAAM,IAAIC,MAAM,qC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E0B,aAAa,EAAEC,OAAO3B,EAAE4B,OAAO5B,EAAE6B,OAAO,GAAG7B,EAAE8B,QAAQ,CAAC,EAAE,CAAC;EACxET,cAAcT;EACdU,YAAY;GACV;GACA;GACA;GACA;EAAyB;EAE3BC,eAAO,CAAA;CA2CT,CAAC;AAAC,CC/jBUY,CAAsB;;AAGtC,SAAgBG,+BACdC,QACAC,cACA;CACA,OAAA,CAAA;AAKF;;AAGA,SAAgBE,sCAAsCF,eAAyC,CAAC,GAAG;CACjG,MAAMG,UAAUZ,oBAAoBE,oCAAoCO,cAAcJ,MAAM;CAC5F,OAAO;EACLQ,oBAAoBD,QAAQE,WAAW,mBAAmB;EAC1DC,oBAAoBH,QAAQE,WAAW,6CAA6C;EACpFE,WAAWJ,QAAQE,WAAW,SAAS;EACvCG,aAAaL,QAAQE,WAAW,WAAW;EAC3CI,iBAAiBN,QAAQE,WAAW,mBAAmB;EACvDK,2BAA2BP,QAAQE,WAAW,8BAA8B;EAC5EM,YAAYR,QAAQE,WAAW,8BAA8B;EAC7DO,SAAST,QAAQU,cAAc,QAAQ,yBAAyBC,eAAe;GAC7EA,WAAW,OAAO,gCAAgC,CAAC,CAAC;EACtD,CAAC;EACDC,mBAAmBZ,QAAQU,cACzB,QACA,4CACCC,eAAe;GACdA,WAAW,OAAO,aAAa,CAAC,CAAC;GACjCA,WAAW,OAAO,qBAAqB,CAAC,CAAC;GACzCA,WAAW,OAAO,gCAAgC,CAAC,CAAC;EACtD,CACF;EACAE,eAAeb,QAAQU,cAAc,QAAQ,wCAAwC;CACvF;AACF"}
@@ -0,0 +1,20 @@
1
+ //#region src/cli/authorization-browser.ts
2
+ /** Selects a shell-free browser launcher so OAuth query parameters remain literal arguments. */
3
+ function resolveAuthorizationBrowserLaunch(platform, url) {
4
+ if (platform === "darwin") return {
5
+ command: "open",
6
+ args: [url]
7
+ };
8
+ if (platform === "win32") return {
9
+ command: "rundll32.exe",
10
+ args: ["url.dll,FileProtocolHandler", url]
11
+ };
12
+ return {
13
+ command: "xdg-open",
14
+ args: [url]
15
+ };
16
+ }
17
+ //#endregion
18
+ export { resolveAuthorizationBrowserLaunch };
19
+
20
+ //# sourceMappingURL=authorization-browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authorization-browser.js","names":[],"sources":["../../src/cli/authorization-browser.ts"],"sourcesContent":["/** Selects a shell-free browser launcher so OAuth query parameters remain literal arguments. */\nexport function resolveAuthorizationBrowserLaunch(platform: NodeJS.Platform, url: string) {\n if (platform === \"darwin\") {\n return { command: \"open\", args: [url] };\n }\n if (platform === \"win32\") {\n return { command: \"rundll32.exe\", args: [\"url.dll,FileProtocolHandler\", url] };\n }\n return { command: \"xdg-open\", args: [url] };\n}\n"],"mappings":";;AACA,SAAgB,kCAAkC,UAA2B,KAAa;CACxF,IAAI,aAAa,UACf,OAAO;EAAE,SAAS;EAAQ,MAAM,CAAC,GAAG;CAAE;CAExC,IAAI,aAAa,SACf,OAAO;EAAE,SAAS;EAAgB,MAAM,CAAC,+BAA+B,GAAG;CAAE;CAE/E,OAAO;EAAE,SAAS;EAAY,MAAM,CAAC,GAAG;CAAE;AAC5C"}
@@ -0,0 +1,6 @@
1
+ //#region src/cli/cli.d.ts
2
+ /** Runs local connector commands through the same fragment HTTP boundary as an application. */
3
+ declare function runProjectConnectorCli(argv: string[], logger?: Pick<Console, "log" | "error">): Promise<number>;
4
+ //#endregion
5
+ export { runProjectConnectorCli };
6
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","names":[],"sources":["../../src/cli/cli.ts"],"mappings":";;iBAuEsB,uBACpB,gBACA,SAAQ,KAAK,4BACZ"}