@dudousxd/nestjs-inertia-client 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,"sources":["../src/fetcher/errors.ts","../src/fetcher/url-builder.ts","../src/fetcher/fetcher.ts","../src/contract/contract.ts","../src/contract/apply-contract.decorator.ts","../src/contract/contract-validation.pipe.ts","../src/contract/metadata.ts","../src/contract/as.decorator.ts","../src/invalidate.ts","../src/index.ts"],"sourcesContent":["export class ApiHttpError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown,\n ) {\n super(`HTTP ${status} ${statusText}`);\n this.name = 'ApiHttpError';\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n get isForbidden(): boolean {\n return this.status === 403;\n }\n get isNotFound(): boolean {\n return this.status === 404;\n }\n get isClient(): boolean {\n return this.status >= 400 && this.status < 500;\n }\n get isServer(): boolean {\n return this.status >= 500;\n }\n\n /**\n * Returns a JSON-serializable representation of the error.\n * The `body` field is **redacted by default** to prevent accidental logging of\n * sensitive response bodies (e.g. API error payloads that may contain PII).\n *\n * Pass `verbose = true` to include the full body in the output.\n *\n * @example\n * ```ts\n * // Safe: body is redacted\n * JSON.stringify(err); // { ..., body: '[redacted]' }\n *\n * // Verbose: includes full body (use only in trusted contexts)\n * JSON.stringify(err.toJSON(true)); // { ..., body: { message: '...' } }\n * ```\n */\n toJSON(verbose = false): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n statusText: this.statusText,\n body: verbose ? this.body : '[redacted — pass verbose=true to include]',\n };\n }\n\n static async fromResponse(res: Response): Promise<ApiHttpError> {\n const ct = res.headers.get('content-type') ?? '';\n const body = ct.includes('application/json')\n ? await res.json().catch(() => null)\n : await res.text().catch(() => '');\n return new ApiHttpError(res.status, res.statusText, body);\n }\n}\n","export interface BuildUrlOptions {\n params?: Record<string, unknown>;\n query?: Record<string, unknown>;\n}\n\n/**\n * Build a URL from a path template, path params, query params, and an optional base URL.\n *\n * Examples:\n * buildUrl('/users/:id', { params: { id: 42 } }) → '/users/42'\n * buildUrl('/users', { query: { active: true } }) → '/users?active=true'\n * buildUrl('/users', {}, 'https://api.test') → 'https://api.test/users'\n */\nexport function buildUrl(path: string, opts: BuildUrlOptions = {}, baseUrl?: string): string {\n // Interpolate path params — encodeURIComponent prevents path traversal\n // e.g. { id: '../admin' } → '/users/..%2Fadmin' not '/users/../admin'\n let resolved = path.replace(/:(\\w+)/g, (_match, key: string) => {\n const val = opts.params?.[key];\n if (val === undefined || val === null) {\n throw new Error(`Missing param: ${key}`);\n }\n return encodeURIComponent(String(val));\n });\n\n // Build query string\n const qs = new URLSearchParams();\n if (opts.query) {\n for (const [k, v] of Object.entries(opts.query)) {\n if (v !== undefined) {\n qs.set(k, String(v));\n }\n }\n }\n const qsStr = qs.toString();\n if (qsStr) resolved += `?${qsStr}`;\n\n // Prepend base URL if provided\n if (baseUrl) {\n const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n return base + resolved;\n }\n return resolved;\n}\n","import { ApiHttpError } from './errors.js';\nimport { buildUrl } from './url-builder.js';\n\nexport interface FetcherOptions {\n baseUrl?: string;\n /** Called once per request; allows dynamic auth tokens. */\n headers?: () => Record<string, string>;\n /** Injection seam for tests; default `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Invoked with the error before it is re-thrown. */\n onError?: (err: ApiHttpError) => void;\n}\n\nexport interface Fetcher {\n get<T>(path: string, opts?: RequestOpts): Promise<T>;\n post<T>(path: string, opts?: RequestOpts): Promise<T>;\n put<T>(path: string, opts?: RequestOpts): Promise<T>;\n patch<T>(path: string, opts?: RequestOpts): Promise<T>;\n delete<T>(path: string, opts?: RequestOpts): Promise<T>;\n}\n\ninterface RequestOpts {\n params?: Record<string, unknown>;\n query?: Record<string, unknown>;\n body?: unknown;\n}\n\nfunction isFormData(b: unknown): b is FormData {\n return typeof FormData !== 'undefined' && b instanceof FormData;\n}\n\nexport function createFetcher(opts: FetcherOptions = {}): Fetcher {\n const fetchImpl = opts.fetch ?? globalThis.fetch;\n const baseUrl = opts.baseUrl ?? '';\n\n async function request<T>(method: string, path: string, ro: RequestOpts = {}): Promise<T> {\n if (!fetchImpl) {\n throw new Error('No fetch implementation: pass opts.fetch or set globalThis.fetch');\n }\n const url = buildUrl(path, ro, baseUrl);\n const headers: Record<string, string> = { ...opts.headers?.() };\n let body: string | FormData | undefined = undefined;\n\n if (ro.body !== undefined) {\n if (isFormData(ro.body)) {\n body = ro.body;\n // Do NOT set Content-Type — the runtime sets it with the multipart boundary\n } else {\n body = JSON.stringify(ro.body);\n headers['content-type'] = 'application/json';\n }\n }\n\n if (!headers.accept) {\n headers.accept = 'application/json';\n }\n\n const res = await fetchImpl(url, { method, headers, ...(body !== undefined ? { body } : {}) });\n\n if (!res.ok) {\n const err = await ApiHttpError.fromResponse(res);\n opts.onError?.(err);\n throw err;\n }\n\n if (res.status === 204) return undefined as T;\n\n const ct = res.headers.get('content-type') ?? '';\n if (ct.includes('application/json')) return (await res.json()) as T;\n return (await res.text()) as unknown as T;\n }\n\n return {\n get: <T>(p: string, ro?: RequestOpts) => request<T>('GET', p, ro),\n post: <T>(p: string, ro?: RequestOpts) => request<T>('POST', p, ro),\n put: <T>(p: string, ro?: RequestOpts) => request<T>('PUT', p, ro),\n patch: <T>(p: string, ro?: RequestOpts) => request<T>('PATCH', p, ro),\n delete: <T>(p: string, ro?: RequestOpts) => request<T>('DELETE', p, ro),\n };\n}\n","import type { z } from 'zod';\n\nexport interface ContractDef<Q = unknown, B = unknown, R = unknown, P = unknown, E = unknown> {\n query?: z.ZodType<Q>;\n body?: z.ZodType<B>;\n response: z.ZodType<R>;\n params?: z.ZodType<P>;\n error?: z.ZodType<E>;\n}\n\nexport function defineContract<Q = unknown, B = unknown, R = unknown, P = unknown, E = unknown>(\n def: ContractDef<Q, B, R, P, E>,\n): ContractDef<Q, B, R, P, E> {\n return def;\n}\n","import { SetMetadata, UsePipes, applyDecorators } from '@nestjs/common';\nimport { ContractValidationPipe } from './contract-validation.pipe.js';\nimport type { ContractDef } from './contract.js';\nimport { CONTRACT_METADATA } from './metadata.js';\n\nexport interface ApplyContractOptions {\n /**\n * When `true`, validates incoming `body` and `query` against the Contract's\n * Zod schemas at runtime using a NestJS pipe.\n *\n * On validation failure a `BadRequestException` is thrown with the Zod\n * issues serialized in the response body:\n * `{ message: 'Contract validation failed', issues: ZodIssue[] }`.\n *\n * **Default: `false`** — schemas are read at codegen-time only, and no\n * runtime validation is performed. This matches the behaviour prior to\n * v0.9 and avoids breaking existing apps. Enable explicitly to enforce\n * the contract at runtime.\n */\n validate?: boolean;\n}\n\nexport function ApplyContract<C extends ContractDef>(\n c: C,\n opts: ApplyContractOptions = {},\n): MethodDecorator {\n const decorators: (ClassDecorator | MethodDecorator)[] = [SetMetadata(CONTRACT_METADATA, c)];\n\n if (opts.validate) {\n decorators.push(UsePipes(new ContractValidationPipe(c)));\n }\n\n return applyDecorators(...(decorators as MethodDecorator[]));\n}\n","import {\n type ArgumentMetadata,\n BadRequestException,\n Injectable,\n type PipeTransform,\n} from '@nestjs/common';\nimport type { ContractDef } from './contract.js';\n\n/**\n * NestJS pipe that validates incoming `body` and `query` against the\n * Contract's Zod schemas at runtime. Installed automatically when\n * `@ApplyContract(c, { validate: true })` is used.\n *\n * On validation failure throws a `BadRequestException` whose response body\n * contains `{ message: 'Contract validation failed', issues: ZodIssue[] }`.\n */\n@Injectable()\nexport class ContractValidationPipe<C extends ContractDef> implements PipeTransform {\n constructor(private readonly contract: C) {}\n\n transform(value: unknown, metadata: ArgumentMetadata): unknown {\n let schema:\n | {\n safeParse: (v: unknown) => {\n success: boolean;\n data: unknown;\n error: { issues: unknown[] };\n };\n }\n | undefined;\n\n if (metadata.type === 'body' && this.contract.body) {\n schema = this.contract.body as typeof schema;\n } else if (metadata.type === 'query' && this.contract.query) {\n schema = this.contract.query as typeof schema;\n } else {\n // Unhandled type — pass through unchanged\n return value;\n }\n\n // schema is always defined here because we checked above\n const parsed = schema!.safeParse(value);\n if (!parsed.success) {\n throw new BadRequestException({\n message: 'Contract validation failed',\n issues: parsed.error.issues,\n });\n }\n return parsed.data;\n }\n}\n","import type { ContractDef } from './contract.js';\n\nexport const CONTRACT_METADATA = Symbol.for('nestjs-inertia:contract');\n\ntype AnyContract = ContractDef<unknown, unknown, unknown, unknown, unknown>;\n\nexport function getContract(target: unknown): AnyContract | undefined {\n if (typeof target !== 'function') return undefined;\n return (Reflect.getMetadata(CONTRACT_METADATA, target) ?? undefined) as AnyContract | undefined;\n}\n","import { SetMetadata } from '@nestjs/common';\n\nexport const ROUTE_NAME_METADATA = Symbol.for('nestjs-inertia:route-name');\n\n/**\n * Override the auto-derived route name on a controller class or method.\n *\n * Codegen composes the final name as `${classPortion}.${methodPortion}`:\n * - **Class portion**: class-level `@As(...)` value if present, else the class name\n * with the `Controller` suffix stripped and first letter lowercased.\n * - **Method portion**: method-level `@As(...)` value if present, else the method name.\n *\n * Both can be multi-segment (contain dots). Each segment is validated against\n * `/^[a-z][a-zA-Z0-9]*$/`.\n *\n * @example Class-level override\n * ```ts\n * @Controller('/api/v1/crew')\n * @As('crew')\n * class CrewController {\n * @Get()\n * @ApplyContract(ListCrew)\n * list() { ... } // → 'crew.list'\n * }\n * ```\n *\n * @example Method-level override only\n * ```ts\n * @Controller('/api/v1/crew')\n * class CrewController {\n * @Get()\n * @ApplyContract(ListCrew)\n * @As('directory.fetch') // → 'crew.directory.fetch'\n * list() { ... }\n * }\n * ```\n *\n * @example Both class and method\n * ```ts\n * @Controller('/api/v1/crew')\n * @As('crew.admin')\n * class CrewController {\n * @Get()\n * @ApplyContract(ListCrew)\n * @As('top10') // → 'crew.admin.top10'\n * list() { ... }\n * }\n * ```\n */\nexport const As = (name: string): ClassDecorator & MethodDecorator =>\n SetMetadata(ROUTE_NAME_METADATA, name);\n","import type { QueryClient } from '@tanstack/query-core';\n\n/**\n * Invalidates queries matching `name` (and optionally `queryArgs`).\n *\n * - `invalidate(qc, 'users.list')` → invalidates `['users.list']`\n * - `invalidate(qc, 'users.list', { id: 1 })` → invalidates `['users.list', { id: 1 }]`\n */\nexport function invalidate(qc: QueryClient, name: string, queryArgs?: unknown): Promise<void> {\n const queryKey = queryArgs === undefined ? [name] : [name, queryArgs];\n return qc.invalidateQueries({ queryKey });\n}\n","export const VERSION = '1.0.0';\n\nexport { createFetcher } from './fetcher/fetcher.js';\nexport { ApiHttpError } from './fetcher/errors.js';\nexport { buildUrl } from './fetcher/url-builder.js';\nexport { defineContract } from './contract/contract.js';\nexport { ApplyContract } from './contract/apply-contract.decorator.js';\nexport { As, ROUTE_NAME_METADATA } from './contract/as.decorator.js';\nexport { ContractValidationPipe } from './contract/contract-validation.pipe.js';\nexport { CONTRACT_METADATA, getContract } from './contract/metadata.js';\nexport type { ApplyContractOptions } from './contract/apply-contract.decorator.js';\nexport { invalidate } from './invalidate.js';\nexport type { FetcherOptions, Fetcher } from './fetcher/fetcher.js';\nexport type { ContractDef } from './contract/contract.js';\n// SSR helpers are available via the `./ssr` subpath export (dist/ssr/hydrate.js)\n"],"mappings":";;;;AAAO,IAAMA,eAAN,MAAMA,sBAAqBC,MAAAA;EAAlC,OAAkCA;;;;;;EAChC,YACkBC,QACAC,YACAC,MAChB;AACA,UAAM,QAAQF,MAAAA,IAAUC,UAAAA,EAAY,GAAA,KAJpBD,SAAAA,QAAAA,KACAC,aAAAA,YAAAA,KACAC,OAAAA;AAGhB,SAAKC,OAAO;EACd;EAEA,IAAIC,iBAA0B;AAC5B,WAAO,KAAKJ,WAAW;EACzB;EACA,IAAIK,cAAuB;AACzB,WAAO,KAAKL,WAAW;EACzB;EACA,IAAIM,aAAsB;AACxB,WAAO,KAAKN,WAAW;EACzB;EACA,IAAIO,WAAoB;AACtB,WAAO,KAAKP,UAAU,OAAO,KAAKA,SAAS;EAC7C;EACA,IAAIQ,WAAoB;AACtB,WAAO,KAAKR,UAAU;EAC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K,cACdC,GACAC,OAA6B,CAAC,GAAC;AAE/B,QAAMC,aAAmD;IAACC,YAAYC,mBAAmBJ,CAAAA;;AAEzF,MAAIC,KAAKI,UAAU;AACjBH,eAAWI,KAAKC,SAAS,IAAIC,uBAAuBR,CAAAA,CAAAA,CAAAA;EACtD;AAEA,SAAOS,gBAAAA,GAAoBP,UAAAA;AAC7B;AAXgBH;;;AGtBhB,SAASW,eAAAA,oBAAmB;AAErB,IAAMC,sBAAsBC,uBAAOC,IAAI,2BAAA;AA+CvC,IAAMC,KAAK,wBAACC,SACjBC,aAAYL,qBAAqBI,IAAAA,GADjB;;;ACzCX,SAASE,WAAWC,IAAiBC,MAAcC,WAAmB;AAC3E,QAAMC,WAAWD,cAAcE,SAAY;IAACH;MAAQ;IAACA;IAAMC;;AAC3D,SAAOF,GAAGK,kBAAkB;IAAEF;EAAS,CAAA;AACzC;AAHgBJ;;;ACRT,IAAMO,UAAU;","names":["ApiHttpError","Error","status","statusText","body","name","isUnauthorized","isForbidden","isNotFound","isClient","isServer","toJSON","verbose","message","fromResponse","res","ct","headers","get","includes","json","catch","text","buildUrl","path","opts","baseUrl","resolved","replace","_match","key","val","params","undefined","Error","encodeURIComponent","String","qs","URLSearchParams","query","k","v","Object","entries","set","qsStr","toString","base","endsWith","slice","isFormData","b","FormData","createFetcher","opts","fetchImpl","fetch","globalThis","baseUrl","request","method","path","ro","Error","url","buildUrl","headers","body","undefined","JSON","stringify","accept","res","ok","err","ApiHttpError","fromResponse","onError","status","ct","get","includes","json","text","p","post","put","patch","delete","defineContract","def","SetMetadata","UsePipes","applyDecorators","BadRequestException","Injectable","ContractValidationPipe","contract","transform","value","metadata","schema","type","body","query","parsed","safeParse","success","BadRequestException","message","issues","error","data","CONTRACT_METADATA","Symbol","for","getContract","target","undefined","Reflect","getMetadata","ApplyContract","c","opts","decorators","SetMetadata","CONTRACT_METADATA","validate","push","UsePipes","ContractValidationPipe","applyDecorators","SetMetadata","ROUTE_NAME_METADATA","Symbol","for","As","name","SetMetadata","invalidate","qc","name","queryArgs","queryKey","undefined","invalidateQueries","VERSION"]}
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/react/index.ts
22
+ var react_exports = {};
23
+ __export(react_exports, {
24
+ InertiaRouteProvider: () => InertiaRouteProvider,
25
+ Link: () => Link,
26
+ useInertiaRoutes: () => useInertiaRoutes
27
+ });
28
+ module.exports = __toCommonJS(react_exports);
29
+
30
+ // src/react/link.tsx
31
+ var import_react2 = require("@inertiajs/react");
32
+
33
+ // src/react/provider.tsx
34
+ var import_react = require("react");
35
+ var InertiaRoutesContext = /* @__PURE__ */ (0, import_react.createContext)(null);
36
+ function useInertiaRoutes() {
37
+ const resolver = (0, import_react.useContext)(InertiaRoutesContext);
38
+ if (!resolver) {
39
+ throw new Error("@dudousxd/nestjs-inertia-client: <InertiaRouteProvider> not found in the component tree.\n\nWrap your app with <InertiaRouteProvider routes={route}> in your entry file:\n\n import { InertiaRouteProvider } from '@dudousxd/nestjs-inertia-client/react';\n import { route } from './.nestjs-inertia/routes.js';\n\n <InertiaRouteProvider routes={route}>\n <App {...props} />\n </InertiaRouteProvider>");
40
+ }
41
+ return resolver;
42
+ }
43
+ __name(useInertiaRoutes, "useInertiaRoutes");
44
+ function InertiaRouteProvider({ routes, children }) {
45
+ return /* @__PURE__ */ React.createElement(InertiaRoutesContext, {
46
+ value: routes
47
+ }, children);
48
+ }
49
+ __name(InertiaRouteProvider, "InertiaRouteProvider");
50
+
51
+ // src/react/link.tsx
52
+ function Link(props) {
53
+ const { route, routeParams, query, ...rest } = props;
54
+ const resolveRoute = useInertiaRoutes();
55
+ const href = resolveRoute(route, routeParams, query);
56
+ return /* @__PURE__ */ React.createElement(import_react2.Link, {
57
+ ...rest,
58
+ href
59
+ });
60
+ }
61
+ __name(Link, "Link");
62
+ // Annotate the CommonJS export names for ESM import in node:
63
+ 0 && (module.exports = {
64
+ InertiaRouteProvider,
65
+ Link,
66
+ useInertiaRoutes
67
+ });
68
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/react/index.ts","../../src/react/link.tsx","../../src/react/provider.tsx"],"sourcesContent":["export { Link } from './link.js';\nexport type { LinkProps } from './link.js';\nexport { InertiaRouteProvider, useInertiaRoutes } from './provider.js';\nexport type { InertiaRouteProviderProps } from './provider.js';\n","import type { RegistryRoutes } from '@dudousxd/nestjs-inertia';\nimport { Link as InertiaLink } from '@inertiajs/react';\nimport type { ComponentProps, ReactNode } from 'react';\nimport { useInertiaRoutes } from './provider.js';\n\ntype AnyRoutes = RegistryRoutes;\n\n// Optional/required routeParams based on whether the route has params\nexport type LinkProps<K extends keyof AnyRoutes> = Omit<\n ComponentProps<typeof InertiaLink>,\n 'href'\n> & {\n route: K;\n query?: Record<string, unknown>;\n children?: ReactNode;\n} & (AnyRoutes[K] extends Record<string, never> | undefined // empty object means no params required\n ? { routeParams?: never }\n : { routeParams: AnyRoutes[K] });\n\nexport function Link<K extends keyof AnyRoutes & string>(props: LinkProps<K>) {\n const { route, routeParams, query, ...rest } = props;\n const resolveRoute = useInertiaRoutes();\n const href = resolveRoute(route, routeParams as Record<string, unknown> | undefined, query);\n return <InertiaLink {...rest} href={href} />;\n}\n","import { type ReactNode, createContext, useContext } from 'react';\n\ntype RouteResolver = (\n name: string,\n params?: Record<string, unknown>,\n query?: Record<string, unknown>,\n) => string;\n\nconst InertiaRoutesContext = createContext<RouteResolver | null>(null);\n\nexport function useInertiaRoutes(): RouteResolver {\n const resolver = useContext(InertiaRoutesContext);\n if (!resolver) {\n throw new Error(\n '@dudousxd/nestjs-inertia-client: <InertiaRouteProvider> not found in the component tree.\\n\\n' +\n 'Wrap your app with <InertiaRouteProvider routes={route}> in your entry file:\\n\\n' +\n \" import { InertiaRouteProvider } from '@dudousxd/nestjs-inertia-client/react';\\n\" +\n \" import { route } from './.nestjs-inertia/routes.js';\\n\\n\" +\n ' <InertiaRouteProvider routes={route}>\\n' +\n ' <App {...props} />\\n' +\n ' </InertiaRouteProvider>',\n );\n }\n return resolver;\n}\n\nexport interface InertiaRouteProviderProps {\n routes: RouteResolver;\n children: ReactNode;\n}\n\nexport function InertiaRouteProvider({ routes, children }: InertiaRouteProviderProps) {\n return <InertiaRoutesContext value={routes}>{children}</InertiaRoutesContext>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACCA,IAAAA,gBAAoC;;;ACDpC,mBAA0D;AAQ1D,IAAMC,uBAAuBC,gDAAoC,IAAA;AAE1D,SAASC,mBAAAA;AACd,QAAMC,eAAWC,yBAAWJ,oBAAAA;AAC5B,MAAI,CAACG,UAAU;AACb,UAAM,IAAIE,MACR,mZAME;EAEN;AACA,SAAOF;AACT;AAdgBD;AAqBT,SAASI,qBAAqB,EAAEC,QAAQC,SAAQ,GAA6B;AAClF,SAAO,sBAAA,cAACR,sBAAAA;IAAqBS,OAAOF;KAASC,QAAAA;AAC/C;AAFgBF;;;ADZT,SAASI,KAAyCC,OAAmB;AAC1E,QAAM,EAAEC,OAAOC,aAAaC,OAAO,GAAGC,KAAAA,IAASJ;AAC/C,QAAMK,eAAeC,iBAAAA;AACrB,QAAMC,OAAOF,aAAaJ,OAAOC,aAAoDC,KAAAA;AACrF,SAAO,sBAAA,cAACK,cAAAA,MAAAA;IAAa,GAAGJ;IAAMG;;AAChC;AALgBR;","names":["import_react","InertiaRoutesContext","createContext","useInertiaRoutes","resolver","useContext","Error","InertiaRouteProvider","routes","children","value","Link","props","route","routeParams","query","rest","resolveRoute","useInertiaRoutes","href","InertiaLink"]}
@@ -0,0 +1,26 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { RegistryRoutes } from '@dudousxd/nestjs-inertia';
3
+ import { Link as Link$1 } from '@inertiajs/react';
4
+ import { ComponentProps, ReactNode } from 'react';
5
+
6
+ type AnyRoutes = RegistryRoutes;
7
+ type LinkProps<K extends keyof AnyRoutes> = Omit<ComponentProps<typeof Link$1>, 'href'> & {
8
+ route: K;
9
+ query?: Record<string, unknown>;
10
+ children?: ReactNode;
11
+ } & (AnyRoutes[K] extends Record<string, never> | undefined ? {
12
+ routeParams?: never;
13
+ } : {
14
+ routeParams: AnyRoutes[K];
15
+ });
16
+ declare function Link<K extends keyof AnyRoutes & string>(props: LinkProps<K>): react_jsx_runtime.JSX.Element;
17
+
18
+ type RouteResolver = (name: string, params?: Record<string, unknown>, query?: Record<string, unknown>) => string;
19
+ declare function useInertiaRoutes(): RouteResolver;
20
+ interface InertiaRouteProviderProps {
21
+ routes: RouteResolver;
22
+ children: ReactNode;
23
+ }
24
+ declare function InertiaRouteProvider({ routes, children }: InertiaRouteProviderProps): react_jsx_runtime.JSX.Element;
25
+
26
+ export { InertiaRouteProvider, type InertiaRouteProviderProps, Link, type LinkProps, useInertiaRoutes };
@@ -0,0 +1,26 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { RegistryRoutes } from '@dudousxd/nestjs-inertia';
3
+ import { Link as Link$1 } from '@inertiajs/react';
4
+ import { ComponentProps, ReactNode } from 'react';
5
+
6
+ type AnyRoutes = RegistryRoutes;
7
+ type LinkProps<K extends keyof AnyRoutes> = Omit<ComponentProps<typeof Link$1>, 'href'> & {
8
+ route: K;
9
+ query?: Record<string, unknown>;
10
+ children?: ReactNode;
11
+ } & (AnyRoutes[K] extends Record<string, never> | undefined ? {
12
+ routeParams?: never;
13
+ } : {
14
+ routeParams: AnyRoutes[K];
15
+ });
16
+ declare function Link<K extends keyof AnyRoutes & string>(props: LinkProps<K>): react_jsx_runtime.JSX.Element;
17
+
18
+ type RouteResolver = (name: string, params?: Record<string, unknown>, query?: Record<string, unknown>) => string;
19
+ declare function useInertiaRoutes(): RouteResolver;
20
+ interface InertiaRouteProviderProps {
21
+ routes: RouteResolver;
22
+ children: ReactNode;
23
+ }
24
+ declare function InertiaRouteProvider({ routes, children }: InertiaRouteProviderProps): react_jsx_runtime.JSX.Element;
25
+
26
+ export { InertiaRouteProvider, type InertiaRouteProviderProps, Link, type LinkProps, useInertiaRoutes };
@@ -0,0 +1,41 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/react/link.tsx
5
+ import { Link as InertiaLink } from "@inertiajs/react";
6
+
7
+ // src/react/provider.tsx
8
+ import { createContext, useContext } from "react";
9
+ var InertiaRoutesContext = /* @__PURE__ */ createContext(null);
10
+ function useInertiaRoutes() {
11
+ const resolver = useContext(InertiaRoutesContext);
12
+ if (!resolver) {
13
+ throw new Error("@dudousxd/nestjs-inertia-client: <InertiaRouteProvider> not found in the component tree.\n\nWrap your app with <InertiaRouteProvider routes={route}> in your entry file:\n\n import { InertiaRouteProvider } from '@dudousxd/nestjs-inertia-client/react';\n import { route } from './.nestjs-inertia/routes.js';\n\n <InertiaRouteProvider routes={route}>\n <App {...props} />\n </InertiaRouteProvider>");
14
+ }
15
+ return resolver;
16
+ }
17
+ __name(useInertiaRoutes, "useInertiaRoutes");
18
+ function InertiaRouteProvider({ routes, children }) {
19
+ return /* @__PURE__ */ React.createElement(InertiaRoutesContext, {
20
+ value: routes
21
+ }, children);
22
+ }
23
+ __name(InertiaRouteProvider, "InertiaRouteProvider");
24
+
25
+ // src/react/link.tsx
26
+ function Link(props) {
27
+ const { route, routeParams, query, ...rest } = props;
28
+ const resolveRoute = useInertiaRoutes();
29
+ const href = resolveRoute(route, routeParams, query);
30
+ return /* @__PURE__ */ React.createElement(InertiaLink, {
31
+ ...rest,
32
+ href
33
+ });
34
+ }
35
+ __name(Link, "Link");
36
+ export {
37
+ InertiaRouteProvider,
38
+ Link,
39
+ useInertiaRoutes
40
+ };
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/react/link.tsx","../../src/react/provider.tsx"],"sourcesContent":["import type { RegistryRoutes } from '@dudousxd/nestjs-inertia';\nimport { Link as InertiaLink } from '@inertiajs/react';\nimport type { ComponentProps, ReactNode } from 'react';\nimport { useInertiaRoutes } from './provider.js';\n\ntype AnyRoutes = RegistryRoutes;\n\n// Optional/required routeParams based on whether the route has params\nexport type LinkProps<K extends keyof AnyRoutes> = Omit<\n ComponentProps<typeof InertiaLink>,\n 'href'\n> & {\n route: K;\n query?: Record<string, unknown>;\n children?: ReactNode;\n} & (AnyRoutes[K] extends Record<string, never> | undefined // empty object means no params required\n ? { routeParams?: never }\n : { routeParams: AnyRoutes[K] });\n\nexport function Link<K extends keyof AnyRoutes & string>(props: LinkProps<K>) {\n const { route, routeParams, query, ...rest } = props;\n const resolveRoute = useInertiaRoutes();\n const href = resolveRoute(route, routeParams as Record<string, unknown> | undefined, query);\n return <InertiaLink {...rest} href={href} />;\n}\n","import { type ReactNode, createContext, useContext } from 'react';\n\ntype RouteResolver = (\n name: string,\n params?: Record<string, unknown>,\n query?: Record<string, unknown>,\n) => string;\n\nconst InertiaRoutesContext = createContext<RouteResolver | null>(null);\n\nexport function useInertiaRoutes(): RouteResolver {\n const resolver = useContext(InertiaRoutesContext);\n if (!resolver) {\n throw new Error(\n '@dudousxd/nestjs-inertia-client: <InertiaRouteProvider> not found in the component tree.\\n\\n' +\n 'Wrap your app with <InertiaRouteProvider routes={route}> in your entry file:\\n\\n' +\n \" import { InertiaRouteProvider } from '@dudousxd/nestjs-inertia-client/react';\\n\" +\n \" import { route } from './.nestjs-inertia/routes.js';\\n\\n\" +\n ' <InertiaRouteProvider routes={route}>\\n' +\n ' <App {...props} />\\n' +\n ' </InertiaRouteProvider>',\n );\n }\n return resolver;\n}\n\nexport interface InertiaRouteProviderProps {\n routes: RouteResolver;\n children: ReactNode;\n}\n\nexport function InertiaRouteProvider({ routes, children }: InertiaRouteProviderProps) {\n return <InertiaRoutesContext value={routes}>{children}</InertiaRoutesContext>;\n}\n"],"mappings":";;;;AACA,SAASA,QAAQC,mBAAmB;;;ACDpC,SAAyBC,eAAeC,kBAAkB;AAQ1D,IAAMC,uBAAuBC,8BAAoC,IAAA;AAE1D,SAASC,mBAAAA;AACd,QAAMC,WAAWC,WAAWJ,oBAAAA;AAC5B,MAAI,CAACG,UAAU;AACb,UAAM,IAAIE,MACR,mZAME;EAEN;AACA,SAAOF;AACT;AAdgBD;AAqBT,SAASI,qBAAqB,EAAEC,QAAQC,SAAQ,GAA6B;AAClF,SAAO,sBAAA,cAACR,sBAAAA;IAAqBS,OAAOF;KAASC,QAAAA;AAC/C;AAFgBF;;;ADZT,SAASI,KAAyCC,OAAmB;AAC1E,QAAM,EAAEC,OAAOC,aAAaC,OAAO,GAAGC,KAAAA,IAASJ;AAC/C,QAAMK,eAAeC,iBAAAA;AACrB,QAAMC,OAAOF,aAAaJ,OAAOC,aAAoDC,KAAAA;AACrF,SAAO,sBAAA,cAACK,aAAAA;IAAa,GAAGJ;IAAMG;;AAChC;AALgBR;","names":["Link","InertiaLink","createContext","useContext","InertiaRoutesContext","createContext","useInertiaRoutes","resolver","useContext","Error","InertiaRouteProvider","routes","children","value","Link","props","route","routeParams","query","rest","resolveRoute","useInertiaRoutes","href","InertiaLink"]}
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/ssr/hydrate.ts
22
+ var hydrate_exports = {};
23
+ __export(hydrate_exports, {
24
+ hydrateClientFromInertia: () => hydrateClientFromInertia,
25
+ seedInitialQueries: () => seedInitialQueries
26
+ });
27
+ module.exports = __toCommonJS(hydrate_exports);
28
+ var import_query_core = require("@tanstack/query-core");
29
+ function hydrateClientFromInertia(page) {
30
+ const qc = new import_query_core.QueryClient();
31
+ const queries = page.props?._initialQueries ?? [];
32
+ for (const [key, data] of queries) {
33
+ qc.setQueryData(key, data);
34
+ }
35
+ return qc;
36
+ }
37
+ __name(hydrateClientFromInertia, "hydrateClientFromInertia");
38
+ function seedInitialQueries(qc) {
39
+ return qc.getQueryCache().getAll().map((q) => [
40
+ q.queryKey,
41
+ q.state.data
42
+ ]);
43
+ }
44
+ __name(seedInitialQueries, "seedInitialQueries");
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ hydrateClientFromInertia,
48
+ seedInitialQueries
49
+ });
50
+ //# sourceMappingURL=hydrate.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/ssr/hydrate.ts"],"sourcesContent":["import { QueryClient } from '@tanstack/query-core';\n\n/**\n * Creates a QueryClient pre-seeded with data from an Inertia page's\n * `_initialQueries` prop (set by the server during SSR).\n *\n * Expected shape:\n * page.props._initialQueries = Array<[queryKey: unknown[], data: unknown]>\n */\nexport function hydrateClientFromInertia(page: {\n props?: { _initialQueries?: Array<[unknown[], unknown]> };\n}): QueryClient {\n const qc = new QueryClient();\n const queries = page.props?._initialQueries ?? [];\n for (const [key, data] of queries) {\n qc.setQueryData(key as readonly unknown[], data);\n }\n return qc;\n}\n\n/**\n * Serialises the entire QueryClient cache into a plain array that can be\n * passed as the `_initialQueries` Inertia prop on the server side.\n */\nexport function seedInitialQueries(qc: QueryClient): Array<[unknown[], unknown]> {\n return qc\n .getQueryCache()\n .getAll()\n .map((q) => [q.queryKey as unknown[], q.state.data]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;wBAA4B;AASrB,SAASA,yBAAyBC,MAExC;AACC,QAAMC,KAAK,IAAIC,8BAAAA;AACf,QAAMC,UAAUH,KAAKI,OAAOC,mBAAmB,CAAA;AAC/C,aAAW,CAACC,KAAKC,IAAAA,KAASJ,SAAS;AACjCF,OAAGO,aAAaF,KAA2BC,IAAAA;EAC7C;AACA,SAAON;AACT;AATgBF;AAeT,SAASU,mBAAmBR,IAAe;AAChD,SAAOA,GACJS,cAAa,EACbC,OAAM,EACNC,IAAI,CAACC,MAAM;IAACA,EAAEC;IAAuBD,EAAEE,MAAMR;GAAK;AACvD;AALgBE;","names":["hydrateClientFromInertia","page","qc","QueryClient","queries","props","_initialQueries","key","data","setQueryData","seedInitialQueries","getQueryCache","getAll","map","q","queryKey","state"]}
@@ -0,0 +1,21 @@
1
+ import { QueryClient } from '@tanstack/query-core';
2
+
3
+ /**
4
+ * Creates a QueryClient pre-seeded with data from an Inertia page's
5
+ * `_initialQueries` prop (set by the server during SSR).
6
+ *
7
+ * Expected shape:
8
+ * page.props._initialQueries = Array<[queryKey: unknown[], data: unknown]>
9
+ */
10
+ declare function hydrateClientFromInertia(page: {
11
+ props?: {
12
+ _initialQueries?: Array<[unknown[], unknown]>;
13
+ };
14
+ }): QueryClient;
15
+ /**
16
+ * Serialises the entire QueryClient cache into a plain array that can be
17
+ * passed as the `_initialQueries` Inertia prop on the server side.
18
+ */
19
+ declare function seedInitialQueries(qc: QueryClient): Array<[unknown[], unknown]>;
20
+
21
+ export { hydrateClientFromInertia, seedInitialQueries };
@@ -0,0 +1,21 @@
1
+ import { QueryClient } from '@tanstack/query-core';
2
+
3
+ /**
4
+ * Creates a QueryClient pre-seeded with data from an Inertia page's
5
+ * `_initialQueries` prop (set by the server during SSR).
6
+ *
7
+ * Expected shape:
8
+ * page.props._initialQueries = Array<[queryKey: unknown[], data: unknown]>
9
+ */
10
+ declare function hydrateClientFromInertia(page: {
11
+ props?: {
12
+ _initialQueries?: Array<[unknown[], unknown]>;
13
+ };
14
+ }): QueryClient;
15
+ /**
16
+ * Serialises the entire QueryClient cache into a plain array that can be
17
+ * passed as the `_initialQueries` Inertia prop on the server side.
18
+ */
19
+ declare function seedInitialQueries(qc: QueryClient): Array<[unknown[], unknown]>;
20
+
21
+ export { hydrateClientFromInertia, seedInitialQueries };
@@ -0,0 +1,26 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/ssr/hydrate.ts
5
+ import { QueryClient } from "@tanstack/query-core";
6
+ function hydrateClientFromInertia(page) {
7
+ const qc = new QueryClient();
8
+ const queries = page.props?._initialQueries ?? [];
9
+ for (const [key, data] of queries) {
10
+ qc.setQueryData(key, data);
11
+ }
12
+ return qc;
13
+ }
14
+ __name(hydrateClientFromInertia, "hydrateClientFromInertia");
15
+ function seedInitialQueries(qc) {
16
+ return qc.getQueryCache().getAll().map((q) => [
17
+ q.queryKey,
18
+ q.state.data
19
+ ]);
20
+ }
21
+ __name(seedInitialQueries, "seedInitialQueries");
22
+ export {
23
+ hydrateClientFromInertia,
24
+ seedInitialQueries
25
+ };
26
+ //# sourceMappingURL=hydrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/ssr/hydrate.ts"],"sourcesContent":["import { QueryClient } from '@tanstack/query-core';\n\n/**\n * Creates a QueryClient pre-seeded with data from an Inertia page's\n * `_initialQueries` prop (set by the server during SSR).\n *\n * Expected shape:\n * page.props._initialQueries = Array<[queryKey: unknown[], data: unknown]>\n */\nexport function hydrateClientFromInertia(page: {\n props?: { _initialQueries?: Array<[unknown[], unknown]> };\n}): QueryClient {\n const qc = new QueryClient();\n const queries = page.props?._initialQueries ?? [];\n for (const [key, data] of queries) {\n qc.setQueryData(key as readonly unknown[], data);\n }\n return qc;\n}\n\n/**\n * Serialises the entire QueryClient cache into a plain array that can be\n * passed as the `_initialQueries` Inertia prop on the server side.\n */\nexport function seedInitialQueries(qc: QueryClient): Array<[unknown[], unknown]> {\n return qc\n .getQueryCache()\n .getAll()\n .map((q) => [q.queryKey as unknown[], q.state.data]);\n}\n"],"mappings":";;;;AAAA,SAASA,mBAAmB;AASrB,SAASC,yBAAyBC,MAExC;AACC,QAAMC,KAAK,IAAIC,YAAAA;AACf,QAAMC,UAAUH,KAAKI,OAAOC,mBAAmB,CAAA;AAC/C,aAAW,CAACC,KAAKC,IAAAA,KAASJ,SAAS;AACjCF,OAAGO,aAAaF,KAA2BC,IAAAA;EAC7C;AACA,SAAON;AACT;AATgBF;AAeT,SAASU,mBAAmBR,IAAe;AAChD,SAAOA,GACJS,cAAa,EACbC,OAAM,EACNC,IAAI,CAACC,MAAM;IAACA,EAAEC;IAAuBD,EAAEE,MAAMR;GAAK;AACvD;AALgBE;","names":["QueryClient","hydrateClientFromInertia","page","qc","QueryClient","queries","props","_initialQueries","key","data","setQueryData","seedInitialQueries","getQueryCache","getAll","map","q","queryKey","state"]}
@@ -0,0 +1,25 @@
1
+ <script lang="ts" generics="K extends keyof import('@dudousxd/nestjs-inertia').InertiaRegistry['routes'] & string">
2
+ import { Link as InertiaLink } from '@inertiajs/svelte';
3
+ import type { RegistryRoutes } from '@dudousxd/nestjs-inertia';
4
+ import { useInertiaRoutes } from './provider.js';
5
+ import type { Snippet } from 'svelte';
6
+
7
+ type Routes = RegistryRoutes;
8
+
9
+ interface Props {
10
+ route: K;
11
+ routeParams?: Routes[K];
12
+ query?: Record<string, unknown>;
13
+ children?: Snippet;
14
+ [key: string]: unknown;
15
+ }
16
+
17
+ const { route, routeParams = undefined, query = undefined, children, ...rest }: Props = $props();
18
+
19
+ const resolveRoute = useInertiaRoutes();
20
+ const href = $derived(resolveRoute(route, routeParams as never, query));
21
+ </script>
22
+
23
+ <InertiaLink {href} {...rest}>
24
+ {@render children?.()}
25
+ </InertiaLink>
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/svelte/index.ts
32
+ var svelte_exports = {};
33
+ __export(svelte_exports, {
34
+ Link: () => Link,
35
+ provideInertiaRoutes: () => provideInertiaRoutes,
36
+ useInertiaRoutes: () => useInertiaRoutes
37
+ });
38
+ module.exports = __toCommonJS(svelte_exports);
39
+
40
+ // src/svelte/Link.svelte
41
+ var import_disclose_version = require("svelte/internal/disclose-version");
42
+ var $ = __toESM(require("svelte/internal/client"));
43
+ var import_svelte2 = require("@inertiajs/svelte");
44
+
45
+ // src/svelte/provider.ts
46
+ var import_svelte = require("svelte");
47
+ var KEY = "inertia-routes";
48
+ function provideInertiaRoutes(resolver) {
49
+ (0, import_svelte.setContext)(KEY, resolver);
50
+ }
51
+ __name(provideInertiaRoutes, "provideInertiaRoutes");
52
+ function useInertiaRoutes() {
53
+ const resolver = (0, import_svelte.getContext)(KEY);
54
+ if (!resolver) {
55
+ throw new Error("@dudousxd/nestjs-inertia-client: provideInertiaRoutes() not called.\n\nCall provideInertiaRoutes(route) in your root layout or app setup:\n\n import { provideInertiaRoutes } from '@dudousxd/nestjs-inertia-client/svelte';\n import { route } from './.nestjs-inertia/routes.js';\n\n provideInertiaRoutes(route);");
56
+ }
57
+ return resolver;
58
+ }
59
+ __name(useInertiaRoutes, "useInertiaRoutes");
60
+
61
+ // src/svelte/Link.svelte
62
+ function Link($$anchor, $$props) {
63
+ $.push($$props, true);
64
+ const routeParams = $.prop($$props, "routeParams", 19, () => void 0), query = $.prop($$props, "query", 19, () => void 0), rest = $.rest_props($$props, [
65
+ "$$slots",
66
+ "$$events",
67
+ "$$legacy",
68
+ "route",
69
+ "routeParams",
70
+ "query",
71
+ "children"
72
+ ]);
73
+ const resolveRoute = useInertiaRoutes();
74
+ const href = $.derived(() => resolveRoute($$props.route, routeParams(), query()));
75
+ (0, import_svelte2.Link)($$anchor, $.spread_props(
76
+ {
77
+ get href() {
78
+ return $.get(href);
79
+ }
80
+ },
81
+ () => rest,
82
+ {
83
+ children: /* @__PURE__ */ __name(($$anchor2, $$slotProps) => {
84
+ var fragment_1 = $.comment();
85
+ var node = $.first_child(fragment_1);
86
+ $.snippet(node, () => $$props.children ?? $.noop);
87
+ $.append($$anchor2, fragment_1);
88
+ }, "children"),
89
+ $$slots: { default: true }
90
+ }
91
+ ));
92
+ $.pop();
93
+ }
94
+ __name(Link, "Link");
95
+ // Annotate the CommonJS export names for ESM import in node:
96
+ 0 && (module.exports = {
97
+ Link,
98
+ provideInertiaRoutes,
99
+ useInertiaRoutes
100
+ });
101
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/svelte/index.ts","../../src/svelte/Link.svelte","../../src/svelte/provider.ts"],"sourcesContent":["export { default as Link } from './Link.svelte';\nexport { provideInertiaRoutes, useInertiaRoutes } from './provider.js';\n","import 'svelte/internal/disclose-version';\nimport * as $ from 'svelte/internal/client';\nimport { Link as InertiaLink } from \"@inertiajs/svelte\";\nimport { useInertiaRoutes } from \"./provider.js\";\n\nexport default function Link($$anchor, $$props) {\n\t$.push($$props, true);\n\n\tconst routeParams = $.prop($$props, 'routeParams', 19, () => void 0),\n\t\tquery = $.prop($$props, 'query', 19, () => void 0),\n\t\trest = $.rest_props($$props, [\n\t\t\t'$$slots',\n\t\t\t'$$events',\n\t\t\t'$$legacy',\n\t\t\t'route',\n\t\t\t'routeParams',\n\t\t\t'query',\n\t\t\t'children'\n\t\t]);\n\n\tconst resolveRoute = useInertiaRoutes();\n\tconst href = $.derived(() => resolveRoute($$props.route, routeParams(), query()));\n\n\tInertiaLink($$anchor, $.spread_props(\n\t\t{\n\t\t\tget href() {\n\t\t\t\treturn $.get(href);\n\t\t\t}\n\t\t},\n\t\t() => rest,\n\t\t{\n\t\t\tchildren: ($$anchor, $$slotProps) => {\n\t\t\t\tvar fragment_1 = $.comment();\n\t\t\t\tvar node = $.first_child(fragment_1);\n\n\t\t\t\t$.snippet(node, () => $$props.children ?? $.noop);\n\t\t\t\t$.append($$anchor, fragment_1);\n\t\t\t},\n\t\t\t$$slots: { default: true }\n\t\t}\n\t));\n\n\t$.pop();\n}","import { getContext, setContext } from 'svelte';\n\ntype RouteResolver = (\n name: string,\n params?: Record<string, unknown>,\n query?: Record<string, unknown>,\n) => string;\n\nconst KEY = 'inertia-routes';\n\nexport function provideInertiaRoutes(resolver: RouteResolver): void {\n setContext(KEY, resolver);\n}\n\nexport function useInertiaRoutes(): RouteResolver {\n const resolver = getContext<RouteResolver | undefined>(KEY);\n if (!resolver) {\n throw new Error(\n '@dudousxd/nestjs-inertia-client: provideInertiaRoutes() not called.\\n\\n' +\n 'Call provideInertiaRoutes(route) in your root layout or app setup:\\n\\n' +\n \" import { provideInertiaRoutes } from '@dudousxd/nestjs-inertia-client/svelte';\\n\" +\n \" import { route } from './.nestjs-inertia/routes.js';\\n\\n\" +\n ' provideInertiaRoutes(route);',\n );\n }\n return resolver;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,8BAAO;AACP,QAAmB;AACnB,IAAAA,iBAAoC;;;ACFpC,oBAAuC;AAQvC,IAAMC,MAAM;AAEL,SAASC,qBAAqBC,UAAuB;AAC1DC,gCAAWH,KAAKE,QAAAA;AAClB;AAFgBD;AAIT,SAASG,mBAAAA;AACd,QAAMF,eAAWG,0BAAsCL,GAAAA;AACvD,MAAI,CAACE,UAAU;AACb,UAAM,IAAII,MACR,yTAIE;EAEN;AACA,SAAOJ;AACT;AAZgBE;;;ADTD,SAAR,KAAsB,UAAU,SAAS;AAC/C,EAAE,OAAK,SAAS,IAAI;AAEpB,QAAM,cAAgB,OAAK,SAAS,eAAe,IAAI,MAAM,MAAM,GAClE,QAAU,OAAK,SAAS,SAAS,IAAI,MAAM,MAAM,GACjD,OAAS,aAAW,SAAS;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,CAAC;AAEF,QAAM,eAAe,iBAAiB;AACtC,QAAM,OAAS,UAAQ,MAAM,aAAa,QAAQ,OAAO,YAAY,GAAG,MAAM,CAAC,CAAC;AAEhF,qBAAAG,MAAY,UAAY;AAAA,IACvB;AAAA,MACC,IAAI,OAAO;AACV,eAAS,MAAI,IAAI;AAAA,MAClB;AAAA,IACD;AAAA,IACA,MAAM;AAAA,IACN;AAAA,MACC,UAAU,wBAACC,WAAU,gBAAgB;AACpC,YAAI,aAAe,UAAQ;AAC3B,YAAI,OAAS,cAAY,UAAU;AAEnC,QAAE,UAAQ,MAAM,MAAM,QAAQ,YAAc,MAAI;AAChD,QAAE,SAAOA,WAAU,UAAU;AAAA,MAC9B,GANU;AAAA,MAOV,SAAS,EAAE,SAAS,KAAK;AAAA,IAC1B;AAAA,EACD,CAAC;AAED,EAAE,MAAI;AACP;AAtCwB;","names":["import_svelte","KEY","provideInertiaRoutes","resolver","setContext","useInertiaRoutes","getContext","Error","InertiaLink","$$anchor"]}
@@ -0,0 +1,21 @@
1
+ import { RegistryRoutes } from '@dudousxd/nestjs-inertia';
2
+ import { SvelteComponent } from 'svelte';
3
+
4
+ type Routes = RegistryRoutes;
5
+
6
+ interface LinkProps<K extends keyof Routes & string> {
7
+ route: K;
8
+ routeParams?: Routes[K] | undefined;
9
+ query?: Record<string, unknown> | undefined;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ declare class Link<
14
+ K extends keyof Routes & string = keyof Routes & string,
15
+ > extends SvelteComponent<LinkProps<K>> {}
16
+
17
+ type RouteResolver = (name: string, params?: Record<string, unknown>, query?: Record<string, unknown>) => string;
18
+ declare function provideInertiaRoutes(resolver: RouteResolver): void;
19
+ declare function useInertiaRoutes(): RouteResolver;
20
+
21
+ export { Link, provideInertiaRoutes, useInertiaRoutes };
@@ -0,0 +1,21 @@
1
+ import { RegistryRoutes } from '@dudousxd/nestjs-inertia';
2
+ import { SvelteComponent } from 'svelte';
3
+
4
+ type Routes = RegistryRoutes;
5
+
6
+ interface LinkProps<K extends keyof Routes & string> {
7
+ route: K;
8
+ routeParams?: Routes[K] | undefined;
9
+ query?: Record<string, unknown> | undefined;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ declare class Link<
14
+ K extends keyof Routes & string = keyof Routes & string,
15
+ > extends SvelteComponent<LinkProps<K>> {}
16
+
17
+ type RouteResolver = (name: string, params?: Record<string, unknown>, query?: Record<string, unknown>) => string;
18
+ declare function provideInertiaRoutes(resolver: RouteResolver): void;
19
+ declare function useInertiaRoutes(): RouteResolver;
20
+
21
+ export { Link, provideInertiaRoutes, useInertiaRoutes };
@@ -0,0 +1,64 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/svelte/Link.svelte
5
+ import "svelte/internal/disclose-version";
6
+ import * as $ from "svelte/internal/client";
7
+ import { Link as InertiaLink } from "@inertiajs/svelte";
8
+
9
+ // src/svelte/provider.ts
10
+ import { getContext, setContext } from "svelte";
11
+ var KEY = "inertia-routes";
12
+ function provideInertiaRoutes(resolver) {
13
+ setContext(KEY, resolver);
14
+ }
15
+ __name(provideInertiaRoutes, "provideInertiaRoutes");
16
+ function useInertiaRoutes() {
17
+ const resolver = getContext(KEY);
18
+ if (!resolver) {
19
+ throw new Error("@dudousxd/nestjs-inertia-client: provideInertiaRoutes() not called.\n\nCall provideInertiaRoutes(route) in your root layout or app setup:\n\n import { provideInertiaRoutes } from '@dudousxd/nestjs-inertia-client/svelte';\n import { route } from './.nestjs-inertia/routes.js';\n\n provideInertiaRoutes(route);");
20
+ }
21
+ return resolver;
22
+ }
23
+ __name(useInertiaRoutes, "useInertiaRoutes");
24
+
25
+ // src/svelte/Link.svelte
26
+ function Link($$anchor, $$props) {
27
+ $.push($$props, true);
28
+ const routeParams = $.prop($$props, "routeParams", 19, () => void 0), query = $.prop($$props, "query", 19, () => void 0), rest = $.rest_props($$props, [
29
+ "$$slots",
30
+ "$$events",
31
+ "$$legacy",
32
+ "route",
33
+ "routeParams",
34
+ "query",
35
+ "children"
36
+ ]);
37
+ const resolveRoute = useInertiaRoutes();
38
+ const href = $.derived(() => resolveRoute($$props.route, routeParams(), query()));
39
+ InertiaLink($$anchor, $.spread_props(
40
+ {
41
+ get href() {
42
+ return $.get(href);
43
+ }
44
+ },
45
+ () => rest,
46
+ {
47
+ children: /* @__PURE__ */ __name(($$anchor2, $$slotProps) => {
48
+ var fragment_1 = $.comment();
49
+ var node = $.first_child(fragment_1);
50
+ $.snippet(node, () => $$props.children ?? $.noop);
51
+ $.append($$anchor2, fragment_1);
52
+ }, "children"),
53
+ $$slots: { default: true }
54
+ }
55
+ ));
56
+ $.pop();
57
+ }
58
+ __name(Link, "Link");
59
+ export {
60
+ Link,
61
+ provideInertiaRoutes,
62
+ useInertiaRoutes
63
+ };
64
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/svelte/Link.svelte","../../src/svelte/provider.ts"],"sourcesContent":["import 'svelte/internal/disclose-version';\nimport * as $ from 'svelte/internal/client';\nimport { Link as InertiaLink } from \"@inertiajs/svelte\";\nimport { useInertiaRoutes } from \"./provider.js\";\n\nexport default function Link($$anchor, $$props) {\n\t$.push($$props, true);\n\n\tconst routeParams = $.prop($$props, 'routeParams', 19, () => void 0),\n\t\tquery = $.prop($$props, 'query', 19, () => void 0),\n\t\trest = $.rest_props($$props, [\n\t\t\t'$$slots',\n\t\t\t'$$events',\n\t\t\t'$$legacy',\n\t\t\t'route',\n\t\t\t'routeParams',\n\t\t\t'query',\n\t\t\t'children'\n\t\t]);\n\n\tconst resolveRoute = useInertiaRoutes();\n\tconst href = $.derived(() => resolveRoute($$props.route, routeParams(), query()));\n\n\tInertiaLink($$anchor, $.spread_props(\n\t\t{\n\t\t\tget href() {\n\t\t\t\treturn $.get(href);\n\t\t\t}\n\t\t},\n\t\t() => rest,\n\t\t{\n\t\t\tchildren: ($$anchor, $$slotProps) => {\n\t\t\t\tvar fragment_1 = $.comment();\n\t\t\t\tvar node = $.first_child(fragment_1);\n\n\t\t\t\t$.snippet(node, () => $$props.children ?? $.noop);\n\t\t\t\t$.append($$anchor, fragment_1);\n\t\t\t},\n\t\t\t$$slots: { default: true }\n\t\t}\n\t));\n\n\t$.pop();\n}","import { getContext, setContext } from 'svelte';\n\ntype RouteResolver = (\n name: string,\n params?: Record<string, unknown>,\n query?: Record<string, unknown>,\n) => string;\n\nconst KEY = 'inertia-routes';\n\nexport function provideInertiaRoutes(resolver: RouteResolver): void {\n setContext(KEY, resolver);\n}\n\nexport function useInertiaRoutes(): RouteResolver {\n const resolver = getContext<RouteResolver | undefined>(KEY);\n if (!resolver) {\n throw new Error(\n '@dudousxd/nestjs-inertia-client: provideInertiaRoutes() not called.\\n\\n' +\n 'Call provideInertiaRoutes(route) in your root layout or app setup:\\n\\n' +\n \" import { provideInertiaRoutes } from '@dudousxd/nestjs-inertia-client/svelte';\\n\" +\n \" import { route } from './.nestjs-inertia/routes.js';\\n\\n\" +\n ' provideInertiaRoutes(route);',\n );\n }\n return resolver;\n}\n"],"mappings":";;;;AAAA,OAAO;AACP,YAAY,OAAO;AACnB,SAAS,QAAQ,mBAAmB;;;ACFpC,SAASA,YAAYC,kBAAkB;AAQvC,IAAMC,MAAM;AAEL,SAASC,qBAAqBC,UAAuB;AAC1DC,aAAWH,KAAKE,QAAAA;AAClB;AAFgBD;AAIT,SAASG,mBAAAA;AACd,QAAMF,WAAWG,WAAsCL,GAAAA;AACvD,MAAI,CAACE,UAAU;AACb,UAAM,IAAII,MACR,yTAIE;EAEN;AACA,SAAOJ;AACT;AAZgBE;;;ADTD,SAAR,KAAsB,UAAU,SAAS;AAC/C,EAAE,OAAK,SAAS,IAAI;AAEpB,QAAM,cAAgB,OAAK,SAAS,eAAe,IAAI,MAAM,MAAM,GAClE,QAAU,OAAK,SAAS,SAAS,IAAI,MAAM,MAAM,GACjD,OAAS,aAAW,SAAS;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACD,CAAC;AAEF,QAAM,eAAe,iBAAiB;AACtC,QAAM,OAAS,UAAQ,MAAM,aAAa,QAAQ,OAAO,YAAY,GAAG,MAAM,CAAC,CAAC;AAEhF,cAAY,UAAY;AAAA,IACvB;AAAA,MACC,IAAI,OAAO;AACV,eAAS,MAAI,IAAI;AAAA,MAClB;AAAA,IACD;AAAA,IACA,MAAM;AAAA,IACN;AAAA,MACC,UAAU,wBAACG,WAAU,gBAAgB;AACpC,YAAI,aAAe,UAAQ;AAC3B,YAAI,OAAS,cAAY,UAAU;AAEnC,QAAE,UAAQ,MAAM,MAAM,QAAQ,YAAc,MAAI;AAChD,QAAE,SAAOA,WAAU,UAAU;AAAA,MAC9B,GANU;AAAA,MAOV,SAAS,EAAE,SAAS,KAAK;AAAA,IAC1B;AAAA,EACD,CAAC;AAED,EAAE,MAAI;AACP;AAtCwB;","names":["getContext","setContext","KEY","provideInertiaRoutes","resolver","setContext","useInertiaRoutes","getContext","Error","$$anchor"]}