@zaptek/application-livel 0.0.0-stage → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +49 -2
  3. package/dist/client/livel-application-client.d.ts +32 -0
  4. package/dist/client/livel-application-client.js +71 -0
  5. package/dist/components/files/file-download-button.component.d.ts +7 -0
  6. package/dist/components/files/file-download-button.component.js +36 -0
  7. package/dist/components/files/file-upload-button.component.d.ts +11 -0
  8. package/dist/components/files/file-upload-button.component.js +41 -0
  9. package/dist/components/files/index.d.ts +4 -0
  10. package/dist/components/files/index.js +2 -0
  11. package/dist/components/index.d.ts +4 -0
  12. package/dist/components/index.js +3 -0
  13. package/dist/components/livel-application.provider.d.ts +20 -0
  14. package/dist/components/livel-application.provider.js +75 -0
  15. package/dist/components/livel-data-connection-status.component.d.ts +4 -0
  16. package/dist/components/livel-data-connection-status.component.js +122 -0
  17. package/dist/dev/dev-errors.contract.d.ts +23 -0
  18. package/dist/dev/dev-errors.contract.js +2 -0
  19. package/dist/hooks/files.hooks.d.ts +51 -0
  20. package/dist/hooks/files.hooks.js +296 -0
  21. package/dist/hooks/index.d.ts +6 -0
  22. package/dist/hooks/index.js +3 -0
  23. package/dist/hooks/rpc.hooks.d.ts +8 -0
  24. package/dist/hooks/rpc.hooks.js +26 -0
  25. package/dist/host/embedded-host.d.ts +8 -0
  26. package/dist/host/embedded-host.js +47 -0
  27. package/dist/host/livel-host.contract.d.ts +17 -0
  28. package/dist/host/livel-host.contract.js +1 -0
  29. package/dist/host/livel-host.d.ts +14 -0
  30. package/dist/host/livel-host.js +1 -0
  31. package/dist/index.d.ts +9 -0
  32. package/dist/index.js +4 -0
  33. package/dist/rpc/rpc-caller.d.ts +9 -0
  34. package/dist/rpc/rpc-caller.js +10 -0
  35. package/dist/vite/index.d.ts +1 -0
  36. package/dist/vite/index.js +1 -0
  37. package/dist/vite/livel-dev-errors.plugin.d.ts +13 -0
  38. package/dist/vite/livel-dev-errors.plugin.js +109 -0
  39. package/docs/README.md +24 -0
  40. package/docs/authentication.md +66 -0
  41. package/docs/data.md +134 -0
  42. package/docs/files.md +130 -0
  43. package/docs/getting-started.md +83 -0
  44. package/docs/rpc.md +49 -0
  45. package/docs/troubleshooting.md +15 -0
  46. package/package.json +66 -3
  47. package/template/.env.example +8 -0
  48. package/template/AGENTS.md +104 -0
  49. package/template/README.md +83 -0
  50. package/template/_gitignore +11 -0
  51. package/template/components.json +25 -0
  52. package/template/livel.json +14 -0
  53. package/template/package.json +48 -0
  54. package/template/pnpm-workspace.yaml +28 -0
  55. package/template/src/components/route-error.tsx +33 -0
  56. package/template/src/components/ui/button.tsx +57 -0
  57. package/template/src/components/ui/toast.tsx +221 -0
  58. package/template/src/lib/utils.ts +1 -0
  59. package/template/src/routeTree.gen.ts +68 -0
  60. package/template/src/router.tsx +19 -0
  61. package/template/src/routes/__root.tsx +53 -0
  62. package/template/src/routes/index.tsx +85 -0
  63. package/template/src/styles.css +148 -0
  64. package/template/tsconfig.json +21 -0
  65. package/template/vite.config.ts +28 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,150 @@
1
+ # @zaptek/application-livel
2
+
3
+ ## 0.15.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Rename the package from `@zaptek/application-zadie` to `@zaptek/application-livel`, as the product is now Livel. Breaking: every name follows. `useZadieApplication` is `useLivelApplication`, `ZadieApplicationProvider` is `LivelApplicationProvider`, `zadieDevErrors()` is `livelDevErrors()`, the environment variables are `VITE_LIVEL_*`, the dev errors route is `/__livel/dev-errors`, and the platform writes `src/livel-objects.gen.ts` and reads `livel.json`. Update the dependency and these names in each application.
8
+
9
+ ## 0.14.1
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [a9786e6]
14
+ - @zaptek/resource@0.2.0
15
+
16
+ ## 0.14.0
17
+
18
+ ### Minor Changes
19
+
20
+ - Call the platform's procedures by their new names. The platform names its procedures in snake_case, under their module: the identity is `["core", "me"]` (was `["me"]`) and the health check `["system", "health_check"]` (was `["health", "check"]`). The files hooks call `files.get_file_download_url`, `prepare_file_upload`, `complete_file_upload`, `delete_file`, `delete_files` and `change_file_visibility`; downloading and deleting a file work again.
21
+
22
+ Breaking: this version needs the platform that serves these names, and an earlier version stops reaching the files and the identity once it is deployed. An application that calls `rpc.call()` with the former paths uses the new ones (see `docs/rpc.md`).
23
+
24
+ ## 0.13.0
25
+
26
+ ### Minor Changes
27
+
28
+ - aed1499: Read and write the workspace's objects with `@zaptek/resource`. Zadie generates `src/zadie-objects.gen.ts`, the Drizzle tables of the workspace's objects; the application declares a resource per object with `defineResource` and uses its hooks (`useList`, `useDetail`, `useAggregate`, `useCreate`…). `ZadieApplicationProvider` gives the resources the application's client and workspace. The generated file also exports each object's labels, by column (`health_contract_labels.choices.status.active`), for the application to show the workspace's own. `ZadieDataConnectionStatus` checks the access to the objects.
29
+
30
+ Breaking: data tables are gone. `useEntries`, `useEntry`, `useCreateEntry`, `useUpdateEntry`, `useDeleteEntry`, `useTable`, `useTables`, the `@zaptek/application-zadie/data` and `/codegen` entrypoints and `src/zadie-tables.gen.ts` are removed. Files hooks paginate as `PaginatedData` of `@zaptek/resource` (`page_size`, `current_page`).
31
+
32
+ Migration of an existing application:
33
+
34
+ 1. Add `@zaptek/resource` and `drizzle-orm` to the application's dependencies, at the versions of the template.
35
+ 2. Call `developApplication`: Zadie writes `src/zadie-objects.gen.ts` with the workspace's objects. Delete `src/zadie-tables.gen.ts`.
36
+ 3. For each table the application read, declare a resource in `src/lib/resources/<object>.resource.ts` with `defineResource` on the generated table (see `docs/data.md`), then replace `useEntries(slug, { where })` by `Resource.useList(filters)`, `useEntry` by `Resource.useDetail`, `useCreateEntry`, `useUpdateEntry` and `useDeleteEntry` by `Resource.useCreate`, `useUpdate` and `useDelete`. A field of `entry.data.x` becomes the column `row.x` (`x_cents` for an amount, `x_id` for a relation).
37
+ 4. Run the build and fix each type error.
38
+
39
+ ### Patch Changes
40
+
41
+ - Updated dependencies [aed1499]
42
+ - @zaptek/resource@0.1.0
43
+
44
+ ## 0.12.0
45
+
46
+ ### Minor Changes
47
+
48
+ - Name data keys in snake_case: `order_by`, `on_delete`, `file_id`, `is_public`, `expires_at`. Exports follow camelCase: `entryColumns`, `tableColumns`, `tableTypesPath`, `zadieDevErrorsPath`.
49
+
50
+ ## 0.11.0
51
+
52
+ ### Minor Changes
53
+
54
+ - Infer table types from the slug. Zadie generates `src/zadie-tables.gen.ts` in each application from the workspace's table schemas; it fills the new `ZadieTables` registry, so `useEntries("factures")` types `data`, checks the fields of `where`, `orderBy` and `include`, and types `entry.included.client` as the related entry. An unknown slug, field or enum value is a compile error. `generateTableTypes` (`@zaptek/application-zadie/codegen`) produces the file.
55
+
56
+ Breaking: the hooks no longer take a type parameter (`useEntries<Task>(...)`); remove it and the hand-written data types. `EntryOf<"slug">` and `TableData<"slug">` name a table's types. `listEntries` and `getEntry` return `ReadEntry`.
57
+
58
+ ## 0.10.0
59
+
60
+ ### Minor Changes
61
+
62
+ - Support relations between data tables. A relation field holds the id of the related entry (a list of ids when it is multiple). `useEntries` and `useEntry` accept `include: ["client"]` to read the related entries into `entry.included.client`, with one query per included field. Filter the entries pointing to an entry with `where: { client: id }`, or `where: { tags: { contains: id } }` for a multiple relation. `eq: null` (or a `null` value) now matches empty or absent fields, like `is_null: true`, and `neq: null` matches filled ones; `is_null` also matches explicit `null` values.
63
+
64
+ Breaking: tables belong to the workspace only. `Table.visibility` is removed, `Table.workspace_id` is always set, and `findTable` and `listTables` no longer return platform tables. `listEntries` takes the table instead of its id, and the new `getEntry` reads one entry with its relations. Date-time fields must be UTC (`toISOString()`).
65
+
66
+ ## 0.9.0
67
+
68
+ ### Minor Changes
69
+
70
+ - 5b7a8b7: Add the `@zaptek/application-zadie/data` entrypoint: `findTable`, `listTables`, `listEntries`, `createEntry`, `patchEntry` and `deleteEntry` take a Supabase client and a workspace id, outside React. The hooks are built on them, and Zadie's agent uses the same functions.
71
+ - 78ccf0a: Rework the data hooks around table slugs: `useEntries(slug, { where, orderBy, page, limit })`, `useEntry`, `useCreateEntry`, `useUpdateEntry` (merges the given fields), `useDeleteEntry`, `useTable` and `useTables` replace the `useDataTable*` hooks. Pagination uses `limit` instead of `page_size`, files included.
72
+
73
+ ### Patch Changes
74
+
75
+ - 32d97a4: Document how to show a total independent of a list filter and how to format date-only fields without a timezone shift. The application template applies the same rules. No API change.
76
+
77
+ ## 0.8.0
78
+
79
+ ### Minor Changes
80
+
81
+ - a7fd34b: The package now ships the application template (`template/`), in the same version: Zadie creates every application from it. Existing applications are unaffected; nothing to migrate.
82
+
83
+ ## 0.7.0
84
+
85
+ ### Minor Changes
86
+
87
+ - Add `zadieDevErrors()`, a Vite plugin (`@zaptek/application-zadie/vite`) that streams the dev server's build errors on `/__zadie/dev-errors`, so Zadie can show and fix them even when the application cannot load.
88
+
89
+ ## 0.6.0
90
+
91
+ ### Minor Changes
92
+
93
+ - Separate where the platform is reached from where the application is embedded: `VITE_ZADIE_PLATFORM_URL` (public API) and `VITE_ZADIE_HOST_ORIGIN` (embedding page) replace `VITE_ZADIE_PLATFORM_ORIGIN`. The member session now comes from a `ZadieHost` (`createEmbeddedHost` inside Zadie's iframe), so a standalone sign-in can plug in later. The ngrok tunnel header applies to RPC calls too.
94
+ - da95e13: Report runtime errors to Zadie: the client forwards uncaught errors and unhandled rejections over the host bridge, and `useReportError()` reports errors the application catches itself.
95
+
96
+ ## 0.5.0
97
+
98
+ ### Minor Changes
99
+
100
+ - Connect to Zadie through a Penpal bridge instead of a hand-written token
101
+ handshake. The client now asks Zadie for the current access token on every
102
+ request, so Zadie keeps refreshing the session and the application never stores
103
+ a token. `useZadieApplication().status` is now `"connecting"`, `"ready"` or
104
+ `"unavailable"`: `"authenticated"` becomes `"ready"`, `"signed_out"` and
105
+ `revision` are removed, and `client.subscribe` no longer exists. The new
106
+ `ZadieHostMethods` type describes the methods Zadie exposes. Applications must
107
+ run inside a Zadie version that provides the bridge.
108
+
109
+ ## 0.4.0
110
+
111
+ ### Minor Changes
112
+
113
+ - 5d9dadc: Expose a reusable oRPC caller and connect it to the current iframe token and workspace. Add `useRpcQuery` for authenticated TanStack Query reads; the connection status uses it to verify `me` alongside the Supabase data read.
114
+ - 0d29bbb: Add authenticated create, update and delete hooks for Zadie data table entries.
115
+ - cd048e9: Add authenticated file hooks for listing, uploading, updating, deleting and
116
+ resolving download URLs. Add reusable upload and download buttons. Uploads use
117
+ Zadie's prepare and complete procedures with direct signed Storage transfer;
118
+ applications retain file IDs rather than temporary URLs. Replace the `/react`
119
+ entrypoint with `/hooks` for hooks and `/components` for components;
120
+ applications must update their imports.
121
+
122
+ ## 0.3.1
123
+
124
+ ### Patch Changes
125
+
126
+ - Allow browser requests to local Supabase instances tunneled through ngrok to reach the API.
127
+
128
+ ## 0.3.0
129
+
130
+ ### Minor Changes
131
+
132
+ - Add a ready-to-render component that confirms when the current Zadie member can read workspace data tables and explains authentication or query failures.
133
+
134
+ ## 0.2.2
135
+
136
+ ### Patch Changes
137
+
138
+ - Publish resolved dependency versions so the SDK installs outside the monorepo.
139
+
140
+ ## 0.2.1
141
+
142
+ ### Patch Changes
143
+
144
+ - 8b27a55: Include versioned SDK documentation and the changelog in the npm package so application developers and coding agents can read the API and release history from their installed version.
145
+
146
+ ## 0.2.0
147
+
148
+ ### Minor Changes
149
+
150
+ - Expose an authenticated React provider and TanStack Query hooks for Zadie data tables and entries.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # Livel Application
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@zaptek/application-livel` gives Livel applications displayed in an iframe an
4
+ authenticated Supabase client, the binding of their resources
5
+ (`@zaptek/resource`) to the workspace's objects, and React hooks for its
6
+ files. Livel keeps the session and the refresh token; the application only receives the current access
7
+ token. Permissions and RLS remain those of the signed-in member.
8
+
9
+ The package is used in the application's browser, not in the Livel
10
+ platform. The template already mounts `LivelApplicationProvider` in its root route.
11
+ The SDK also provides `useRpcQuery` for reads from Livel's API and an
12
+ authenticated RPC caller for direct calls. The low-level transport remains
13
+ available; see [`docs/rpc.md`](docs/rpc.md).
14
+
15
+ The file hooks and components let you browse, upload, open,
16
+ download and delete the files accessible to the signed-in member; see
17
+ [`docs/files.md`](docs/files.md).
18
+
19
+ To visibly check the reading of the workspace's objects and the connection to
20
+ Livel's API:
21
+
22
+ ```tsx
23
+ import { LivelDataConnectionStatus } from "@zaptek/application-livel/components"
24
+
25
+ ;<LivelDataConnectionStatus />
26
+ ```
27
+
28
+ The component shows the state of the data and that of the API separately, with
29
+ the identity recognized after a successful `me` call. It does not require a CSS
30
+ stylesheet from the package.
31
+
32
+ The data is the workspace's objects. The application declares one resource
33
+ per object with `defineResource` from `@zaptek/resource`, on the tables that Livel
34
+ generates in `src/livel-objects.gen.ts`:
35
+
36
+ ```tsx
37
+ function ActiveContracts() {
38
+ const contracts = Contracts.useList({ status: "active" })
39
+ if (contracts.isPending) return <p>Chargement…</p>
40
+ if (contracts.isError) return <p>Impossible de charger les contrats.</p>
41
+ return <p>{contracts.data.pagination.total} contrats en cours</p>
42
+ }
43
+ ```
44
+
45
+ See [`docs/data.md`](docs/data.md).
46
+
47
+ The documentation of the installed version is in
48
+ [`docs/README.md`](docs/README.md). Read getting started and authentication first
49
+ before developing a screen that uses the data. Changes between
50
+ versions are recorded in [`CHANGELOG.md`](CHANGELOG.md).
@@ -0,0 +1,32 @@
1
+ import { type SupabaseClient } from "@supabase/supabase-js";
2
+ import type { LivelHost } from "../host/livel-host.js";
3
+ import { type RpcCaller } from "../rpc/rpc-caller.js";
4
+ export type LivelApplicationClient = {
5
+ supabase: SupabaseClient;
6
+ rpc: RpcCaller;
7
+ workspace_id: string;
8
+ /** Resolves to `true` once the member session is available, `false` if never. */
9
+ ready: Promise<boolean>;
10
+ /** Shows an error in Livel; uncaught errors and rejections are reported already. */
11
+ reportError: (error: unknown) => void;
12
+ dispose: () => void;
13
+ };
14
+ /** Public configuration of an application, given to Vite as `VITE_` variables. */
15
+ export type LivelApplicationConfig = {
16
+ /** Public URL of the Livel platform, which serves its API. */
17
+ platform_url: string;
18
+ /** Origin of the Livel page embedding the application. */
19
+ host_origin: string;
20
+ supabase_url: string;
21
+ supabase_publishable_key: string;
22
+ /** Workspace the application shows when the member has several. */
23
+ workspace_id: string;
24
+ };
25
+ /** Reads the configuration Livel gives the application through Vite. */
26
+ export declare function readLivelApplicationConfig(): LivelApplicationConfig;
27
+ /**
28
+ * Supabase and RPC clients acting as the member: every request asks the host
29
+ * for the current access token, so the application never holds a refresh
30
+ * token. Inside Livel's iframe the host is the embedding page. Browser only.
31
+ */
32
+ export declare function createLivelApplicationClient(config?: LivelApplicationConfig, host?: LivelHost): LivelApplicationClient;
@@ -0,0 +1,71 @@
1
+ import { createClient } from "@supabase/supabase-js";
2
+ import { createEmbeddedHost } from "../host/embedded-host.js";
3
+ import { createRpcCaller } from "../rpc/rpc-caller.js";
4
+ function requireEnvironmentVariable(name, value) {
5
+ if (!value?.trim()) {
6
+ throw new Error(`Missing application environment variable: ${name}`);
7
+ }
8
+ return value;
9
+ }
10
+ function requireHttpUrl(name, value) {
11
+ const url = new URL(value);
12
+ if (!["http:", "https:"].includes(url.protocol)) {
13
+ throw new Error(`${name} must be an HTTP URL`);
14
+ }
15
+ return url;
16
+ }
17
+ /** Reads the configuration Livel gives the application through Vite. */
18
+ export function readLivelApplicationConfig() {
19
+ const env = import.meta.env;
20
+ return {
21
+ platform_url: requireEnvironmentVariable("VITE_LIVEL_PLATFORM_URL", env.VITE_LIVEL_PLATFORM_URL),
22
+ host_origin: requireEnvironmentVariable("VITE_LIVEL_HOST_ORIGIN", env.VITE_LIVEL_HOST_ORIGIN),
23
+ supabase_url: requireEnvironmentVariable("VITE_SUPABASE_URL", env.VITE_SUPABASE_URL),
24
+ supabase_publishable_key: requireEnvironmentVariable("VITE_SUPABASE_PUBLISHABLE_KEY", env.VITE_SUPABASE_PUBLISHABLE_KEY),
25
+ workspace_id: requireEnvironmentVariable("VITE_LIVEL_WORKSPACE_ID", env.VITE_LIVEL_WORKSPACE_ID),
26
+ };
27
+ }
28
+ /**
29
+ * A free ngrok tunnel answers browsers with a warning page unless asked not
30
+ * to; local platforms are exposed this way during development.
31
+ */
32
+ function tunnelHeaders(url) {
33
+ return /\.ngrok(-free)?\.(app|dev)$/u.test(url.hostname)
34
+ ? { "ngrok-skip-browser-warning": "1" }
35
+ : {};
36
+ }
37
+ /**
38
+ * Supabase and RPC clients acting as the member: every request asks the host
39
+ * for the current access token, so the application never holds a refresh
40
+ * token. Inside Livel's iframe the host is the embedding page. Browser only.
41
+ */
42
+ export function createLivelApplicationClient(config = readLivelApplicationConfig(), host = createEmbeddedHost(requireHttpUrl("VITE_LIVEL_HOST_ORIGIN", config.host_origin).origin)) {
43
+ const platformUrl = requireHttpUrl("VITE_LIVEL_PLATFORM_URL", config.platform_url);
44
+ const supabaseUrl = requireHttpUrl("VITE_SUPABASE_URL", config.supabase_url);
45
+ const supabase = createClient(supabaseUrl.href, config.supabase_publishable_key, {
46
+ global: { headers: tunnelHeaders(supabaseUrl) },
47
+ accessToken: host.getAccessToken,
48
+ });
49
+ const rpc = createRpcCaller({
50
+ url: new URL("/api/rpc", platformUrl).href,
51
+ headers: async () => {
52
+ const accessToken = await host.getAccessToken();
53
+ if (!accessToken) {
54
+ throw new Error("Livel application is not signed in");
55
+ }
56
+ return {
57
+ ...tunnelHeaders(platformUrl),
58
+ authorization: `Bearer ${accessToken}`,
59
+ "x-force-workspace-id": config.workspace_id,
60
+ };
61
+ },
62
+ });
63
+ return {
64
+ supabase,
65
+ rpc,
66
+ workspace_id: config.workspace_id,
67
+ ready: host.ready,
68
+ reportError: host.reportError,
69
+ dispose: host.dispose,
70
+ };
71
+ }
@@ -0,0 +1,7 @@
1
+ import { type ButtonHTMLAttributes } from "react";
2
+ export type FileDownloadButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "type"> & {
3
+ fileId: string | null;
4
+ onDownloadError?: (error: Error) => void;
5
+ };
6
+ /** Requests a fresh attachment URL when clicked and lets the browser save it. */
7
+ export declare function FileDownloadButton({ fileId, onDownloadError, children, disabled, onClick, "aria-describedby": ariaDescribedby, ...buttonProps }: FileDownloadButtonProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId } from "react";
3
+ import { useDownloadFile } from "../../hooks/files.hooks.js";
4
+ import { useLivelApplication } from "../livel-application.provider.js";
5
+ /** Requests a fresh attachment URL when clicked and lets the browser save it. */
6
+ export function FileDownloadButton({ fileId, onDownloadError, children, disabled, onClick, "aria-describedby": ariaDescribedby, ...buttonProps }) {
7
+ const download = useDownloadFile();
8
+ const { status } = useLivelApplication();
9
+ const errorId = useId();
10
+ const isDisabled = disabled || status !== "ready" || !fileId || download.isPending;
11
+ async function startDownload() {
12
+ if (!fileId)
13
+ return;
14
+ download.reset();
15
+ try {
16
+ const url = await download.mutateAsync(fileId);
17
+ const anchor = document.createElement("a");
18
+ anchor.href = url;
19
+ anchor.hidden = true;
20
+ document.body.append(anchor);
21
+ anchor.click();
22
+ anchor.remove();
23
+ }
24
+ catch (cause) {
25
+ onDownloadError?.(cause instanceof Error ? cause : new Error("File download failed"));
26
+ }
27
+ }
28
+ return (_jsxs(_Fragment, { children: [_jsx("button", { ...buttonProps, type: 'button', disabled: isDisabled, "aria-busy": download.isPending, "aria-describedby": [ariaDescribedby, download.isError ? errorId : null]
29
+ .filter(Boolean)
30
+ .join(" ") || undefined, onClick: event => {
31
+ onClick?.(event);
32
+ if (!event.defaultPrevented && !isDisabled) {
33
+ void startDownload();
34
+ }
35
+ }, children: download.isPending ? "Téléchargement…" : (children ?? "Télécharger") }), download.isError && (_jsx("span", { id: errorId, role: 'alert', children: "Impossible de t\u00E9l\u00E9charger le fichier." }))] }));
36
+ }
@@ -0,0 +1,11 @@
1
+ import { type ButtonHTMLAttributes } from "react";
2
+ import { type UploadedFile, type UploadFilesInput } from "../../hooks/files.hooks.js";
3
+ export type FileUploadButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "type"> & {
4
+ accept?: string;
5
+ multiple?: boolean;
6
+ uploadOptions?: Omit<UploadFilesInput, "files">;
7
+ onUploaded?: (files: UploadedFile[]) => void;
8
+ onUploadError?: (error: Error) => void;
9
+ };
10
+ /** Lets the user select files and uploads them through Livel's file service. */
11
+ export declare function FileUploadButton({ accept, multiple, uploadOptions, onUploaded, onUploadError, children, disabled, onClick, "aria-describedby": ariaDescribedby, ...buttonProps }: FileUploadButtonProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,41 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useId, useRef } from "react";
3
+ import { getCompletedUploads, useUploadFiles, } from "../../hooks/files.hooks.js";
4
+ import { useLivelApplication } from "../livel-application.provider.js";
5
+ /** Lets the user select files and uploads them through Livel's file service. */
6
+ export function FileUploadButton({ accept, multiple = false, uploadOptions, onUploaded, onUploadError, children, disabled, onClick, "aria-describedby": ariaDescribedby, ...buttonProps }) {
7
+ const inputRef = useRef(null);
8
+ const errorId = useId();
9
+ const upload = useUploadFiles();
10
+ const { status } = useLivelApplication();
11
+ const isDisabled = disabled || status !== "ready" || upload.isPending;
12
+ async function handleFileChange(event) {
13
+ const files = Array.from(event.currentTarget.files ?? []);
14
+ event.currentTarget.value = "";
15
+ if (files.length === 0)
16
+ return;
17
+ upload.reset();
18
+ let uploadedFiles;
19
+ try {
20
+ uploadedFiles = await upload.mutateAsync({ ...uploadOptions, files });
21
+ }
22
+ catch (cause) {
23
+ const completedFiles = getCompletedUploads(cause);
24
+ if (completedFiles.length > 0)
25
+ onUploaded?.(completedFiles);
26
+ onUploadError?.(cause instanceof Error ? cause : new Error("File upload failed"));
27
+ return;
28
+ }
29
+ onUploaded?.(uploadedFiles);
30
+ }
31
+ return (_jsxs(_Fragment, { children: [_jsx("button", { ...buttonProps, type: 'button', disabled: isDisabled, "aria-busy": upload.isPending, "aria-describedby": [ariaDescribedby, upload.isError ? errorId : null]
32
+ .filter(Boolean)
33
+ .join(" ") || undefined, onClick: event => {
34
+ onClick?.(event);
35
+ if (!event.defaultPrevented && !isDisabled) {
36
+ inputRef.current?.click();
37
+ }
38
+ }, children: upload.isPending
39
+ ? "Envoi en cours…"
40
+ : (children ?? (multiple ? "Ajouter des fichiers" : "Ajouter un fichier")) }), _jsx("input", { ref: inputRef, type: 'file', accept: accept, multiple: multiple, disabled: isDisabled, hidden: true, tabIndex: -1, "aria-hidden": 'true', onChange: event => void handleFileChange(event) }), upload.isError && (_jsxs("span", { id: errorId, role: 'alert', children: ["Impossible d\u2019envoyer ", multiple ? "les fichiers" : "le fichier", "."] }))] }));
41
+ }
@@ -0,0 +1,4 @@
1
+ export { FileDownloadButton } from "./file-download-button.component.js";
2
+ export type { FileDownloadButtonProps } from "./file-download-button.component.js";
3
+ export { FileUploadButton } from "./file-upload-button.component.js";
4
+ export type { FileUploadButtonProps } from "./file-upload-button.component.js";
@@ -0,0 +1,2 @@
1
+ export { FileDownloadButton } from "./file-download-button.component.js";
2
+ export { FileUploadButton } from "./file-upload-button.component.js";
@@ -0,0 +1,4 @@
1
+ export { LivelApplicationProvider } from "./livel-application.provider.js";
2
+ export { LivelDataConnectionStatus } from "./livel-data-connection-status.component.js";
3
+ export { FileDownloadButton, FileUploadButton } from "./files/index.js";
4
+ export type { FileDownloadButtonProps, FileUploadButtonProps, } from "./files/index.js";
@@ -0,0 +1,3 @@
1
+ export { LivelApplicationProvider } from "./livel-application.provider.js";
2
+ export { LivelDataConnectionStatus } from "./livel-data-connection-status.component.js";
3
+ export { FileDownloadButton, FileUploadButton } from "./files/index.js";
@@ -0,0 +1,20 @@
1
+ import { type ReactNode } from "react";
2
+ import { type LivelApplicationClient } from "../client/livel-application-client.js";
3
+ export type LivelApplicationStatus = "connecting" | "ready" | "unavailable";
4
+ export type LivelApplicationState = {
5
+ client: LivelApplicationClient | null;
6
+ status: LivelApplicationStatus;
7
+ };
8
+ /**
9
+ * Owns the browser client and its connection to Livel, and gives the
10
+ * application's resources (`@zaptek/resource`) that client and workspace.
11
+ */
12
+ export declare function LivelApplicationProvider({ children, }: {
13
+ children: ReactNode;
14
+ }): import("react/jsx-runtime").JSX.Element;
15
+ /**
16
+ * Reports an error the application caught itself, e.g. in a route error
17
+ * component, so the member can ask Livel to fix it.
18
+ */
19
+ export declare function useReportError(): (error: unknown) => void;
20
+ export declare function useLivelApplication(): LivelApplicationState;
@@ -0,0 +1,75 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
3
+ import { ResourceProvider } from "@zaptek/resource";
4
+ import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react";
5
+ import { createLivelApplicationClient, } from "../client/livel-application-client.js";
6
+ const LivelApplicationContext = createContext(null);
7
+ /** No message of its own: the application shows a write's outcome itself. */
8
+ const noFeedback = { onSuccess: () => { }, onError: () => { } };
9
+ const resourceErrors = {
10
+ access_denied: () => new Error("This record cannot be read or changed"),
11
+ workspace_required: () => new Error("Livel is not connected"),
12
+ };
13
+ /** The workspace once connected: resources read nothing before. */
14
+ function useConnectedWorkspaceId() {
15
+ const { client, status } = useLivelApplication();
16
+ return status === "ready" && client ? client.workspace_id : null;
17
+ }
18
+ /**
19
+ * Owns the browser client and its connection to Livel, and gives the
20
+ * application's resources (`@zaptek/resource`) that client and workspace.
21
+ */
22
+ export function LivelApplicationProvider({ children, }) {
23
+ const [queryClient] = useState(() => new QueryClient());
24
+ const [state, setState] = useState({
25
+ client: null,
26
+ status: "connecting",
27
+ });
28
+ useEffect(() => {
29
+ let client;
30
+ try {
31
+ client = createLivelApplicationClient();
32
+ }
33
+ catch {
34
+ setState({ client: null, status: "unavailable" });
35
+ return;
36
+ }
37
+ let disposed = false;
38
+ setState({ client, status: "connecting" });
39
+ void client.ready.then(ready => {
40
+ if (!disposed)
41
+ setState({ client, status: ready ? "ready" : "unavailable" });
42
+ });
43
+ return () => {
44
+ disposed = true;
45
+ client.dispose();
46
+ queryClient.clear();
47
+ };
48
+ }, [queryClient]);
49
+ const resourceConfig = useMemo(() => ({
50
+ client: () => {
51
+ if (!state.client)
52
+ throw resourceErrors.workspace_required();
53
+ return state.client.supabase;
54
+ },
55
+ useWorkspaceId: useConnectedWorkspaceId,
56
+ useMutationFeedback: () => noFeedback,
57
+ errors: resourceErrors,
58
+ }), [state.client]);
59
+ return (_jsx(QueryClientProvider, { client: queryClient, children: _jsx(LivelApplicationContext.Provider, { value: state, children: _jsx(ResourceProvider, { config: resourceConfig, children: children }) }) }));
60
+ }
61
+ /**
62
+ * Reports an error the application caught itself, e.g. in a route error
63
+ * component, so the member can ask Livel to fix it.
64
+ */
65
+ export function useReportError() {
66
+ const { client } = useLivelApplication();
67
+ return useCallback((error) => client?.reportError(error), [client]);
68
+ }
69
+ export function useLivelApplication() {
70
+ const state = useContext(LivelApplicationContext);
71
+ if (!state) {
72
+ throw new Error("Wrap application routes in LivelApplicationProvider");
73
+ }
74
+ return state;
75
+ }
@@ -0,0 +1,4 @@
1
+ /** Confirms both the Supabase data read and the authenticated platform RPC. */
2
+ export declare function LivelDataConnectionStatus({ className, }: {
3
+ className?: string;
4
+ }): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,122 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import { useRpcQuery } from "../hooks/rpc.hooks.js";
4
+ import { useLivelApplication } from "./livel-application.provider.js";
5
+ function isMeIdentity(value) {
6
+ return (typeof value === "object" &&
7
+ value !== null &&
8
+ "id" in value &&
9
+ typeof value.id === "string" &&
10
+ "email" in value &&
11
+ (typeof value.email === "string" || value.email === null));
12
+ }
13
+ function ConnectionLine({ connection }) {
14
+ const color = connection.tone === "error"
15
+ ? "var(--destructive, #b42318)"
16
+ : connection.tone === "success"
17
+ ? "var(--primary, #167353)"
18
+ : "var(--muted-foreground, #667085)";
19
+ return (_jsxs("div", { "data-status": connection.tone, children: [_jsxs("p", { style: {
20
+ alignItems: "center",
21
+ color,
22
+ display: "flex",
23
+ fontSize: "0.875rem",
24
+ fontWeight: 600,
25
+ gap: "0.5rem",
26
+ margin: 0,
27
+ }, children: [_jsx("span", { "aria-hidden": 'true', style: {
28
+ backgroundColor: color,
29
+ borderRadius: "50%",
30
+ flexShrink: 0,
31
+ height: "0.5rem",
32
+ width: "0.5rem",
33
+ } }), connection.label] }), _jsx("p", { style: {
34
+ color: "var(--muted-foreground, #667085)",
35
+ fontSize: "0.875rem",
36
+ lineHeight: 1.5,
37
+ margin: "0.5rem 0 0",
38
+ }, children: connection.description })] }));
39
+ }
40
+ /** Confirms both the Supabase data read and the authenticated platform RPC. */
41
+ export function LivelDataConnectionStatus({ className, }) {
42
+ const { client, status } = useLivelApplication();
43
+ // The workspace's model, which every member reads.
44
+ const tables = useQuery({
45
+ queryKey: ["livel-application", client?.workspace_id ?? null, "objects"],
46
+ enabled: status === "ready" && !!client,
47
+ queryFn: async () => {
48
+ const { count } = await client.supabase
49
+ .from("objects")
50
+ .select("id", { count: "exact", head: true })
51
+ .eq("workspace_id", client.workspace_id)
52
+ .throwOnError();
53
+ return count ?? 0;
54
+ },
55
+ });
56
+ const identity = useRpcQuery({
57
+ path: ["core", "me"],
58
+ retry: false,
59
+ });
60
+ const userIdentity = identity.isSuccess && isMeIdentity(identity.data) ? identity.data : null;
61
+ let dataConnection;
62
+ if (status === "unavailable") {
63
+ dataConnection = {
64
+ label: "Données indisponibles",
65
+ description: "Ouvrez l'application depuis Livel pour accéder aux données.",
66
+ tone: "error",
67
+ };
68
+ }
69
+ else if (status === "ready" && tables.isError) {
70
+ dataConnection = {
71
+ label: "Lecture impossible",
72
+ description: "Impossible de lire les données pour le moment.",
73
+ tone: "error",
74
+ };
75
+ }
76
+ else if (status === "ready" && tables.isSuccess) {
77
+ const count = tables.data;
78
+ dataConnection = {
79
+ label: "Données connectées",
80
+ description: `${count} objet${count > 1 ? "s" : ""} visible${count > 1 ? "s" : ""}.`,
81
+ tone: "success",
82
+ };
83
+ }
84
+ else {
85
+ dataConnection = {
86
+ label: "Connexion aux données…",
87
+ description: "Vérification de l'accès aux données…",
88
+ tone: "pending",
89
+ };
90
+ }
91
+ let rpcConnection;
92
+ if (status === "unavailable") {
93
+ rpcConnection = {
94
+ label: "API indisponible",
95
+ description: "Ouvrez l'application depuis Livel pour vérifier votre identité.",
96
+ tone: "error",
97
+ };
98
+ }
99
+ else if (status === "ready" &&
100
+ (identity.isError || (identity.isSuccess && !userIdentity))) {
101
+ rpcConnection = {
102
+ label: "API inaccessible",
103
+ description: "Impossible de vérifier votre identité auprès de Livel.",
104
+ tone: "error",
105
+ };
106
+ }
107
+ else if (status === "ready" && userIdentity) {
108
+ rpcConnection = {
109
+ label: "API connectée",
110
+ description: `Identifié comme ${userIdentity.email ?? userIdentity.id}.`,
111
+ tone: "success",
112
+ };
113
+ }
114
+ else {
115
+ rpcConnection = {
116
+ label: "Connexion à l'API…",
117
+ description: "Vérification de votre identité auprès de Livel…",
118
+ tone: "pending",
119
+ };
120
+ }
121
+ return (_jsxs("section", { "aria-live": 'polite', className: className, "data-status": dataConnection.tone, "data-rpc-status": rpcConnection.tone, style: { display: "grid", gap: "1.25rem" }, children: [_jsx(ConnectionLine, { connection: dataConnection }), _jsx(ConnectionLine, { connection: rpcConnection })] }));
122
+ }