@fragno-dev/stripe 0.1.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-Cw3xL5oQ.js","names":["resolveRouteFactories","context","routesOrFactories","routes","item","factoryRoutes","push","defineRoute","config","defineRoutes","_definition","create","fn","ctx","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","parsedBody","inputSchema","shouldValidateInput","constructor","config","rawBody","fromRequest","state","fromSSRContext","URLSearchParams","Headers","query","input","schema","valid","validateInput","#validateInput","Error","FormData","Blob","result","validate","issues","value","ResponseStream","writer","encoder","abortSubscribers","responseReadable","aborted","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","res","setTimeout","onAbort","listener","forEach","subscriber","ResponseStream","mergeHeaders","headerSources","mergedHeaders","Headers","headerSource","key","value","entries","set","Array","isArray","Object","OutputContext","error","message","code","initOrStatus","headers","Response","json","status","empty","defaultHeaders","mergedHeaders$1","object","jsonStream","cb","onError","readable","writable","TransformStream","stream","e","Error","console","close","responseReadable","RequestOutputContext","outputSchema","constructor","extractPathParams","pathPattern","segments","split","filter","s","length","names","segment","startsWith","push","slice","buildPath","params","patternSegments","builtSegments","name","value","Error","encodeURIComponent","join","FragnoClientError","Error","code","constructor","message","options","cause","name","FragnoClientFetchError","fromUnknownFetchError","error","FragnoClientFetchNetworkError","FragnoClientFetchAbortError","FragnoClientUnknownApiError","status","FragnoClientApiError","fromResponse","response","unknown","json","parseContentType","contentType","trimmed","trim","parts","split","map","part","mediaType","typeParts","length","type","subtype","toLowerCase","parameters","i","param","equalIndex","indexOf","key","slice","value","startsWith","endsWith","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientUnknownApiError","createAbortPromise","abortSignal","Promise","_","reject","abortHandler","aborted","addEventListener","once","handleNdjsonStreamingFirstItem","response","store","options","body","decoder","TextDecoder","reader","getReader","buffer","firstItem","items","releaseLock","done","value","race","read","decode","stream","lines","split","pop","line","trim","jsonObject","JSON","parse","push","streamingPromise","continueStreaming","parseError","cause","error","setError","clientError","initialBuffer","lines$1","setData","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","epoch","atom","initialValue","listeners","$atom","get","lc","listen","value","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","atom","epoch","onMount","computedStore","stores","cb","batched","Array","isArray","previousArgs","currentEpoch","set","args","map","$store","get","some","arg","i","value","then","t","asyncValue","$computed","undefined","timer","run","clearTimeout","setTimeout","unbinds","listen","unbind","computed","fn","atom","map","initial","$map","setKey","key","value","oldMap","notify","allTasks","stores","SSR_ENABLED","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","stores$1","storesInitialValue","value","loading","set","unwrapAtom","value","get","unwrapObject","params","Object","fromEntries","entries","map","key","isReadableAtom","lc","notify","off","subscribe","mergeFetcherConfigs","authorConfig","userConfig","type","authorOpts","options","userOpts","Object","keys","length","headers","mergeHeaders","author","user","merged","Headers","forEach","value","key","set","next","done","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","resolveRouteFactories","getMountRoute","RequestInputContext","RequestOutputContext","buildPath","extractPathParams","FragnoClientApiError","FragnoClientError","FragnoClientFetchAbortError","FragnoClientFetchError","FragnoClientFetchNetworkError","FragnoClientUnknownApiError","parseContentType","handleNdjsonStreamingFirstItem","SSR_ENABLED","addStore","getInitialData","unwrapObject","mergeFetcherConfigs","computed","task","nanoquery","GET_HOOK_SYMBOL","Symbol","MUTATOR_HOOK_SYMBOL","STORE_SYMBOL","buildUrl","config","params","baseUrl","mountRoute","path","pathParams","queryParams","normalizedPathParams","normalizedQueryParams","filteredQueryParams","Object","fromEntries","entries","filter","_","value","searchParams","URLSearchParams","toString","getCacheKey","method","pathParamValues","map","name","queryParamValues","keys","sort","key","v","isStreamingResponse","response","contentType","headers","get","subtype","isGetHook","hook","isMutatorHook","isStore","obj","ClientBuilder","publicConfig","fragmentConfig","fetcherConfig","cache","Map","createFetcherStore","createMutatorStore","invalidateKeys","constructor","cacheEntries","createStore","query","getFetcher","fetcher","defaultOptions","getFetcherOptions","#getFetcher","type","fetch","#getFetcherOptions","options","createHook","route","routes","find","r","outputSchema","Error","createRouteQueryHook","createMutator","onInvalidate","createRouteQueryMutator","#createRouteQueryHook","fetcherOptions","callServerSideHandler","handler","fromSSRContext","executeQuery","window","url","error","fromUnknownFetchError","ok","fromResponse","store","args","initialData","d","join","isStreaming","json","firstItem","setData","set","loading","Array","isArray","length","data","setError","onErrorRetry","dedupeTime","Infinity","streamingPromise","#createRouteQueryMutator","invalidate","executeMutateQuery","body","inputSchema","JSON","stringify","mutatorStore","bind","status","onError","console","mutateQuery","#invalidate","prefix","k","startsWith","createClientBuilder","definition","routesOrFactories","authorFetcherConfig","deps","services","serviceDeps","mergedFetcherConfig","SimpleQueryInterface","TableToInsertValues","Logger","StripeFragmentConfig","StripeFragmentDeps","StripeFragmentServices","defineFragment","stripeFragmentDefinition","extend","x","withDependencies","providesBaseService","build","z","defineRoutes","stripeFragmentDefinition","webhookRoutesFactory","create","config","deps","services","defineRoute","method","path","outputSchema","object","success","boolean","errorCodes","const","handler","z","CustomerResponseSchema","object","id","string","literal","balance","number","business_name","optional","created","currency","nullable","deleted","void","delinquent","boolean","description","email","individual_name","invoice_credit_balance","record","invoice_prefix","livemode","metadata","name","next_invoice_sequence","phone","preferred_locales","array","infer","z","CustomerResponseSchema","defineRoutes","stripeFragmentDefinition","customersRoutesFactory","create","deps","config","defineRoute","method","path","inputSchema","object","limit","number","int","positive","max","optional","default","describe","startingAfter","string","outputSchema","customers","array","hasMore","boolean","handler","returnUrl","url","redirect","errorCodes","const","z","SubscriptionReponseSchema","object","id","string","stripeSubscriptionId","stripeCustomerId","stripePriceId","referenceId","nullable","status","enum","periodStart","date","periodEnd","trialStart","trialEnd","cancelAtPeriodEnd","boolean","cancelAt","seats","number","createdAt","updatedAt","SubscriptionUpgradeRequestSchema","priceId","describe","quantity","positive","successUrl","url","cancelUrl","returnUrl","optional","promotionCode","subscriptionId","SubscriptionResponse","infer","z","SubscriptionReponseSchema","SubscriptionUpgradeRequestSchema","SubscriptionResponse","defineRoutes","stripeFragmentDefinition","subscriptionsRoutesFactory","create","deps","services","config","defineRoute","method","path","outputSchema","object","subscriptions","array","handler","inputSchema","url","string","redirect","boolean","sessionId","optional","errorCodes","const","returnUrl","describe","subscriptionId","z","ProductResponseSchema","object","id","string","literal","active","boolean","created","number","default_price","union","any","nullable","optional","deleted","void","description","images","array","livemode","marketing_features","metadata","name","package_dimensions","shippable","statement_descriptor","tax_code","type","unit_label","updated","url","infer","z","ProductResponseSchema","defineRoutes","stripeFragmentDefinition","productsRoutesFactory","create","deps","config","defineRoute","method","path","inputSchema","object","limit","number","int","positive","max","optional","default","describe","startingAfter","string","outputSchema","products","array","hasMore","boolean","handler","z","PriceResponseSchema","object","id","string","literal","active","boolean","billing_scheme","created","number","currency","custom_unit_amount","any","nullable","optional","deleted","void","livemode","lookup_key","metadata","nickname","product","union","recurring","aggregate_usage","interval","enum","interval_count","meter","trial_period_days","usage_type","tax_behavior","tiers_mode","transform_quantity","type","unit_amount","unit_amount_decimal","infer","z","PriceResponseSchema","defineRoutes","stripeFragmentDefinition","pricesRoutesFactory","create","deps","config","defineRoute","method","path","inputSchema","object","limit","number","int","positive","max","optional","default","describe","startingAfter","string","outputSchema","prices","array","hasMore","boolean","handler","createClientBuilder","FragnoPublicClientConfig","FragnoPublicConfig","StripeFragmentConfig","stripeFragmentDefinition","webhookRoutesFactory","customersRoutesFactory","subscriptionsRoutesFactory","productsRoutesFactory","pricesRoutesFactory","routes","const","createStripeFragment","config","fragnoConfig","FragnoPublicConfigWithDatabase","createStripeFragmentClients","builder","useCustomers","createHook","useProducts","usePrices","useSubscription","useBillingPortal","createMutator","upgradeSubscription","cancelSubscription","StripeFragmentDeps","StripeFragmentServices","Logger","FragnoRouteConfig"],"sources":["../../../fragno/dist/api/route.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/internal/path.js","../../../fragno/dist/client/client-error.js","../../../fragno/dist/util/content-type.js","../../../fragno/dist/client/internal/ndjson-streaming.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/task/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/clean-stores/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/atom/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/lifecycle/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/computed/index.js","../../../../node_modules/.pnpm/nanostores@1.1.0/node_modules/nanostores/map/index.js","../../../fragno/dist/util/ssr.js","../../../fragno/dist/util/nanostores.js","../../../fragno/dist/client/internal/fetcher-merge.js","../../../../node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js","../../../../node_modules/.pnpm/@nanostores+query@0.3.4_nanostores@1.1.0/node_modules/@nanostores/query/dist/nanoquery.js","../../../fragno/dist/client/client.js","../../src/definition.ts","../../src/routes/webhooks.ts","../../src/models/customers.ts","../../src/routes/customers.ts","../../src/models/subscriptions.ts","../../src/routes/subscriptions.ts","../../src/models/products.ts","../../src/routes/products.ts","../../src/models/prices.ts","../../src/routes/prices.ts","../../src/index.ts"],"sourcesContent":["//#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\n//#endregion\nexport { defineRoute, defineRoutes, resolveRouteFactories };\n//# sourceMappingURL=route.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\n//#endregion\nexport { getMountRoute };\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\t#issues;\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\tget issues() {\n\t\treturn this.#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\n//#endregion\nexport { FragnoApiError, FragnoApiValidationError };\n//# sourceMappingURL=error.js.map","import { FragnoApiValidationError } from \"./error.js\";\n\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#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.#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\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\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\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\n//#endregion\nexport { RequestInputContext };\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#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: () => {\n\t\t\t\tthis.abort();\n\t\t\t}\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} catch {}\n\t}\n\twrite(input) {\n\t\treturn this.writeRaw(JSON.stringify(input) + \"\\n\");\n\t}\n\tsleep(ms) {\n\t\treturn new Promise((res) => setTimeout(res, ms));\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.aborted) {\n\t\t\tthis.#aborted = true;\n\t\t\tthis.#abortSubscribers.forEach((subscriber) => subscriber());\n\t\t}\n\t}\n};\n\n//#endregion\nexport { ResponseStream };\n//# sourceMappingURL=response-stream.js.map","import { ResponseStream } from \"./internal/response-stream.js\";\n\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/**\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$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: 201,\n\t\t\t\theaders: mergedHeaders$1\n\t\t\t});\n\t\t}\n\t\tif (typeof initOrStatus === \"number\") {\n\t\t\tconst mergedHeaders$1 = mergeHeaders(defaultHeaders, headers);\n\t\t\treturn new Response(null, {\n\t\t\t\tstatus: initOrStatus,\n\t\t\t\theaders: mergedHeaders$1\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\t(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\tstream.close();\n\t\t\t}\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) {\n\t\tsuper();\n\t\tthis.#outputSchema = outputSchema;\n\t}\n};\n\n//#endregion\nexport { OutputContext, RequestOutputContext };\n//# sourceMappingURL=request-output-context.js.map","//#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\n//#endregion\nexport { buildPath, extractPathParams };\n//# sourceMappingURL=path.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\n//#endregion\nexport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError };\n//# sourceMappingURL=client-error.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\n//#endregion\nexport { parseContentType };\n//# sourceMappingURL=content-type.js.map","import { FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientUnknownApiError } from \"../client-error.js\";\n\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}\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\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tif (firstItem === null) {\n\t\t\t\t\t\tfirstItem = jsonObject;\n\t\t\t\t\t\tconst streamingPromise = continueStreaming(reader, decoder, buffer, items, store, abortSignal);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tfirstItem,\n\t\t\t\t\t\t\tstreamingPromise\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 500, { cause: parseError });\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 FragnoClientError) {\n\t\t\tstore?.setError(error);\n\t\t\tthrow error;\n\t\t} else {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 500, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\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\ttry {\n\t\twhile (true) {\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\tif (buffer.trim()) {\n\t\t\t\t\tconst lines$1 = buffer.split(\"\\n\");\n\t\t\t\t\tfor (const line of lines$1) {\n\t\t\t\t\t\tif (!line.trim()) continue;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t\t\t} catch (parseError) {\n\t\t\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\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\tconst lines = buffer.split(\"\\n\");\n\t\t\tbuffer = lines.pop() || \"\";\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (!line.trim()) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst jsonObject = JSON.parse(line);\n\t\t\t\t\titems.push(jsonObject);\n\t\t\t\t\tstore?.setData([...items]);\n\t\t\t\t} catch (parseError) {\n\t\t\t\t\tthrow new FragnoClientUnknownApiError(\"Failed to parse NDJSON line\", 400, { cause: parseError });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof FragnoClientError) store?.setError(error);\n\t\telse {\n\t\t\tconst clientError = new FragnoClientUnknownApiError(\"Unknown streaming error\", 400, { cause: error });\n\t\t\tstore?.setError(clientError);\n\t\t\tthrow clientError;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn items;\n}\n\n//#endregion\nexport { handleNdjsonStreamingFirstItem };\n//# sourceMappingURL=ndjson-streaming.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 let clean = Symbol('clean')\n\nexport let 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\nexport let 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 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 ) {\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 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 let 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","import { atom, epoch } from '../atom/index.js'\nimport { onMount } from '../lifecycle/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 === epoch) return\n currentEpoch = 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 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 = 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\n//#region src/util/ssr.ts\nlet stores = [];\nconst SSR_ENABLED = false;\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 (typeof window !== \"undefined\" && 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$1 = getStores();\n\tconst storesInitialValue = /* @__PURE__ */ new Map();\n\tfor (const store of stores$1) {\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\n//#endregion\nexport { SSR_ENABLED, addStore, cleanStores, getFinalStoreValues, getInitialData, hydrateFromWindow };\n//# sourceMappingURL=ssr.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\n//#endregion\nexport { isReadableAtom, unwrapObject };\n//# sourceMappingURL=nanostores.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) => merged.set(key, value));\n\tif (merged.keys().next().done) return;\n\treturn merged;\n}\n\n//#endregion\nexport { mergeFetcherConfigs };\n//# sourceMappingURL=fetcher-merge.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 { resolveRouteFactories } from \"../api/route.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 { buildPath, extractPathParams } from \"../api/internal/path.js\";\nimport { FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError } from \"./client-error.js\";\nimport { parseContentType } from \"../util/content-type.js\";\nimport { handleNdjsonStreamingFirstItem } from \"./internal/ndjson-streaming.js\";\nimport { SSR_ENABLED, addStore, getInitialData } from \"../util/ssr.js\";\nimport { unwrapObject } from \"../util/nanostores.js\";\nimport { mergeFetcherConfigs } from \"./internal/fetcher-merge.js\";\nimport { computed, task } from \"nanostores\";\nimport { nanoquery } from \"@nanostores/query\";\n\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\");\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({ cache: this.#cache });\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(obj) {\n\t\treturn {\n\t\t\tobj,\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(this.#fragmentConfig),\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 fetch;\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 ${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(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\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\") 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\tif (SSR_ENABLED) {\n\t\t\t\t\t\t\tconst initialData = getInitialData(key.map((d) => typeof d === \"string\" ? d : d.get()).join(\"\"));\n\t\t\t\t\t\t\tif (initialData) return initialData;\n\t\t\t\t\t\t}\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\") return [];\n\t\t\t\t\t\tif (isStreaming === \"ndjson\") {\n\t\t\t\t\t\t\tconst { firstItem } = await handleNdjsonStreamingFirstItem(response, {\n\t\t\t\t\t\t\t\tsetData: (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\tloading: !(Array.isArray(value) && value.length > 0),\n\t\t\t\t\t\t\t\t\t\tdata: 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\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 [firstItem];\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) => invalidate(\"GET\", route.path, params)) {\n\t\tconst method = route.method;\n\t\tconst baseUrl = this.#publicConfig.baseUrl ?? \"\";\n\t\tconst mountRoute = getMountRoute(this.#fragmentConfig);\n\t\tconst fetcher = this.#getFetcher();\n\t\tconst fetcherOptions = this.#getFetcherOptions();\n\t\tasync function executeMutateQuery({ body, path, query }) {\n\t\t\tif (typeof window === \"undefined\") 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\tresponse = await fetcher(url, {\n\t\t\t\t\t...fetcherOptions,\n\t\t\t\t\tmethod,\n\t\t\t\t\tbody: body !== void 0 ? JSON.stringify(body) : void 0\n\t\t\t\t});\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\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"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 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\tif (typeof body === \"undefined\" && route.inputSchema !== void 0) throw new Error(\"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 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 = publicConfig.mountRoute ?? `/${definition.name}`;\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\n//#endregion\nexport { ClientBuilder, FragnoClientApiError, FragnoClientError, FragnoClientFetchAbortError, FragnoClientFetchError, FragnoClientFetchNetworkError, FragnoClientUnknownApiError, buildUrl, createClientBuilder, getCacheKey, isGetHook, isMutatorHook, isStore };\n//# sourceMappingURL=client.js.map","import Stripe from \"stripe\";\nimport type { SimpleQueryInterface, TableToInsertValues } from \"@fragno-dev/db/query\";\nimport type {\n Logger,\n StripeFragmentConfig,\n StripeFragmentDeps,\n StripeFragmentServices,\n} from \"./types\";\nimport { stripeSchema } from \"./database/schema\";\nimport { defineFragment } from \"@fragno-dev/core\";\nimport { withDatabase } from \"@fragno-dev/db\";\nimport { stripeSubscriptionToInternalSubscription } from \"./utils\";\n\nconst LOG_PREFIX = \"[Stripe Fragment]\";\nconst defaultLogger: Logger = {\n info: (...data) => console.info(LOG_PREFIX, ...data),\n error: (...data) => console.error(LOG_PREFIX, ...data),\n warn: (...data) => console.warn(LOG_PREFIX, ...data),\n debug: (...data) => console.debug(LOG_PREFIX, ...data),\n log: (...data) => console.log(LOG_PREFIX, ...data),\n};\n\nconst asExternalSubscription = <T extends { id: { externalId: string }; status: string }>(\n subscription: T,\n) => ({\n ...subscription,\n id: subscription.id.externalId,\n status: subscription.status as Stripe.Subscription.Status,\n});\n\nfunction createStripeServices(\n deps: StripeFragmentDeps,\n db: SimpleQueryInterface<typeof stripeSchema>,\n): StripeFragmentServices {\n const services: StripeFragmentServices = {\n getStripeClient(): Stripe {\n return deps.stripe;\n },\n createSubscription: async (\n data: Omit<\n TableToInsertValues<typeof stripeSchema.tables.subscription>,\n \"id\" | \"createdAt\" | \"updatedAt\"\n >,\n ) => {\n return (await db.create(\"subscription\", data)).externalId;\n },\n updateSubscription: async (\n id: string,\n data: Partial<Omit<TableToInsertValues<typeof stripeSchema.tables.subscription>, \"id\">>,\n ) => {\n await db.update(\"subscription\", id, (b) => b.set({ ...data, updatedAt: new Date() }));\n },\n\n getSubscriptionByStripeId: async (stripeSubscriptionId: string) => {\n const result = await db.findFirst(\"subscription\", (b) =>\n b.whereIndex(\"idx_stripe_subscription_id\", (eb) =>\n eb(\"stripeSubscriptionId\", \"=\", stripeSubscriptionId),\n ),\n );\n if (!result) {\n return null;\n }\n\n return asExternalSubscription(result);\n },\n getSubscriptionsByStripeCustomerId: async (stripeCustomerId: string) => {\n return (\n await db.find(\"subscription\", (b) =>\n b.whereIndex(\"idx_stripe_customer_id\", (eb) =>\n eb(\"stripeCustomerId\", \"=\", stripeCustomerId),\n ),\n )\n ).map(asExternalSubscription);\n },\n getSubscriptionById: async (id: string) => {\n const result = await db.findFirst(\"subscription\", (b) =>\n b.whereIndex(\"primary\", (eb) => eb(\"id\", \"=\", id)),\n );\n if (!result) {\n return null;\n }\n return asExternalSubscription(result);\n },\n getSubscriptionsByReferenceId: async (referenceId: string) => {\n const result = await db.find(\"subscription\", (b) =>\n b.whereIndex(\"idx_reference_id\", (eb) => eb(\"referenceId\", \"=\", referenceId)),\n );\n if (result.length == 0) {\n return [];\n }\n return result.map(asExternalSubscription);\n },\n\n deleteSubscription: async (id: string) => {\n await db.delete(\"subscription\", id);\n },\n\n deleteSubscriptionsByReferenceId: async (referenceId: string) => {\n const uow = db\n .createUnitOfWork()\n .find(\"subscription\", (b) =>\n b.whereIndex(\"idx_reference_id\", (eb) => eb(\"referenceId\", \"=\", referenceId)),\n );\n\n const [subscriptions] = await uow.executeRetrieve();\n subscriptions.forEach((sub) => sub && uow.delete(\"subscription\", sub.id));\n\n return await uow.executeMutations();\n },\n\n getAllSubscriptions: async () => {\n return (await db.find(\"subscription\", (b) => b.whereIndex(\"primary\"))).map(\n asExternalSubscription,\n );\n },\n\n /* Retrieve Stripe Subscription and create/update/delete internal entity */\n syncStripeSubscriptions: async (referenceId: string, stripeCustomerId: string) => {\n const stripeSubscriptions = await deps.stripe.subscriptions.list({\n customer: stripeCustomerId,\n status: \"all\",\n });\n\n if (stripeSubscriptions.data.length === 0) {\n await services.deleteSubscriptionsByReferenceId(referenceId);\n return { success: true };\n }\n\n const uow = db\n .createUnitOfWork()\n .find(\"subscription\", (b) =>\n b.whereIndex(\"idx_reference_id\", (eb) => eb(\"referenceId\", \"=\", referenceId)),\n );\n\n const [existingSubscriptions] = await uow.executeRetrieve();\n\n // Mutation phase: process all Stripe subscriptions (including canceled)\n for (const stripeSubscription of stripeSubscriptions.data) {\n const existingSubscription = existingSubscriptions.find(\n (sub) => sub.stripeSubscriptionId === stripeSubscription.id,\n );\n\n if (existingSubscription) {\n // Update existing subscription with optimistic concurrency control\n uow.update(\"subscription\", existingSubscription.id, (b) =>\n b\n .set({\n ...stripeSubscriptionToInternalSubscription(stripeSubscription),\n updatedAt: new Date(),\n })\n .check(),\n );\n } else {\n // Create new subscription\n uow.create(\"subscription\", {\n ...stripeSubscriptionToInternalSubscription(stripeSubscription),\n referenceId: referenceId ?? null,\n updatedAt: new Date(),\n });\n }\n }\n\n // Execute all mutations and return result\n return uow.executeMutations();\n },\n };\n return services;\n}\n\nexport const stripeFragmentDefinition = defineFragment<StripeFragmentConfig>(\"stripe\")\n .extend(withDatabase(stripeSchema))\n .withDependencies(({ config }) => {\n const stripeClient = new Stripe(config.stripeSecretKey, config.stripeClientOptions ?? {});\n\n return {\n stripe: stripeClient,\n log: config.logger ? config.logger : defaultLogger,\n };\n })\n .providesBaseService(({ deps }) => {\n return {\n ...createStripeServices(deps, deps.db),\n };\n })\n .build();\n","import { z } from \"zod\";\nimport Stripe from \"stripe\";\nimport { eventToHandler, type SupportedStripeEvent } from \"../webhook/handlers\";\nimport { defineRoutes } from \"@fragno-dev/core\";\nimport { stripeFragmentDefinition } from \"../definition\";\n\nexport const webhookRoutesFactory = defineRoutes(stripeFragmentDefinition).create(\n ({ config, deps, services, defineRoute }) => {\n return [\n defineRoute({\n method: \"POST\",\n path: \"/webhook\",\n outputSchema: z.object({\n success: z.boolean(),\n }),\n errorCodes: [\"MISSING_SIGNATURE\", \"WEBHOOK_SIGNATURE_INVALID\", \"WEBHOOK_ERROR\"] as const,\n handler: async ({ headers, rawBody }, { json, error }) => {\n // Get the signature\n const signature = headers.get(\"stripe-signature\");\n\n if (!signature) {\n return error(\n { message: \"Missing stripe-signature header\", code: \"MISSING_SIGNATURE\" },\n 400,\n );\n }\n\n if (!rawBody) {\n return error(\n { message: \"Missing request body for webhook verification\", code: \"WEBHOOK_ERROR\" },\n 400,\n );\n }\n\n // Verify the webhook signature\n let event: Stripe.Event;\n try {\n // Support both Stripe v18 (constructEvent) and v19+ (constructEventAsync)\n if (typeof deps.stripe.webhooks.constructEventAsync === \"function\") {\n // Stripe v19+ - use async method\n event = await deps.stripe.webhooks.constructEventAsync(\n rawBody,\n signature,\n config.webhookSecret,\n );\n } else {\n // Stripe v18 - use sync method\n event = deps.stripe.webhooks.constructEvent(rawBody, signature, config.webhookSecret);\n }\n } catch (err) {\n if (err instanceof Stripe.errors.StripeSignatureVerificationError) {\n return error(\n {\n message: `Webhook signature verification failed`,\n code: \"WEBHOOK_SIGNATURE_INVALID\",\n },\n 400,\n );\n }\n throw err;\n }\n\n if (!event) {\n return error({ message: \"Failed to construct event\", code: \"WEBHOOK_ERROR\" }, 400);\n }\n\n if (config.onEvent) {\n deps.log.info(\"Running user callback event\");\n await config.onEvent({ event, stripeClient: deps.stripe });\n }\n\n const eventHandler = eventToHandler[event.type as SupportedStripeEvent];\n if (!eventHandler) {\n deps.log.info(`Webhook event ${event.type}: ${event.id} ignored`);\n return json({ success: true });\n }\n\n deps.log.info(`Executing event handler for ${event.type}: ${event.id}`);\n await eventHandler({ event, services, deps, config });\n\n return json({ success: true });\n },\n }),\n ];\n },\n);\n","import { z } from \"zod\";\n\nexport const CustomerResponseSchema = z.object({\n id: z.string(),\n object: z.literal(\"customer\"),\n balance: z.number(),\n business_name: z.string().optional(),\n created: z.number(),\n currency: z.string().nullable().optional(),\n deleted: z.void().optional(),\n delinquent: z.boolean().nullable().optional(),\n description: z.string().nullable(),\n email: z.string().nullable(),\n individual_name: z.string().optional(),\n invoice_credit_balance: z.record(z.string(), z.number()).optional(),\n invoice_prefix: z.string().nullable().optional(),\n livemode: z.boolean(),\n metadata: z.record(z.string(), z.string()),\n name: z.string().nullable().optional(),\n next_invoice_sequence: z.number().optional(),\n phone: z.string().nullable().optional(),\n preferred_locales: z.array(z.string()).nullable().optional(),\n});\n\nexport type CustomerResponseSchema = z.infer<typeof CustomerResponseSchema>;\n","import { z } from \"zod\";\nimport { CustomerResponseSchema } from \"../models/customers\";\nimport { stripeToApiError } from \"./errors\";\nimport { defineRoutes } from \"@fragno-dev/core\";\nimport { stripeFragmentDefinition } from \"../definition\";\n\nexport const customersRoutesFactory = defineRoutes(stripeFragmentDefinition).create(\n ({ deps, config, defineRoute }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/customers\",\n inputSchema: z.object({\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .default(50)\n .describe(\"Number of customers to return (max 100)\"),\n startingAfter: z\n .string()\n .optional()\n .describe(\"Customer ID to start after for pagination\"),\n }),\n outputSchema: z.object({\n customers: z.array(CustomerResponseSchema),\n hasMore: z.boolean().describe(\"Whether there are more customers to fetch\"),\n }),\n handler: async ({ query }, { json, error }) => {\n if (!config.enableAdminRoutes) {\n return error({ message: \"Unauthorized\", code: \"UNAUTHORIZED\" }, 401);\n }\n\n const limit = Number(query.get(\"limit\")) || undefined;\n const startingAfter = query.get(\"startingAfter\") || undefined;\n\n const customers = await deps.stripe.customers.list({\n limit,\n starting_after: startingAfter,\n });\n return json({\n customers: customers.data,\n hasMore: customers.has_more,\n });\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/portal\",\n inputSchema: z.object({\n returnUrl: z.url().describe(\"URL to redirect to after completing billing portal\"),\n }),\n outputSchema: z.object({\n url: z.url().describe(\"URL to redirect to after cancellation\"),\n redirect: z.boolean().describe(\"Whether to redirect to the URL\"),\n }),\n errorCodes: [\"NO_STRIPE_CUSTOMER_FOR_ENTITY\"] as const,\n handler: async (context, { json, error }) => {\n const body = await context.input.valid();\n const { stripeCustomerId } = await config.resolveEntityFromRequest(context);\n\n if (!stripeCustomerId) {\n return error(\n {\n message: \"No stripe customer to create billing portal for\",\n code: \"NO_STRIPE_CUSTOMER_FOR_ENTITY\",\n },\n 400,\n );\n }\n\n try {\n const portalSession = await deps.stripe.billingPortal.sessions.create({\n customer: stripeCustomerId,\n return_url: body.returnUrl,\n });\n\n return json({\n url: portalSession.url,\n redirect: true,\n });\n } catch (err: unknown) {\n throw stripeToApiError(err);\n }\n },\n }),\n ];\n },\n);\n","import { z } from \"zod\";\n\nexport const SubscriptionReponseSchema = z.object({\n id: z.string(),\n stripeSubscriptionId: z.string(),\n stripeCustomerId: z.string(),\n stripePriceId: z.string(),\n referenceId: z.string().nullable(),\n status: z.enum([\n \"active\",\n \"canceled\",\n \"incomplete\",\n \"incomplete_expired\",\n \"past_due\",\n \"paused\",\n \"trialing\",\n \"unpaid\",\n ]),\n periodStart: z.date().nullable(),\n periodEnd: z.date().nullable(),\n trialStart: z.date().nullable(),\n trialEnd: z.date().nullable(),\n cancelAtPeriodEnd: z.boolean().nullable(),\n cancelAt: z.date().nullable(),\n seats: z.number().nullable(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport const SubscriptionUpgradeRequestSchema = z.object({\n priceId: z.string().describe(\"Stripe price ID to subscribe/upgrade to\"),\n quantity: z.number().positive().describe(\"Number of seats\"),\n successUrl: z.url().describe(\"Redirect URL after successful checkout\"),\n cancelUrl: z.url().describe(\"Redirect URL if checkout is cancelled\"),\n returnUrl: z.string().optional().describe(\"Return URL for billing portal\"),\n promotionCode: z.string().optional().describe(\"Promotion code to apply\"),\n subscriptionId: z\n .string()\n .optional()\n .describe(\n \"Subscription ID to upgrade, if none provided assume the active subscription of the user.\",\n ),\n});\n\nexport type SubscriptionResponse = z.infer<typeof SubscriptionReponseSchema>;\n","import { z } from \"zod\";\nimport {\n SubscriptionReponseSchema,\n SubscriptionUpgradeRequestSchema,\n type SubscriptionResponse,\n} from \"../models/subscriptions\";\nimport { stripeToApiError } from \"./errors\";\nimport { defineRoutes } from \"@fragno-dev/core\";\nimport { stripeFragmentDefinition } from \"../definition\";\n\nexport const subscriptionsRoutesFactory = defineRoutes(stripeFragmentDefinition).create(\n ({ deps, services, config, defineRoute }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/subscriptions\",\n outputSchema: z.object({\n subscriptions: z.array(SubscriptionReponseSchema),\n }),\n handler: async (_, { json, error }) => {\n if (!config.enableAdminRoutes) {\n return error({ message: \"Unauthorized\", code: \"UNAUTHORIZED\" }, 401);\n }\n\n // TODO: Implement pagination\n return json({\n subscriptions: await services.getAllSubscriptions(),\n });\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/subscription/upgrade\",\n inputSchema: SubscriptionUpgradeRequestSchema,\n outputSchema: z.object({\n url: z.string(),\n redirect: z.boolean(),\n sessionId: z.string().optional(),\n }),\n errorCodes: [\n \"MISSING_CUSTOMER_INFO\",\n \"SUBSCRIPTION_NOT_FOUND\",\n \"CUSTOMER_SUBSCRIPTION_MISMATCH\",\n \"UPGRADE_HAS_NO_EFFECT\",\n \"SUBSCRIPTION_UPDATE_NOT_ALLOWED\",\n \"SUBSCRIPTION_UPDATE_PROMO_CODE_NOT_ALLOWED\",\n \"PROMOTION_CODE_CUSTOMER_NOT_FIRST_TIME\",\n \"MULTIPLE_ACTIVE_SUBSCRIPTIONS\",\n \"NO_ACTIVE_SUBSCRIPTIONS\",\n ] as const,\n handler: async (context, { json, error }) => {\n const body = await context.input.valid();\n const entity = await config.resolveEntityFromRequest(context);\n\n let customerId: string | undefined = entity.stripeCustomerId;\n let existingSubscription: SubscriptionResponse | null = null;\n\n // Step 1: Get active subscriptions\n if (entity.stripeCustomerId) {\n const existingSubscriptions = await services.getSubscriptionsByStripeCustomerId(\n entity.stripeCustomerId,\n );\n\n // Cannot upgrade cancelled subscriptions\n let activeSubscriptions = existingSubscriptions.filter((s) => s.status !== \"canceled\");\n\n // A specific subscription has been specified\n if (body.subscriptionId) {\n activeSubscriptions = activeSubscriptions.filter((s) => s.id === body.subscriptionId);\n }\n\n if (activeSubscriptions.length > 1) {\n return error(\n {\n message:\n \"Multiple active subscriptions found for customer, please specify which subscription to upgrade\",\n code: \"MULTIPLE_ACTIVE_SUBSCRIPTIONS\",\n },\n 400,\n );\n }\n if (activeSubscriptions.length === 0) {\n return error(\n {\n message: \"No active subscriptions found for customer\",\n code: \"NO_ACTIVE_SUBSCRIPTIONS\",\n },\n 400,\n );\n }\n existingSubscription = activeSubscriptions[0];\n\n if (\n customerId &&\n existingSubscription.stripeCustomerId &&\n existingSubscription.stripeCustomerId !== customerId\n ) {\n return error(\n {\n message:\n \"Subsciption being updated does not belong to Stripe Customer that was provided\",\n code: \"CUSTOMER_SUBSCRIPTION_MISMATCH\",\n },\n 422,\n );\n }\n\n customerId = existingSubscription.stripeCustomerId;\n }\n\n // Step 2: Get or Create customer if not found\n if (!customerId) {\n const existingLinkedCustomer = await deps.stripe.customers.search({\n query: `metadata['referenceId']:'${entity.referenceId}'`,\n limit: 1,\n });\n\n if (existingLinkedCustomer.data.length === 1) {\n // Use existing customer\n customerId = existingLinkedCustomer.data[0].id;\n } else {\n // Create new Stripe Customer\n\n // Check if sufficient data is provided for this scenario\n if (!entity.customerEmail || !entity.referenceId) {\n return error({\n message:\n \"New Stripe Customer must be created, but customerEmail or referenceID has not been provided\",\n code: \"MISSING_CUSTOMER_INFO\",\n });\n }\n\n const newCustomer = await deps.stripe.customers.create({\n email: entity.customerEmail,\n metadata: {\n referenceId: entity.referenceId,\n ...entity.stripeMetadata,\n },\n });\n customerId = newCustomer.id;\n }\n\n // Communicate back to the user that a customer has been created/linked\n try {\n await config.onStripeCustomerCreated(customerId, entity.referenceId);\n } catch (error) {\n deps.log.error(\"onStripeCustomerCreated failed!\", error);\n }\n }\n\n // Step 3: Resolve promotion code to ID if provided\n let promotionCodeId: string | undefined = undefined;\n if (body.promotionCode) {\n const promotionCodes = await deps.stripe.promotionCodes.list({\n code: body.promotionCode,\n active: true,\n limit: 1,\n });\n if (promotionCodes.data.length > 0) {\n promotionCodeId = promotionCodes.data[0].id;\n }\n }\n\n // Step 4: If existing subscription is active, modify using billing portal\n if (\n existingSubscription?.status === \"active\" ||\n existingSubscription?.status === \"trialing\"\n ) {\n const stripeSubscription = await deps.stripe.subscriptions.retrieve(\n existingSubscription.stripeSubscriptionId,\n );\n\n try {\n // when /upgrade is called on a subscription scheduled to cancel at the end of the billing period,\n // it is still \"active\" but it's not possible to renew it using a billing portal.\n if (existingSubscription.cancelAt != null) {\n deps.log.info(\"un-cancelling subscription\", stripeSubscription.id);\n\n await deps.stripe.subscriptions.update(stripeSubscription.id, {\n cancel_at_period_end: false,\n });\n\n return json({\n url: body.returnUrl || body.successUrl,\n redirect: true,\n });\n }\n // Portal session to confirm subscription changes\n const portalSession = await deps.stripe.billingPortal.sessions.create({\n customer: customerId,\n return_url: body.returnUrl || body.successUrl,\n flow_data: {\n type: \"subscription_update_confirm\",\n after_completion: {\n type: \"redirect\",\n redirect: {\n return_url: body.returnUrl || body.successUrl,\n },\n },\n subscription_update_confirm: {\n subscription: existingSubscription.stripeSubscriptionId,\n items: [\n {\n // We always create subscriptions with a single item\n id: stripeSubscription.items.data[0]?.id as string,\n quantity: body.quantity,\n price: body.priceId,\n },\n ],\n ...(promotionCodeId && {\n discounts: [{ promotion_code: promotionCodeId }],\n }),\n },\n },\n });\n return json({\n url: portalSession.url,\n redirect: true,\n });\n } catch (error: unknown) {\n throw stripeToApiError(error);\n }\n }\n\n // Step 5: Create a Subscription\n const checkoutSession = await deps.stripe.checkout.sessions.create({\n customer: customerId,\n success_url: body.successUrl,\n cancel_url: body.cancelUrl,\n line_items: [\n {\n price: body.priceId,\n quantity: body.quantity,\n },\n ],\n mode: \"subscription\",\n metadata: {\n referenceId: entity.referenceId,\n },\n ...(promotionCodeId && {\n discounts: [{ promotion_code: promotionCodeId }],\n }),\n });\n\n return json({\n url: checkoutSession.url!,\n redirect: true,\n sessionId: checkoutSession.id,\n });\n },\n }),\n defineRoute({\n method: \"POST\",\n path: \"/subscription/cancel\",\n inputSchema: z.object({\n returnUrl: z.url().describe(\"URL to redirect to after cancellation is complete\"),\n subscriptionId: z\n .string()\n .optional()\n .describe(\"Which subscription to cancel, if there are multiple active subscriptions\"),\n }),\n outputSchema: z.object({\n url: z.url().describe(\"URL to redirect to after cancellation\"),\n redirect: z.boolean().describe(\"Whether to redirect to the URL\"),\n }),\n errorCodes: [\n \"SUBSCRIPTION_NOT_FOUND\",\n \"NO_SUBSCRIPTION_TO_CANCEL\",\n \"SUBSCRIPTION_ALREADY_CANCELED\",\n \"NO_STRIPE_CUSTOMER_LINKED\",\n \"MULTIPLE_SUBSCRIPTIONS_FOUND\",\n ] as const,\n handler: async (context, { json, error }) => {\n const body = await context.input.valid();\n const { stripeCustomerId } = await config.resolveEntityFromRequest(context);\n\n if (!stripeCustomerId) {\n return error(\n { message: \"No stripe customer linked to entity\", code: \"NO_STRIPE_CUSTOMER_LINKED\" },\n 400,\n );\n }\n\n let activeSubscriptions = (\n await services.getSubscriptionsByStripeCustomerId(stripeCustomerId)\n ).filter((s) => s.status === \"active\");\n\n // A specific active subscription was requested\n if (body.subscriptionId) {\n activeSubscriptions = activeSubscriptions.filter((s) => s.id === body.subscriptionId);\n }\n\n if (activeSubscriptions.length === 0) {\n return error(\n { message: \"No active subscription to cancel\", code: \"NO_SUBSCRIPTION_TO_CANCEL\" },\n 404,\n );\n }\n\n if (activeSubscriptions.length > 1) {\n return error(\n {\n message: \"Multiple active subscriptions found\",\n code: \"MULTIPLE_SUBSCRIPTIONS_FOUND\",\n },\n 400,\n );\n }\n\n const activeSubscription = activeSubscriptions[0];\n\n try {\n // Get active subscriptions from Stripe for this customer\n const stripeSubscription = await deps.stripe.subscriptions.retrieve(\n activeSubscription.stripeSubscriptionId,\n );\n\n if (!stripeSubscription) {\n return error(\n {\n message: \"Active subscription not found in Stripe\",\n code: \"SUBSCRIPTION_NOT_FOUND\",\n },\n 404,\n );\n }\n\n // Check if subscription is already set to cancel at period end\n if (stripeSubscription.cancel_at_period_end) {\n // Already scheduled for cancellation, just return success\n return json({\n url: \"\", // No redirect needed\n redirect: false,\n });\n }\n\n // Create billing portal session for cancellation\n const portalSession = await deps.stripe.billingPortal.sessions.create({\n customer: activeSubscription.stripeCustomerId!,\n return_url: body.returnUrl,\n flow_data: {\n type: \"subscription_cancel\",\n subscription_cancel: {\n subscription: stripeSubscription.id,\n },\n after_completion: {\n type: \"redirect\",\n redirect: {\n return_url: body.returnUrl,\n },\n },\n },\n });\n\n return json({\n url: portalSession.url,\n redirect: true,\n });\n } catch (err: unknown) {\n throw stripeToApiError(err);\n }\n },\n }),\n ];\n },\n);\n","import { z } from \"zod\";\n\nexport const ProductResponseSchema = z.object({\n id: z.string(),\n object: z.literal(\"product\"),\n active: z.boolean(),\n created: z.number(),\n default_price: z.union([z.string(), z.any()]).nullable().optional(),\n deleted: z.void().optional(),\n description: z.string().nullable(),\n images: z.array(z.string()),\n livemode: z.boolean(),\n marketing_features: z.array(z.any()),\n metadata: z.any(),\n name: z.string(),\n package_dimensions: z.any().nullable(),\n shippable: z.boolean().nullable(),\n statement_descriptor: z.string().nullable().optional(),\n tax_code: z.union([z.string(), z.any()]).nullable(),\n type: z.string(),\n unit_label: z.string().nullable().optional(),\n updated: z.number(),\n url: z.string().nullable(),\n});\n\nexport type ProductResponseSchema = z.infer<typeof ProductResponseSchema>;\n","import { z } from \"zod\";\nimport { ProductResponseSchema } from \"../models/products\";\nimport { defineRoutes } from \"@fragno-dev/core\";\nimport { stripeFragmentDefinition } from \"../definition\";\n\nexport const productsRoutesFactory = defineRoutes(stripeFragmentDefinition).create(\n ({ deps, config, defineRoute }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/products\",\n inputSchema: z.object({\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .default(50)\n .describe(\"Number of products to return (max 100)\"),\n startingAfter: z.string().optional().describe(\"Product ID to start after for pagination\"),\n }),\n outputSchema: z.object({\n products: z.array(ProductResponseSchema),\n hasMore: z.boolean().describe(\"Whether there are more items to fetch\"),\n }),\n handler: async ({ query }, { json, error }) => {\n if (!config.enableAdminRoutes) {\n return error({ message: \"Unauthorized\", code: \"UNAUTHORIZED\" }, 401);\n }\n\n const limit = Number(query.get(\"limit\")) || undefined;\n const startingAfter = query.get(\"startingAfter\") || undefined;\n\n const products = await deps.stripe.products.list({\n limit,\n starting_after: startingAfter,\n });\n\n return json({\n products: products.data,\n hasMore: products.has_more,\n });\n },\n }),\n ];\n },\n);\n","import { z } from \"zod\";\n\nexport const PriceResponseSchema = z.object({\n id: z.string(),\n object: z.literal(\"price\"),\n active: z.boolean(),\n billing_scheme: z.string(),\n created: z.number(),\n currency: z.string(),\n custom_unit_amount: z.any().nullable().optional(),\n deleted: z.void().optional(),\n livemode: z.boolean(),\n lookup_key: z.string().nullable().optional(),\n metadata: z.any(),\n nickname: z.string().nullable().optional(),\n product: z.union([z.string(), z.any()]),\n recurring: z\n .object({\n aggregate_usage: z.string().nullable().optional(),\n interval: z.enum([\"day\", \"week\", \"month\", \"year\"]),\n interval_count: z.number(),\n meter: z.string().nullable().optional(),\n trial_period_days: z.number().nullable().optional(),\n usage_type: z.string(),\n })\n .nullable()\n .optional(),\n tax_behavior: z.string().nullable().optional(),\n tiers_mode: z.string().nullable().optional(),\n transform_quantity: z.any().nullable().optional(),\n type: z.enum([\"one_time\", \"recurring\"]),\n unit_amount: z.number().nullable().optional(),\n unit_amount_decimal: z.string().nullable().optional(),\n});\n\nexport type PriceResponseSchema = z.infer<typeof PriceResponseSchema>;\n","import { z } from \"zod\";\nimport { PriceResponseSchema } from \"../models/prices\";\nimport { defineRoutes } from \"@fragno-dev/core\";\nimport { stripeFragmentDefinition } from \"../definition\";\n\nexport const pricesRoutesFactory = defineRoutes(stripeFragmentDefinition).create(\n ({ deps, config, defineRoute }) => {\n return [\n defineRoute({\n method: \"GET\",\n path: \"/admin/products/:productId/prices\",\n inputSchema: z.object({\n limit: z\n .number()\n .int()\n .positive()\n .max(100)\n .optional()\n .default(50)\n .describe(\"Number of prices to return (max 100)\"),\n startingAfter: z.string().optional().describe(\"Price ID to start after for pagination\"),\n }),\n outputSchema: z.object({\n prices: z.array(PriceResponseSchema),\n hasMore: z.boolean().describe(\"Whether there are more items to fetch\"),\n }),\n handler: async ({ pathParams, query }, { json, error }) => {\n if (!config.enableAdminRoutes) {\n return error({ message: \"Unauthorized\", code: \"UNAUTHORIZED\" }, 401);\n }\n\n const { productId } = pathParams;\n const limit = Number(query.get(\"limit\")) || undefined;\n const startingAfter = query.get(\"startingAfter\") || undefined;\n\n const prices = await deps.stripe.prices.list({\n product: productId,\n limit,\n starting_after: startingAfter,\n });\n\n return json({\n prices: prices.data,\n hasMore: prices.has_more,\n });\n },\n }),\n ];\n },\n);\n","import { createClientBuilder } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicClientConfig } from \"@fragno-dev/core/client\";\nimport type { FragnoPublicConfigWithDatabase } from \"@fragno-dev/db\";\nimport type { StripeFragmentConfig } from \"./types\";\nimport { stripeFragmentDefinition } from \"./definition\";\nimport { webhookRoutesFactory } from \"./routes/webhooks\";\nimport { customersRoutesFactory } from \"./routes/customers\";\nimport { subscriptionsRoutesFactory } from \"./routes/subscriptions\";\nimport { productsRoutesFactory } from \"./routes/products\";\nimport { pricesRoutesFactory } from \"./routes/prices\";\nimport { instantiate } from \"@fragno-dev/core\";\n\nconst routes = [\n webhookRoutesFactory,\n customersRoutesFactory,\n subscriptionsRoutesFactory,\n productsRoutesFactory,\n pricesRoutesFactory,\n] as const;\n\nexport function createStripeFragment(\n config: StripeFragmentConfig,\n fragnoConfig: FragnoPublicConfigWithDatabase,\n) {\n return instantiate(stripeFragmentDefinition)\n .withConfig(config)\n .withRoutes(routes)\n .withOptions(fragnoConfig)\n .build();\n}\n\nexport function createStripeFragmentClients(fragnoConfig: FragnoPublicClientConfig = {}) {\n const builder = createClientBuilder(stripeFragmentDefinition, fragnoConfig, routes);\n\n return {\n // These hooks are for building internal administrative interfaces\n useCustomers: builder.createHook(\"/admin/customers\"),\n useProducts: builder.createHook(\"/admin/products\"),\n usePrices: builder.createHook(\"/admin/products/:productId/prices\"),\n useSubscription: builder.createHook(\"/admin/subscriptions\"),\n // Billing Portal for stripe customer\n useBillingPortal: builder.createMutator(\"POST\", \"/portal\"),\n // These clients are for end-users to create/update/cancel their subscriptions\n upgradeSubscription: builder.createMutator(\"POST\", \"/subscription/upgrade\"),\n cancelSubscription: builder.createMutator(\"POST\", \"/subscription/cancel\"),\n };\n}\n\nexport { stripeFragmentDefinition } from \"./definition\";\nexport type {\n StripeFragmentConfig,\n StripeFragmentDeps,\n StripeFragmentServices,\n Logger,\n} from \"./types\";\nexport type { FragnoRouteConfig } from \"@fragno-dev/core\";\n"],"x_google_ignoreList":[10,11,12,13,14,15,19,20],"mappings":";;;;;;;;AAKA,SAASA,sBAAsBC,SAASC,mBAAmB;CAC1D,MAAMC,WAAS,CAAE;AACjB,MAAK,MAAMC,QAAQF,kBAAmB,YAAWE,SAAS,YAAY;EACrE,MAAMC,gBAAgBD,KAAKH,QAAQ;AACnCE,WAAOG,KAAK,GAAGD,cAAc;CAC7B,MAAMF,UAAOG,KAAKF,KAAK;AACxB,QAAOD;AACR;;;;ACXA,SAASW,cAAcC,MAAM;CAC5B,MAAMC,aAAaD,KAAKC,eAAc,OAAQD,KAAKE,KAAI;AACvD,KAAID,WAAWE,SAAS,IAAI,CAAE,QAAOF,WAAWG,MAAM,GAAG,GAAG;AAC5D,QAAOH;AACR;;;;ACJA,IAAII,iBAAiB,cAAcC,MAAM;CACxC;CACA;CACAG,YAAY,EAAEC,SAASF,MAAM,EAAED,QAAQ;AACtC,QAAMG,QAAQ;AACd,OAAKC,OAAO;AACZ,OAAK,UAAUJ;AACf,OAAK,QAAQC;CACd;CACA,IAAID,SAAS;AACZ,SAAO,KAAK;CACb;CACA,IAAIC,OAAO;AACV,SAAO,KAAK;CACb;CACAI,aAA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;CACAC;CACAC;AACD;AAED,SAAgBG,qBACdC,QACAC,cACA;AACA,QAAA,CAAA;AAKF;AAEA,SAAgBE,4BAA4BF,eAAyC,CAAE,GAAE;CACvF,MAAMG,UAAUjB,oBAAoBI,0BAA0BU,cAAcJ,OAAO;AAEnF,QAAO;EAELQ,cAAcD,QAAQE,WAAW,mBAAmB;EACpDC,aAAaH,QAAQE,WAAW,kBAAkB;EAClDE,WAAWJ,QAAQE,WAAW,oCAAoC;EAClEG,iBAAiBL,QAAQE,WAAW,uBAAuB;EAE3DI,kBAAkBN,QAAQO,cAAc,QAAQ,UAAU;EAE1DC,qBAAqBR,QAAQO,cAAc,QAAQ,wBAAwB;EAC3EE,oBAAoBT,QAAQO,cAAc,QAAQ,uBAAsB;CACzE;AACH"}
@@ -8,7 +8,7 @@ import * as _fragno_dev_db_schema0 from "@fragno-dev/db/schema";
8
8
  import * as _fragno_dev_core9 from "@fragno-dev/core";
9
9
  import * as _fragno_dev_core0 from "@fragno-dev/core";
10
10
  import { FragnoRouteConfig } from "@fragno-dev/core";
11
- import * as _fragno_dev_db9 from "@fragno-dev/db";
11
+ import * as _fragno_dev_db20 from "@fragno-dev/db";
12
12
  import * as _fragno_dev_db0 from "@fragno-dev/db";
13
13
  import { FragnoPublicConfigWithDatabase } from "@fragno-dev/db";
14
14
  import * as zod0 from "zod";
@@ -181,10 +181,10 @@ interface StripeFragmentServices {
181
181
  //# sourceMappingURL=types.d.ts.map
182
182
  //#endregion
183
183
  //#region src/definition.d.ts
184
- declare const stripeFragmentDefinition: _fragno_dev_core9.FragmentDefinition<StripeFragmentConfig, _fragno_dev_db9.FragnoPublicConfigWithDatabase, {
184
+ declare const stripeFragmentDefinition: _fragno_dev_core9.FragmentDefinition<StripeFragmentConfig, _fragno_dev_db20.FragnoPublicConfigWithDatabase, {
185
185
  stripe: Stripe;
186
186
  log: Logger;
187
- } & _fragno_dev_db9.ImplicitDatabaseDependencies<_fragno_dev_db_schema93.Schema<Record<"subscription", _fragno_dev_db_schema93.Table<Record<string, _fragno_dev_db_schema93.AnyColumn> & Record<"id", _fragno_dev_db_schema93.IdColumn<"varchar(30)", string | _fragno_dev_db_schema93.FragnoId | null, _fragno_dev_db_schema93.FragnoId>> & Record<"referenceId", _fragno_dev_db_schema93.Column<"string", string | null, string | null>> & Record<"stripePriceId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"stripeCustomerId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"stripeSubscriptionId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"status", _fragno_dev_db_schema93.Column<"string", string | null, string>> & Record<"periodStart", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"periodEnd", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"trialStart", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"trialEnd", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"cancelAtPeriodEnd", _fragno_dev_db_schema93.Column<"bool", boolean | null, boolean>> & Record<"cancelAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"seats", _fragno_dev_db_schema93.Column<"integer", number | null, number | null>> & Record<"createdAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date>> & Record<"updatedAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date>>, Record<string, _fragno_dev_db_schema93.AnyRelation>, Record<string, _fragno_dev_db_schema93.Index<_fragno_dev_db_schema93.AnyColumn[], readonly string[]>> & Record<"idx_stripe_customer_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string, string>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["stripeCustomerId"]>> & Record<"idx_stripe_subscription_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string, string>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["stripeSubscriptionId"]>> & Record<"idx_reference_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string | null, string | null>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["referenceId"]>>>>>>, {
187
+ } & _fragno_dev_db20.ImplicitDatabaseDependencies<_fragno_dev_db_schema93.Schema<Record<"subscription", _fragno_dev_db_schema93.Table<Record<string, _fragno_dev_db_schema93.AnyColumn> & Record<"id", _fragno_dev_db_schema93.IdColumn<"varchar(30)", string | _fragno_dev_db_schema93.FragnoId | null, _fragno_dev_db_schema93.FragnoId>> & Record<"referenceId", _fragno_dev_db_schema93.Column<"string", string | null, string | null>> & Record<"stripePriceId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"stripeCustomerId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"stripeSubscriptionId", _fragno_dev_db_schema93.Column<"string", string, string>> & Record<"status", _fragno_dev_db_schema93.Column<"string", string | null, string>> & Record<"periodStart", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"periodEnd", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"trialStart", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"trialEnd", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"cancelAtPeriodEnd", _fragno_dev_db_schema93.Column<"bool", boolean | null, boolean>> & Record<"cancelAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date | null>> & Record<"seats", _fragno_dev_db_schema93.Column<"integer", number | null, number | null>> & Record<"createdAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date>> & Record<"updatedAt", _fragno_dev_db_schema93.Column<"timestamp", Date | null, Date>>, Record<string, _fragno_dev_db_schema93.AnyRelation>, Record<string, _fragno_dev_db_schema93.Index<_fragno_dev_db_schema93.AnyColumn[], readonly string[]>> & Record<"idx_stripe_customer_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string, string>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["stripeCustomerId"]>> & Record<"idx_stripe_subscription_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string, string>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["stripeSubscriptionId"]>> & Record<"idx_reference_id", _fragno_dev_db_schema93.Index<readonly [_fragno_dev_db_schema93.Column<"string", string | null, string | null>] & _fragno_dev_db_schema93.AnyColumn[], readonly ["referenceId"]>>>>>>, {
188
188
  getStripeClient(): Stripe;
189
189
  createSubscription(data: Omit<TableToInsertValues<typeof stripeSchema.tables.subscription>, "id" | "createdAt" | "updatedAt">): Promise<string>;
190
190
  updateSubscription(id: string, data: Partial<Omit<TableToInsertValues<typeof stripeSchema.tables.subscription>, "id">>): Promise<void>;
@@ -200,13 +200,15 @@ declare const stripeFragmentDefinition: _fragno_dev_core9.FragmentDefinition<Str
200
200
  syncStripeSubscriptions(referenceId: string, customerId: string): Promise<{
201
201
  success: boolean;
202
202
  }>;
203
- }, {}, {}, {}, _fragno_dev_db_fragment_definition_builder1.DatabaseServiceContext, _fragno_dev_db9.DatabaseRequestContext, _fragno_dev_db_fragment_definition_builder1.DatabaseRequestStorage, {}>;
203
+ }, {}, {}, {}, _fragno_dev_db_fragment_definition_builder1.DatabaseServiceContext<_fragno_dev_db20.HooksMap>, _fragno_dev_db20.DatabaseRequestContext<_fragno_dev_db20.HooksMap>, _fragno_dev_db_fragment_definition_builder1.DatabaseRequestStorage, {
204
+ _fragno_internal: _fragno_dev_db20.InternalFragmentInstance;
205
+ }>;
204
206
  //# sourceMappingURL=definition.d.ts.map
205
207
  //#endregion
206
208
  //#region src/index.d.ts
207
209
  declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig: FragnoPublicConfigWithDatabase): _fragno_dev_core0.FragnoInstantiatedFragment<[_fragno_dev_core0.FragnoRouteConfig<"POST", "/webhook", _standard_schema_spec0.StandardSchemaV1<unknown, unknown> | undefined, zod0.ZodObject<{
208
210
  success: zod0.ZodBoolean;
209
- }, zod_v4_core0.$strip>, "MISSING_SIGNATURE" | "WEBHOOK_SIGNATURE_INVALID" | "WEBHOOK_ERROR", string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/customers", zod0.ZodObject<{
211
+ }, zod_v4_core0.$strip>, "MISSING_SIGNATURE" | "WEBHOOK_SIGNATURE_INVALID" | "WEBHOOK_ERROR", string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/customers", zod0.ZodObject<{
210
212
  limit: zod0.ZodDefault<zod0.ZodOptional<zod0.ZodNumber>>;
211
213
  startingAfter: zod0.ZodOptional<zod0.ZodString>;
212
214
  }, zod_v4_core0.$strip>, zod0.ZodObject<{
@@ -232,12 +234,12 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
232
234
  preferred_locales: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodArray<zod0.ZodString>>>;
233
235
  }, zod_v4_core0.$strip>>;
234
236
  hasMore: zod0.ZodBoolean;
235
- }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/portal", zod0.ZodObject<{
237
+ }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/portal", zod0.ZodObject<{
236
238
  returnUrl: zod0.ZodURL;
237
239
  }, zod_v4_core0.$strip>, zod0.ZodObject<{
238
240
  url: zod0.ZodURL;
239
241
  redirect: zod0.ZodBoolean;
240
- }, zod_v4_core0.$strip>, "NO_STRIPE_CUSTOMER_FOR_ENTITY", string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/subscriptions", _standard_schema_spec0.StandardSchemaV1<unknown, unknown> | undefined, zod0.ZodObject<{
242
+ }, zod_v4_core0.$strip>, "NO_STRIPE_CUSTOMER_FOR_ENTITY", string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/subscriptions", _standard_schema_spec0.StandardSchemaV1<unknown, unknown> | undefined, zod0.ZodObject<{
241
243
  subscriptions: zod0.ZodArray<zod0.ZodObject<{
242
244
  id: zod0.ZodString;
243
245
  stripeSubscriptionId: zod0.ZodString;
@@ -264,7 +266,7 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
264
266
  createdAt: zod0.ZodDate;
265
267
  updatedAt: zod0.ZodDate;
266
268
  }, zod_v4_core0.$strip>>;
267
- }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/subscription/upgrade", zod0.ZodObject<{
269
+ }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/subscription/upgrade", zod0.ZodObject<{
268
270
  priceId: zod0.ZodString;
269
271
  quantity: zod0.ZodNumber;
270
272
  successUrl: zod0.ZodURL;
@@ -276,13 +278,13 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
276
278
  url: zod0.ZodString;
277
279
  redirect: zod0.ZodBoolean;
278
280
  sessionId: zod0.ZodOptional<zod0.ZodString>;
279
- }, zod_v4_core0.$strip>, "MISSING_CUSTOMER_INFO" | "SUBSCRIPTION_NOT_FOUND" | "CUSTOMER_SUBSCRIPTION_MISMATCH" | "UPGRADE_HAS_NO_EFFECT" | "SUBSCRIPTION_UPDATE_NOT_ALLOWED" | "SUBSCRIPTION_UPDATE_PROMO_CODE_NOT_ALLOWED" | "PROMOTION_CODE_CUSTOMER_NOT_FIRST_TIME" | "MULTIPLE_ACTIVE_SUBSCRIPTIONS" | "NO_ACTIVE_SUBSCRIPTIONS", string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/subscription/cancel", zod0.ZodObject<{
281
+ }, zod_v4_core0.$strip>, "MISSING_CUSTOMER_INFO" | "SUBSCRIPTION_NOT_FOUND" | "CUSTOMER_SUBSCRIPTION_MISMATCH" | "UPGRADE_HAS_NO_EFFECT" | "SUBSCRIPTION_UPDATE_NOT_ALLOWED" | "SUBSCRIPTION_UPDATE_PROMO_CODE_NOT_ALLOWED" | "PROMOTION_CODE_CUSTOMER_NOT_FIRST_TIME" | "MULTIPLE_ACTIVE_SUBSCRIPTIONS" | "NO_ACTIVE_SUBSCRIPTIONS", string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"POST", "/subscription/cancel", zod0.ZodObject<{
280
282
  returnUrl: zod0.ZodURL;
281
283
  subscriptionId: zod0.ZodOptional<zod0.ZodString>;
282
284
  }, zod_v4_core0.$strip>, zod0.ZodObject<{
283
285
  url: zod0.ZodURL;
284
286
  redirect: zod0.ZodBoolean;
285
- }, zod_v4_core0.$strip>, "SUBSCRIPTION_NOT_FOUND" | "NO_SUBSCRIPTION_TO_CANCEL" | "SUBSCRIPTION_ALREADY_CANCELED" | "NO_STRIPE_CUSTOMER_LINKED" | "MULTIPLE_SUBSCRIPTIONS_FOUND", string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/products", zod0.ZodObject<{
287
+ }, zod_v4_core0.$strip>, "SUBSCRIPTION_NOT_FOUND" | "NO_SUBSCRIPTION_TO_CANCEL" | "SUBSCRIPTION_ALREADY_CANCELED" | "NO_STRIPE_CUSTOMER_LINKED" | "MULTIPLE_SUBSCRIPTIONS_FOUND", string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/products", zod0.ZodObject<{
286
288
  limit: zod0.ZodDefault<zod0.ZodOptional<zod0.ZodNumber>>;
287
289
  startingAfter: zod0.ZodOptional<zod0.ZodString>;
288
290
  }, zod_v4_core0.$strip>, zod0.ZodObject<{
@@ -309,7 +311,7 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
309
311
  url: zod0.ZodNullable<zod0.ZodString>;
310
312
  }, zod_v4_core0.$strip>>;
311
313
  hasMore: zod0.ZodBoolean;
312
- }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/products/:productId/prices", zod0.ZodObject<{
314
+ }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>, _fragno_dev_core0.FragnoRouteConfig<"GET", "/admin/products/:productId/prices", zod0.ZodObject<{
313
315
  limit: zod0.ZodDefault<zod0.ZodOptional<zod0.ZodNumber>>;
314
316
  startingAfter: zod0.ZodOptional<zod0.ZodString>;
315
317
  }, zod_v4_core0.$strip>, zod0.ZodObject<{
@@ -351,7 +353,7 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
351
353
  unit_amount_decimal: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodString>>;
352
354
  }, zod_v4_core0.$strip>>;
353
355
  hasMore: zod0.ZodBoolean;
354
- }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext>], {
356
+ }, zod_v4_core0.$strip>, string, string, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>>], {
355
357
  stripe: stripe0.Stripe;
356
358
  log: Logger;
357
359
  } & _fragno_dev_db0.ImplicitDatabaseDependencies<_fragno_dev_db_schema0.Schema<Record<"subscription", _fragno_dev_db_schema0.Table<Record<string, _fragno_dev_db_schema0.AnyColumn> & Record<"id", _fragno_dev_db_schema0.IdColumn<"varchar(30)", string | _fragno_dev_db_schema0.FragnoId | null, _fragno_dev_db_schema0.FragnoId>> & Record<"referenceId", _fragno_dev_db_schema0.Column<"string", string | null, string | null>> & Record<"stripePriceId", _fragno_dev_db_schema0.Column<"string", string, string>> & Record<"stripeCustomerId", _fragno_dev_db_schema0.Column<"string", string, string>> & Record<"stripeSubscriptionId", _fragno_dev_db_schema0.Column<"string", string, string>> & Record<"status", _fragno_dev_db_schema0.Column<"string", string | null, string>> & Record<"periodStart", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date | null>> & Record<"periodEnd", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date | null>> & Record<"trialStart", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date | null>> & Record<"trialEnd", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date | null>> & Record<"cancelAtPeriodEnd", _fragno_dev_db_schema0.Column<"bool", boolean | null, boolean>> & Record<"cancelAt", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date | null>> & Record<"seats", _fragno_dev_db_schema0.Column<"integer", number | null, number | null>> & Record<"createdAt", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date>> & Record<"updatedAt", _fragno_dev_db_schema0.Column<"timestamp", Date | null, Date>>, Record<string, _fragno_dev_db_schema0.AnyRelation>, Record<string, _fragno_dev_db_schema0.Index<_fragno_dev_db_schema0.AnyColumn[], readonly string[]>> & Record<"idx_stripe_customer_id", _fragno_dev_db_schema0.Index<readonly [_fragno_dev_db_schema0.Column<"string", string, string>] & _fragno_dev_db_schema0.AnyColumn[], readonly ["stripeCustomerId"]>> & Record<"idx_stripe_subscription_id", _fragno_dev_db_schema0.Index<readonly [_fragno_dev_db_schema0.Column<"string", string, string>] & _fragno_dev_db_schema0.AnyColumn[], readonly ["stripeSubscriptionId"]>> & Record<"idx_reference_id", _fragno_dev_db_schema0.Index<readonly [_fragno_dev_db_schema0.Column<"string", string | null, string | null>] & _fragno_dev_db_schema0.AnyColumn[], readonly ["referenceId"]>>>>>>, _fragno_dev_core0.BoundServices<{
@@ -370,7 +372,9 @@ declare function createStripeFragment(config: StripeFragmentConfig, fragnoConfig
370
372
  syncStripeSubscriptions(referenceId: string, customerId: string): Promise<{
371
373
  success: boolean;
372
374
  }>;
373
- }>, _fragno_dev_db_fragment_definition_builder0.DatabaseServiceContext, _fragno_dev_db0.DatabaseRequestContext, _fragno_dev_db_fragment_definition_builder0.DatabaseRequestStorage, FragnoPublicConfigWithDatabase, {}>;
375
+ }>, _fragno_dev_db_fragment_definition_builder0.DatabaseServiceContext<_fragno_dev_db0.HooksMap>, _fragno_dev_db0.DatabaseRequestContext<_fragno_dev_db0.HooksMap>, _fragno_dev_db_fragment_definition_builder0.DatabaseRequestStorage, FragnoPublicConfigWithDatabase, {
376
+ _fragno_internal: _fragno_dev_db0.InternalFragmentInstance;
377
+ }>;
374
378
  declare function createStripeFragmentClients(fragnoConfig?: FragnoPublicClientConfig): {
375
379
  useCustomers: _fragno_dev_core_client0.FragnoClientHookData<"GET", "/admin/customers", zod0.ZodObject<{
376
380
  customers: zod0.ZodArray<zod0.ZodObject<{