wcz-layout 9.7.0 → 10.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.
- package/dist/AggregatedCell-BtKC5-m6.mjs +497 -0
- package/dist/AggregatedCell-BtKC5-m6.mjs.map +1 -0
- package/dist/Approval-C-hF4jbT.mjs.map +1 -1
- package/dist/DialogsContext-DLqA8RJ_.mjs.map +1 -1
- package/dist/Email-BzQQkbe9.mjs.map +1 -1
- package/dist/FileMeta-DDqUju1Y.mjs.map +1 -1
- package/dist/LayoutTable-4DLs-NI-.d.mts +752 -0
- package/dist/{QueryClientParam-Cbb0MIKg.d.mts → QueryClientParam-JcH0mJWl.d.mts} +2 -2
- package/dist/RouterListItemButton-ULMlaQh6.mjs.map +1 -1
- package/dist/{User-1gKoYJvW.d.mts → User-D4__w1I1.d.mts} +4 -2
- package/dist/approval-DFExxyAJ.mjs +84 -0
- package/dist/approval-DFExxyAJ.mjs.map +1 -0
- package/dist/auth.d.mts +21 -11
- package/dist/auth.mjs +43 -26
- package/dist/auth.mjs.map +1 -1
- package/dist/components.d.mts +22 -30
- package/dist/components.mjs +786 -139
- package/dist/components.mjs.map +1 -1
- package/dist/createApi-CLYWCzR2.mjs +27 -0
- package/dist/createApi-CLYWCzR2.mjs.map +1 -0
- package/dist/data/client.d.mts +702 -1152
- package/dist/data/client.mjs +4 -3
- package/dist/data/client.mjs.map +1 -1
- package/dist/data/server.d.mts +3 -3
- package/dist/data/server.mjs +4 -2
- package/dist/data/server.mjs.map +1 -1
- package/dist/{file-BWcNzq55.mjs → file-CZwQfvTU.mjs} +5 -24
- package/dist/file-CZwQfvTU.mjs.map +1 -0
- package/dist/{file-DimNsRly.mjs → file-aSQto2rw.mjs} +6 -7
- package/dist/file-aSQto2rw.mjs.map +1 -0
- package/dist/hooks.d.mts +7 -46
- package/dist/hooks.mjs +2578 -239
- package/dist/hooks.mjs.map +1 -1
- package/dist/index.d.mts +28 -9
- package/dist/index.mjs +1248 -500
- package/dist/index.mjs.map +1 -1
- package/dist/middleware.d.mts +20 -19
- package/dist/middleware.mjs +47 -2
- package/dist/middleware.mjs.map +1 -1
- package/dist/models.d.mts +17 -10
- package/dist/models.mjs.map +1 -1
- package/dist/{peoplesoft-CskGsqd6.d.mts → peoplesoft-BY_75WTS.d.mts} +2 -2
- package/dist/{peoplesoft-DTPGpN2h.mjs → peoplesoft-CQnc01Hc.mjs} +24 -81
- package/dist/peoplesoft-CQnc01Hc.mjs.map +1 -0
- package/dist/providers-Dbl95AxR.mjs +74 -0
- package/dist/providers-Dbl95AxR.mjs.map +1 -0
- package/dist/tokens-D8CVIFTb.mjs +143 -0
- package/dist/tokens-D8CVIFTb.mjs.map +1 -0
- package/dist/{utils-5x4uNxsX.d.mts → utils-Bhi0KiBx.d.mts} +18 -6
- package/dist/{utils-DjdexspV.mjs → utils-KaM5VMTJ.mjs} +64 -42
- package/dist/utils-KaM5VMTJ.mjs.map +1 -0
- package/dist/utils.d.mts +2 -2
- package/dist/utils.mjs +2 -2
- package/dist/vite.d.mts +1 -2
- package/dist/vite.mjs +3 -3
- package/dist/vite.mjs.map +1 -1
- package/package.json +23 -23
- package/skills/client-db/SKILL.md +104 -96
- package/skills/db-schema/SKILL.md +46 -33
- package/skills/dialogs/SKILL.md +21 -27
- package/skills/forms/SKILL.md +60 -39
- package/skills/general/SKILL.md +56 -25
- package/skills/general/references/exports.md +106 -0
- package/skills/migrations/SKILL.md +53 -2
- package/skills/migrations/versions/migrate-v9-to-v10.md +581 -0
- package/skills/routing/SKILL.md +50 -60
- package/skills/server-functions/SKILL.md +36 -56
- package/skills/services/SKILL.md +7 -4
- package/skills/services/docs/approval.md +2 -2
- package/skills/services/docs/peoplesoft.md +1 -1
- package/skills/start/SKILL.md +9 -5
- package/skills/start/steps/05-database-setup.md +52 -52
- package/skills/start/steps/06-entra-setup.md +1 -1
- package/skills/start/steps/07-vault-setup.md +5 -12
- package/skills/table/SKILL.md +275 -0
- package/skills/unslop/SKILL.md +80 -0
- package/dist/NotificationContext-CgwUOeW0.mjs +0 -7
- package/dist/NotificationContext-CgwUOeW0.mjs.map +0 -1
- package/dist/authMiddleware-DPly0b_T.mjs +0 -48
- package/dist/authMiddleware-DPly0b_T.mjs.map +0 -1
- package/dist/entra-CJSyeQsx.mjs +0 -109
- package/dist/entra-CJSyeQsx.mjs.map +0 -1
- package/dist/file-BWcNzq55.mjs.map +0 -1
- package/dist/file-DimNsRly.mjs.map +0 -1
- package/dist/msalServer-DLwA7_ta.mjs +0 -30
- package/dist/msalServer-DLwA7_ta.mjs.map +0 -1
- package/dist/peoplesoft-DTPGpN2h.mjs.map +0 -1
- package/dist/useDialogs-BUzVrTSP.mjs +0 -248
- package/dist/useDialogs-BUzVrTSP.mjs.map +0 -1
- package/dist/user-Dzv0N9fj.d.mts +0 -16
- package/dist/utils-DjdexspV.mjs.map +0 -1
- package/skills/data-grid/SKILL.md +0 -142
- package/skills/migrations/versions/migrate-v9-to-v10.tsx +0 -9
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: table
|
|
3
|
+
description: "Use when building or changing a data table, grid, or list page. Covers useLayoutTable, LayoutTable, createLayoutColumnHelper, column definitions and headers, cell formatters, filter variants, sorting, row selection and bulk actions, per-row actions, pagination, footer aggregation."
|
|
4
|
+
metadata:
|
|
5
|
+
type: convention
|
|
6
|
+
library: wcz-layout
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Table patterns
|
|
10
|
+
|
|
11
|
+
> Mechanics (`createTableHook`, column helpers, row models, faceting, the state
|
|
12
|
+
> atoms) belong to TanStack Table v9 itself. List the skills shipped by
|
|
13
|
+
> `@tanstack/table-core` and `@tanstack/react-table` and load whichever cover the task at
|
|
14
|
+
> hand. This skill covers only the wcz-layout conventions on top of it.
|
|
15
|
+
|
|
16
|
+
## Rules
|
|
17
|
+
|
|
18
|
+
- For selection and actions display columns, always set `size: 50`,
|
|
19
|
+
`enableResizing: false`, and `enableCellSelection: false`.
|
|
20
|
+
- Create the column helper once at module scope, outside the component:
|
|
21
|
+
`const columnHelper = createLayoutColumnHelper<Todo>()`. Wrap the array in
|
|
22
|
+
`columnHelper.columns([...])` so each column keeps its own value type.
|
|
23
|
+
- Build the instance with `useLayoutTable({ data, columns })` and pass it to
|
|
24
|
+
`<LayoutTable table={table} />`. Rows are keyed by `row.id`, so every row object
|
|
25
|
+
needs an `id`.
|
|
26
|
+
- Render cells with the bound components off the render prop
|
|
27
|
+
(`cell.ValueCell`, `NumberCell`, `DateCell`, `DateTimeCell`, `BooleanCell`)
|
|
28
|
+
instead of raw JSX. They carry the alignment, the number and date locale, and
|
|
29
|
+
the noWrap behaviour. Write raw JSX only when the cell is a link or
|
|
30
|
+
another interactive element.
|
|
31
|
+
- Set `meta.variant` for non-text filters. Omission means `"text"`.
|
|
32
|
+
- Give `meta.label` to any column whose `header` is not a plain string. A string
|
|
33
|
+
header supplies the label automatically; a function or JSX header leaves the
|
|
34
|
+
header menu and column selector without a label; the filter picker falls back to
|
|
35
|
+
`column.id`. `meta` has four keys: `label`, `align`, `variant`, `options`.
|
|
36
|
+
- Do not enumerate `meta.options` for a free-text column. `select` and
|
|
37
|
+
`multi-select` read their options from the faceted unique values, so the choices
|
|
38
|
+
track the data. Pass explicit string options when labels differ from stored values or
|
|
39
|
+
the UI needs a fixed list. Derive database-enum options from `enumValues`, never a
|
|
40
|
+
second hand-written list.
|
|
41
|
+
- Translate every `header`. The table's own strings come from the app's
|
|
42
|
+
`src/lib/locales/*.json` under `Layout.Table`. See the `general` skill for the
|
|
43
|
+
setup step: the app owns the whole `Layout` namespace, not just `Layout.Table`.
|
|
44
|
+
- Wrap the table in `Fullscreen` when it is the only content on the page.
|
|
45
|
+
- Rows and columns virtualize by default. Pass `pagination` for page-based navigation.
|
|
46
|
+
Virtualization reduces rendered DOM; it does not reduce fetched data or replace
|
|
47
|
+
server-side pagination. Column virtualization
|
|
48
|
+
switches off for grouped header rows and while `loading`, which is a real perf
|
|
49
|
+
cliff on wide tables that use `columnHelper.group`.
|
|
50
|
+
- Props go on `LayoutTable`, not on a slot: `title`, `actions`, `showToolbar`,
|
|
51
|
+
`loading`, `pagination`, `pageSizeOptions`, `onRowClick`, `onRowDoubleClick`,
|
|
52
|
+
`sx`, and the `disableSearch` / `disableColumnFilter` / `disableColumnSelector` /
|
|
53
|
+
`disableColumnMenu` escape hatches.
|
|
54
|
+
- Omit the second `useLayoutTable` selector when passing its result to `LayoutTable`; the
|
|
55
|
+
renderer requires the full selected state.
|
|
56
|
+
- For bulk actions read `table.getSelectedRowIds()` and clear with
|
|
57
|
+
`table.resetRowSelection()`. For per-row actions add a `display` column rendering
|
|
58
|
+
`cell.ActionsCell` with a `RowAction[]`.
|
|
59
|
+
- A footer total needs both halves: `aggregationFn` on the column and
|
|
60
|
+
`footer: ({ header }) => <header.AggregationFooter />`.
|
|
61
|
+
|
|
62
|
+
## Example
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
import { Fullscreen, LayoutTable, RouterIconButton, RouterLink } from "wcz-layout/components";
|
|
66
|
+
import {
|
|
67
|
+
createLayoutColumnHelper,
|
|
68
|
+
useDialogs,
|
|
69
|
+
useLayoutTable,
|
|
70
|
+
useTranslation,
|
|
71
|
+
} from "wcz-layout/hooks";
|
|
72
|
+
|
|
73
|
+
const columnHelper = createLayoutColumnHelper<Todo>();
|
|
74
|
+
|
|
75
|
+
function RouteComponent() {
|
|
76
|
+
const { t } = useTranslation();
|
|
77
|
+
const { confirm, alert } = useDialogs();
|
|
78
|
+
const navigate = useNavigate();
|
|
79
|
+
const todos = useTodoCollection();
|
|
80
|
+
const { data, isLoading } = useLiveQuery(todosQueryOptions);
|
|
81
|
+
|
|
82
|
+
const columns = columnHelper.columns([
|
|
83
|
+
columnHelper.display({
|
|
84
|
+
id: "select",
|
|
85
|
+
header: ({ header }) => <header.SelectAllCell scope="all" />,
|
|
86
|
+
cell: ({ cell }) => <cell.SelectCell />,
|
|
87
|
+
size: 50,
|
|
88
|
+
enableResizing: false,
|
|
89
|
+
}),
|
|
90
|
+
columnHelper.accessor("name", {
|
|
91
|
+
header: t("Todo.Name"),
|
|
92
|
+
cell: ({ cell }) => (
|
|
93
|
+
<RouterLink
|
|
94
|
+
to="/todos/$id"
|
|
95
|
+
params={{ id: cell.row.original.id }}
|
|
96
|
+
underline="hover"
|
|
97
|
+
color="inherit"
|
|
98
|
+
>
|
|
99
|
+
{cell.getValue()}
|
|
100
|
+
</RouterLink>
|
|
101
|
+
),
|
|
102
|
+
size: 260,
|
|
103
|
+
}),
|
|
104
|
+
columnHelper.accessor("assignee", {
|
|
105
|
+
header: t("Todo.Assignee"),
|
|
106
|
+
cell: ({ cell }) => <cell.ValueCell />,
|
|
107
|
+
// No options: the filter builds them from the faceted unique values.
|
|
108
|
+
meta: { variant: "multi-select" },
|
|
109
|
+
size: 180,
|
|
110
|
+
}),
|
|
111
|
+
columnHelper.accessor("priority", {
|
|
112
|
+
header: t("Todo.Priority"),
|
|
113
|
+
cell: ({ cell }) => <cell.NumberCell />,
|
|
114
|
+
footer: ({ header }) => <header.AggregationFooter options={{ maximumFractionDigits: 1 }} />,
|
|
115
|
+
aggregationFn: "mean",
|
|
116
|
+
meta: { variant: "number", align: "right" },
|
|
117
|
+
size: 120,
|
|
118
|
+
}),
|
|
119
|
+
columnHelper.accessor("starred", {
|
|
120
|
+
header: t("Todo.Starred"),
|
|
121
|
+
cell: ({ cell }) => <cell.BooleanCell />,
|
|
122
|
+
meta: { variant: "boolean", align: "center" },
|
|
123
|
+
size: 120,
|
|
124
|
+
}),
|
|
125
|
+
columnHelper.accessor("createdAt", {
|
|
126
|
+
header: t("Todo.CreatedAt"),
|
|
127
|
+
cell: ({ cell }) => <cell.DateTimeCell />,
|
|
128
|
+
meta: { variant: "date" },
|
|
129
|
+
size: 190,
|
|
130
|
+
}),
|
|
131
|
+
]);
|
|
132
|
+
|
|
133
|
+
const table = useLayoutTable({ data, columns });
|
|
134
|
+
const selectedIds = table.getSelectedRowIds();
|
|
135
|
+
|
|
136
|
+
const handleOnDelete = createOptimisticAction<Array<string>>({
|
|
137
|
+
onMutate: (ids) => {
|
|
138
|
+
ids.forEach((id) => {
|
|
139
|
+
todos.delete(id);
|
|
140
|
+
});
|
|
141
|
+
},
|
|
142
|
+
mutationFn: async (ids) => {
|
|
143
|
+
await deleteTodos({ data: ids });
|
|
144
|
+
await todos.utils.refetch({ throwOnError: true });
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
return (
|
|
149
|
+
<Fullscreen>
|
|
150
|
+
<LayoutTable
|
|
151
|
+
table={table}
|
|
152
|
+
loading={isLoading}
|
|
153
|
+
showToolbar
|
|
154
|
+
title={t("Todo.Todos")}
|
|
155
|
+
onRowDoubleClick={(row) => navigate({ to: "/todos/$id", params: { id: row.id } })}
|
|
156
|
+
actions={
|
|
157
|
+
<>
|
|
158
|
+
<Tooltip title={t("Create")}>
|
|
159
|
+
<RouterIconButton to="/todos/create">
|
|
160
|
+
<Add fontSize="small" />
|
|
161
|
+
</RouterIconButton>
|
|
162
|
+
</Tooltip>
|
|
163
|
+
|
|
164
|
+
{selectedIds.length === 1 && (
|
|
165
|
+
<Tooltip title={t("Edit")}>
|
|
166
|
+
<RouterIconButton to="/todos/edit/$id" params={{ id: selectedIds[0] }}>
|
|
167
|
+
<Edit fontSize="small" />
|
|
168
|
+
</RouterIconButton>
|
|
169
|
+
</Tooltip>
|
|
170
|
+
)}
|
|
171
|
+
|
|
172
|
+
{selectedIds.length > 0 && (
|
|
173
|
+
<Tooltip title={t("Delete")}>
|
|
174
|
+
<IconButton
|
|
175
|
+
onClick={async () => {
|
|
176
|
+
const confirmed = await confirm(
|
|
177
|
+
t("DeleteConfirmation", { count: selectedIds.length }),
|
|
178
|
+
);
|
|
179
|
+
if (!confirmed) return;
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
const transaction = handleOnDelete(selectedIds);
|
|
183
|
+
await transaction.isPersisted.promise;
|
|
184
|
+
table.resetRowSelection();
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error instanceof Error) await alert(error.message);
|
|
187
|
+
}
|
|
188
|
+
}}
|
|
189
|
+
>
|
|
190
|
+
<Badge
|
|
191
|
+
badgeContent={selectedIds.length}
|
|
192
|
+
invisible={selectedIds.length <= 1}
|
|
193
|
+
color="error"
|
|
194
|
+
>
|
|
195
|
+
<Delete fontSize="small" />
|
|
196
|
+
</Badge>
|
|
197
|
+
</IconButton>
|
|
198
|
+
</Tooltip>
|
|
199
|
+
)}
|
|
200
|
+
</>
|
|
201
|
+
}
|
|
202
|
+
/>
|
|
203
|
+
</Fullscreen>
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Per-row actions
|
|
209
|
+
|
|
210
|
+
```tsx
|
|
211
|
+
columnHelper.display({
|
|
212
|
+
id: "actions",
|
|
213
|
+
cell: ({ cell }) => (
|
|
214
|
+
<cell.ActionsCell
|
|
215
|
+
actions={[
|
|
216
|
+
{
|
|
217
|
+
label: t("Edit"),
|
|
218
|
+
icon: <Edit fontSize="small" />,
|
|
219
|
+
onClick: (row) => navigate({ to: "/todos/edit/$id", params: { id: row.id } }),
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
label: t("Delete"),
|
|
223
|
+
icon: <Delete fontSize="small" />,
|
|
224
|
+
divider: true,
|
|
225
|
+
onClick: (row) => remove(row.id),
|
|
226
|
+
},
|
|
227
|
+
]}
|
|
228
|
+
/>
|
|
229
|
+
),
|
|
230
|
+
size: 60,
|
|
231
|
+
enableResizing: false,
|
|
232
|
+
}),
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### Other bound components
|
|
236
|
+
|
|
237
|
+
On the header render prop: `SelectAllCell`, `ExpandAllCell`, `AggregationFooter`,
|
|
238
|
+
`HeaderMenu`, `HeaderSortLabel`, `HeaderResizeHandle`. On the cell one:
|
|
239
|
+
`SelectCell`, `ExpandCell`, `GroupCell`, `PinRowCell`, `ActionsCell` and the
|
|
240
|
+
formatter cells. `LayoutTable` already places the menu, the sort label and the
|
|
241
|
+
resize handle, so reach for those three only when building a table by hand.
|
|
242
|
+
|
|
243
|
+
### Custom cells and headers
|
|
244
|
+
|
|
245
|
+
The render prop only exposes the components registered in the library. To write your
|
|
246
|
+
own, read the context directly inside a plain component: `useCellContext<TValue>()`,
|
|
247
|
+
`useHeaderContext()` or `useTableContext()` from `wcz-layout/hooks`.
|
|
248
|
+
`layoutTableFeatures` and the `LayoutTableFeatures` type are the feature set
|
|
249
|
+
`useLayoutTable` installs — you need them only to type a hand-built table instance.
|
|
250
|
+
|
|
251
|
+
## Common Mistakes
|
|
252
|
+
|
|
253
|
+
### CRITICAL: Writing TanStack Table v8 column definitions
|
|
254
|
+
|
|
255
|
+
Wrong: `accessorKey: "name"`, `cell: (info) => info.getValue()`, `getCoreRowModel:
|
|
256
|
+
getCoreRowModel()`.
|
|
257
|
+
|
|
258
|
+
Correct: `columnHelper.accessor("name", { cell: ({ cell }) => <cell.ValueCell /> })`
|
|
259
|
+
inside `columnHelper.columns([...])`, and no row models at all.
|
|
260
|
+
|
|
261
|
+
This is v9. v8 column defs either type-error inside `columnHelper.columns()` or
|
|
262
|
+
silently no-op, and row models are gone.
|
|
263
|
+
|
|
264
|
+
### HIGH: Adding your own virtualizer or pager
|
|
265
|
+
|
|
266
|
+
Wrong: wrapping rows in `useVirtualizer` from `@tanstack/react-virtual`, or bolting on
|
|
267
|
+
a `TablePagination`.
|
|
268
|
+
|
|
269
|
+
Correct: render `<LayoutTable table={table} />` and pass `pagination` if the user wants
|
|
270
|
+
a pager.
|
|
271
|
+
|
|
272
|
+
`LayoutTable` already virtualizes rows and columns. A second virtualizer fights the
|
|
273
|
+
first over scroll position.
|
|
274
|
+
|
|
275
|
+
Use only `LayoutTable`'s `pagination` prop for its pager.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: unslop
|
|
3
|
+
description: Cut AI tells from any writing. Must always apply.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Unslop
|
|
7
|
+
|
|
8
|
+
Edit text to remove AI patterns and add human voice.
|
|
9
|
+
|
|
10
|
+
## Process
|
|
11
|
+
|
|
12
|
+
1. Scan for the patterns below.
|
|
13
|
+
2. Rewrite. Preserve meaning, match intended tone.
|
|
14
|
+
3. Add soul (see next section).
|
|
15
|
+
4. Self-audit: "What makes this obviously AI generated?" Fix remaining tells.
|
|
16
|
+
|
|
17
|
+
## Adding soul
|
|
18
|
+
|
|
19
|
+
Removing patterns is half the job. Sterile, voiceless writing is just as obvious.
|
|
20
|
+
|
|
21
|
+
- **Have opinions.** React to facts instead of neutrally listing pros and cons.
|
|
22
|
+
- **Vary rhythm.** Short sentences. Then longer ones that take their time. Mix it up.
|
|
23
|
+
- **Acknowledge complexity.** "Impressive but also kind of unsettling" beats "impressive."
|
|
24
|
+
- **Use "I" when it fits.** First person isn't unprofessional.
|
|
25
|
+
- **Let some mess in.** Perfect structure looks machine-made.
|
|
26
|
+
- **Be specific.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am."
|
|
27
|
+
|
|
28
|
+
## Patterns to detect and fix
|
|
29
|
+
|
|
30
|
+
### Content
|
|
31
|
+
|
|
32
|
+
1. **Puffery.** "pivotal moment", "testament to", "evolving landscape", "setting the stage for", "indelible mark", "deeply rooted". Cut puffery, state what happened.
|
|
33
|
+
2. **Name-dropping.** Listing media outlets without context. Pick one, say what was said.
|
|
34
|
+
3. **Superficial -ing phrases.** "highlighting...", "ensuring...", "reflecting...", "showcasing...", "fostering...". Delete or expand with real sources.
|
|
35
|
+
4. **Promotional language.** "nestled", "vibrant", "breathtaking", "groundbreaking", "renowned", "stunning", "must-visit". Use neutral descriptions.
|
|
36
|
+
5. **Vague attributions.** "Experts believe", "Industry reports suggest", "Some critics argue". Name the source or delete.
|
|
37
|
+
6. **Formulaic challenges.** "Despite challenges... continues to thrive." Replace with specific facts.
|
|
38
|
+
|
|
39
|
+
### Language
|
|
40
|
+
|
|
41
|
+
7. **AI vocabulary.** Additionally, crucial, delve, enduring, enhance, fostering, garner, interplay, intricate, landscape (abstract), pivotal, showcase, tapestry (abstract), testament, underscore, vibrant. Replace with plain words.
|
|
42
|
+
8. **Fancy ways to say "is".** "serves as", "stands as", "boasts", "features". Just say "is" or "has".
|
|
43
|
+
9. **"Not just X, but Y."** State the point directly instead.
|
|
44
|
+
10. **Rule of three.** Forcing ideas into groups of three. Use the natural number.
|
|
45
|
+
11. **Synonym cycling.** Protagonist, main character, central figure, hero all in one paragraph. Pick one, repeat it.
|
|
46
|
+
12. **False ranges.** "from X to Y" where X and Y aren't on a meaningful scale. List topics directly.
|
|
47
|
+
|
|
48
|
+
### Style
|
|
49
|
+
|
|
50
|
+
13. **Em dash overuse.** Avoid em dashes entirely. Use periods or commas only (no parentheses, no en dashes, no hyphen-as-dash substitutes). Em dashes are an AI tell, and reaching for parentheses instead just trades one tell for another. If a thought needs separation, end the sentence or use a comma.
|
|
51
|
+
14. **Colon overuse.** Colons are fine before a list or example. Not as mid-sentence connectors. "If you're coming from traditional automation: instead of registering event handlers, you describe conditions" adds nothing with the colon. Rewrite to let the point stand on its own without comparison framing. "Describing when the scheduler should fire works best as plain English." Same meaning, no crutch punctuation.
|
|
52
|
+
15. **Boldface overuse.** Don't bold every proper noun or acronym.
|
|
53
|
+
16. **Inline-header lists.** The tell is a bold label and colon that restates the line: "**Performance:** Performance improved...". Convert those to prose. A bold lead-in that ends in a period, names the item, and is followed by genuinely new detail ("**Schema in TypeScript.** Tables live in one file.") is fine, not a tell.
|
|
54
|
+
17. **Title case headings.** Use sentence case.
|
|
55
|
+
18. **Decorative emojis.** Remove from headings and bullets.
|
|
56
|
+
19. **Curly quotes.** Replace with straight quotes.
|
|
57
|
+
|
|
58
|
+
### Communication artifacts
|
|
59
|
+
|
|
60
|
+
20. **Chatbot phrases.** "I hope this helps!", "Let me know if...", "Of course!", "Certainly!", "Found the smoking gun!" Remove.
|
|
61
|
+
21. **Cutoff disclaimers.** "While specific details are limited..." Find sources or remove.
|
|
62
|
+
22. **Sycophantic tone.** "Great question! You're absolutely right!" Respond directly.
|
|
63
|
+
|
|
64
|
+
### Filler
|
|
65
|
+
|
|
66
|
+
23. **Filler phrases.** "In order to" becomes "To". "Due to the fact that" becomes "Because". "It is important to note that" gets deleted.
|
|
67
|
+
24. **Excessive hedging.** "could potentially possibly be argued that it might" becomes "may".
|
|
68
|
+
25. **Generic conclusions.** "The future looks bright." State specific plans or facts.
|
|
69
|
+
|
|
70
|
+
### Jargon
|
|
71
|
+
|
|
72
|
+
26. **Abstract metaphor nouns.** Substrate, wedge, vector, locus, vantage, nexus, primitive (as noun), harness (as metaphor), surface (as in "API surface"), bedrock, scaffolding (as metaphor), modality, paradigm, gold-plating, ratchet (as metaphor), evacuate (for moving code), endgame, north star, flywheel. These read as technical but usually have a plainer concrete word. "Substrate" becomes "base". "Wedge in" becomes "add". "Vector" becomes "way" or "method". "Gold-plating" becomes "more than the job needs". "Ratchet" becomes the mechanism's real name or "a limit that only tightens". "Evacuate" becomes "move out". "Endgame" becomes "the last phase". Pick the concrete word.
|
|
73
|
+
|
|
74
|
+
### Plain speech
|
|
75
|
+
|
|
76
|
+
27. **Say what it does, not how it feels.** "the database stays close at hand", "SQL you can read", "types that follow your schema" name a feeling. The fix names the mechanism or a number: "`.toSQL()` returns the exact string sent to the database", "a column rename fails the build". Ask what the sentence tells the reader to do or know, then write that. If you can't restate it as a concrete instruction, fact, or number, cut it. One more check: if the sentence could appear unchanged in another project's docs, it says nothing about this one. Cut it.
|
|
77
|
+
28. **Shorten or split dense sentences.** If the reader has to backtrack to parse a sentence, break it in two or drop clauses. One idea per sentence.
|
|
78
|
+
29. **Active voice.** Prefer it. Catch "is/are/was/were + past participle" and name the actor: "queries are validated" becomes "the compiler validates queries", "the file is parsed by the loader" becomes "the loader parses the file". Passive is fine only when the actor is unknown or genuinely doesn't matter.
|
|
79
|
+
30. **Cut adverbs, or use a stronger verb.** "runs quickly" becomes "is fast" or the number. "significantly improves" becomes the measured delta. An adverb propping up a weak verb means the verb is wrong.
|
|
80
|
+
31. **Prefer the plain word.** "utilize" becomes "use", "leverage" becomes "use", "facilitate" becomes "help", "numerous" becomes "many", "in the event that" becomes "if". The fancier synonym is rarely clearer.
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationContext-CgwUOeW0.mjs","names":[],"sources":["../src/contexts/NotificationContext.tsx"],"sourcesContent":["import { createContext } from \"react\";\nimport type { AlertColor } from \"@mui/material/Alert\";\n\nexport interface NotificationOptions {\n severity?: AlertColor;\n autoHideDuration?: number;\n}\n\nexport interface NotificationContextValue {\n notify: (message: string, options?: NotificationOptions) => void;\n}\n\nexport const NotificationContext = createContext<NotificationContextValue | null>(null);\n"],"mappings":";;AAYA,MAAa,sBAAsB,cAA+C,IAAI"}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { i as buildUser, m as serverEnv, o as hasPermission, u as getSessionUser } from "./utils-DjdexspV.mjs";
|
|
2
|
-
import { createMiddleware } from "@tanstack/react-start";
|
|
3
|
-
import * as jose from "jose";
|
|
4
|
-
//#region src/middleware/authMiddleware.ts
|
|
5
|
-
async function resolveUser(request) {
|
|
6
|
-
const authHeader = request.headers.get("Authorization");
|
|
7
|
-
if (authHeader?.startsWith("Bearer ")) {
|
|
8
|
-
let payload;
|
|
9
|
-
try {
|
|
10
|
-
payload = await verifyToken(authHeader.substring(7));
|
|
11
|
-
} catch (error) {
|
|
12
|
-
throw Response.json({ message: error instanceof Error ? error.message : "Unauthorized: Invalid access token" }, { status: 401 });
|
|
13
|
-
}
|
|
14
|
-
return buildUser(payload);
|
|
15
|
-
}
|
|
16
|
-
return getSessionUser();
|
|
17
|
-
}
|
|
18
|
-
const requiredAuthenticationMiddleware = createMiddleware().server(async ({ next, request }) => {
|
|
19
|
-
const user = await resolveUser(request);
|
|
20
|
-
if (!user) throw Response.json({ message: "Unauthorized: User not signed in" }, { status: 401 });
|
|
21
|
-
return next({ context: { user } });
|
|
22
|
-
});
|
|
23
|
-
const publicAuthenticationMiddleware = createMiddleware().server(async ({ next, request }) => {
|
|
24
|
-
return next({ context: { user: await resolveUser(request) } });
|
|
25
|
-
});
|
|
26
|
-
function authenticationMiddleware(options) {
|
|
27
|
-
return options?.optional ? publicAuthenticationMiddleware : requiredAuthenticationMiddleware;
|
|
28
|
-
}
|
|
29
|
-
const authorizationMiddleware = (permissionKey) => createMiddleware().middleware([authenticationMiddleware()]).server(async ({ next, context }) => {
|
|
30
|
-
if (hasPermission(context.user, permissionKey)) return next();
|
|
31
|
-
throw Response.json({ message: `Forbidden: User ${context.user.name} is not authorized to access this resource` }, { status: 403 });
|
|
32
|
-
});
|
|
33
|
-
async function verifyToken(token) {
|
|
34
|
-
const { payload } = await jose.jwtVerify(token, getJWKS(), {
|
|
35
|
-
issuer: `https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}/v2.0`,
|
|
36
|
-
audience: serverEnv.ENTRA_CLIENT_ID
|
|
37
|
-
});
|
|
38
|
-
return payload;
|
|
39
|
-
}
|
|
40
|
-
let jwksCache = null;
|
|
41
|
-
function getJWKS() {
|
|
42
|
-
jwksCache ??= jose.createRemoteJWKSet(new URL(`https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}/discovery/v2.0/keys`));
|
|
43
|
-
return jwksCache;
|
|
44
|
-
}
|
|
45
|
-
//#endregion
|
|
46
|
-
export { authorizationMiddleware as n, authenticationMiddleware as t };
|
|
47
|
-
|
|
48
|
-
//# sourceMappingURL=authMiddleware-DPly0b_T.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"authMiddleware-DPly0b_T.mjs","names":[],"sources":["../src/middleware/authMiddleware.ts"],"sourcesContent":["import { createMiddleware } from \"@tanstack/react-start\";\nimport * as jose from \"jose\";\nimport type { permissions } from \"virtual:wcz-layout\";\nimport { serverEnv } from \"~/env\";\nimport { getSessionUser } from \"~/lib/auth/user\";\nimport { buildUser, hasPermission } from \"~/lib/utils\";\nimport type { TokenPayload } from \"~/models/TokenPayload\";\nimport type { User } from \"~/models/User\";\n\nasync function resolveUser(request: Request): Promise<User | null> {\n const authHeader = request.headers.get(\"Authorization\");\n\n if (authHeader?.startsWith(\"Bearer \")) {\n let payload: TokenPayload;\n try {\n payload = await verifyToken(authHeader.substring(\"Bearer \".length));\n } catch (error) {\n throw Response.json(\n { message: error instanceof Error ? error.message : \"Unauthorized: Invalid access token\" },\n { status: 401 },\n );\n }\n return buildUser(payload);\n }\n\n return getSessionUser();\n}\n\nconst requiredAuthenticationMiddleware = createMiddleware().server<{ user: User }>(\n async ({ next, request }) => {\n const user = await resolveUser(request);\n\n if (!user)\n throw Response.json({ message: \"Unauthorized: User not signed in\" }, { status: 401 });\n\n return next({ context: { user } });\n },\n);\n\nconst publicAuthenticationMiddleware = createMiddleware().server<{ user: User | null }>(\n async ({ next, request }) => {\n const user = await resolveUser(request);\n return next({ context: { user } });\n },\n);\n\nexport function authenticationMiddleware(options?: {\n optional?: false;\n}): typeof requiredAuthenticationMiddleware;\n\nexport function authenticationMiddleware(options: {\n optional: true;\n}): typeof publicAuthenticationMiddleware;\n\nexport function authenticationMiddleware(options: {\n optional: boolean;\n}): typeof requiredAuthenticationMiddleware | typeof publicAuthenticationMiddleware;\n\nexport function authenticationMiddleware(options?: { optional?: boolean }) {\n return options?.optional ? publicAuthenticationMiddleware : requiredAuthenticationMiddleware;\n}\n\nexport const authorizationMiddleware = (permissionKey: keyof typeof permissions) =>\n createMiddleware()\n .middleware([authenticationMiddleware()])\n .server(async ({ next, context }) => {\n if (hasPermission(context.user, permissionKey)) return next();\n throw Response.json(\n {\n message: `Forbidden: User ${context.user.name} is not authorized to access this resource`,\n },\n { status: 403 },\n );\n });\n\nasync function verifyToken(token: string): Promise<TokenPayload> {\n const { payload } = await jose.jwtVerify(token, getJWKS(), {\n issuer: `https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}/v2.0`,\n audience: serverEnv.ENTRA_CLIENT_ID,\n });\n return payload as unknown as TokenPayload;\n}\n\nlet jwksCache: ReturnType<typeof jose.createRemoteJWKSet> | null = null;\n\nfunction getJWKS() {\n jwksCache ??= jose.createRemoteJWKSet(\n new URL(`https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}/discovery/v2.0/keys`),\n );\n return jwksCache;\n}\n"],"mappings":";;;;AASA,eAAe,YAAY,SAAwC;CACjE,MAAM,aAAa,QAAQ,QAAQ,IAAI,eAAe;CAEtD,IAAI,YAAY,WAAW,SAAS,GAAG;EACrC,IAAI;EACJ,IAAI;GACF,UAAU,MAAM,YAAY,WAAW,UAAU,CAAgB,CAAC;EACpE,SAAS,OAAO;GACd,MAAM,SAAS,KACb,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,qCAAqC,GACzF,EAAE,QAAQ,IAAI,CAChB;EACF;EACA,OAAO,UAAU,OAAO;CAC1B;CAEA,OAAO,eAAe;AACxB;AAEA,MAAM,mCAAmC,iBAAiB,CAAC,CAAC,OAC1D,OAAO,EAAE,MAAM,cAAc;CAC3B,MAAM,OAAO,MAAM,YAAY,OAAO;CAEtC,IAAI,CAAC,MACH,MAAM,SAAS,KAAK,EAAE,SAAS,mCAAmC,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEtF,OAAO,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;AACnC,CACF;AAEA,MAAM,iCAAiC,iBAAiB,CAAC,CAAC,OACxD,OAAO,EAAE,MAAM,cAAc;CAE3B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAA,MADN,YAAY,OAAO,EACR,EAAE,CAAC;AACnC,CACF;AAcA,SAAgB,yBAAyB,SAAkC;CACzE,OAAO,SAAS,WAAW,iCAAiC;AAC9D;AAEA,MAAa,2BAA2B,kBACtC,iBAAiB,CAAC,CACf,WAAW,CAAC,yBAAyB,CAAC,CAAC,CAAC,CACxC,OAAO,OAAO,EAAE,MAAM,cAAc;CACnC,IAAI,cAAc,QAAQ,MAAM,aAAa,GAAG,OAAO,KAAK;CAC5D,MAAM,SAAS,KACb,EACE,SAAS,mBAAmB,QAAQ,KAAK,KAAI,4CAC/C,GACA,EAAE,QAAQ,IAAI,CAChB;AACF,CAAC;AAEL,eAAe,YAAY,OAAsC;CAC/D,MAAM,EAAE,YAAY,MAAM,KAAK,UAAU,OAAO,QAAQ,GAAG;EACzD,QAAQ,qCAAqC,UAAU,gBAAe;EACtE,UAAU,UAAU;CACtB,CAAC;CACD,OAAO;AACT;AAEA,IAAI,YAA+D;AAEnE,SAAS,UAAU;CACjB,cAAc,KAAK,mBACjB,IAAI,IAAI,qCAAqC,UAAU,gBAAe,qBAAsB,CAC9F;CACA,OAAO;AACT"}
|
package/dist/entra-CJSyeQsx.mjs
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import { m as serverEnv } from "./utils-DjdexspV.mjs";
|
|
2
|
-
import { ConfidentialClientApplication, CryptoProvider, InteractionRequiredAuthError, ServerError } from "@azure/msal-node";
|
|
3
|
-
//#region src/lib/auth/entra.ts
|
|
4
|
-
/**
|
|
5
|
-
* Scopes requested during the interactive login. `offline_access` yields the
|
|
6
|
-
* refresh token that the session is built around; `User.Read` lets us read the
|
|
7
|
-
* user's Graph profile (e.g. avatar). Resource API scopes (file, approval, …) are
|
|
8
|
-
* acquired on demand via {@link acquireDelegatedToken} using the multi-resource
|
|
9
|
-
* refresh token.
|
|
10
|
-
*/
|
|
11
|
-
const LOGIN_SCOPES = [
|
|
12
|
-
"openid",
|
|
13
|
-
"profile",
|
|
14
|
-
"offline_access",
|
|
15
|
-
"User.Read"
|
|
16
|
-
];
|
|
17
|
-
/** Entra authority for this tenant. */
|
|
18
|
-
const ENTRA_AUTHORITY = `https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}`;
|
|
19
|
-
/** Shared across login/callback/refresh calls — stateless and cheap to reuse. */
|
|
20
|
-
const cryptoProvider = new CryptoProvider();
|
|
21
|
-
/**
|
|
22
|
-
* Creates a confidential client (no persistent cache plugin).
|
|
23
|
-
*
|
|
24
|
-
* The interactive/refresh flows below deliberately use a FRESH client per token
|
|
25
|
-
* operation rather than a singleton: the client's in-memory cache then holds only
|
|
26
|
-
* that operation's tokens, so {@link extractRefreshToken} reads the correct user's
|
|
27
|
-
* refresh token — a shared client would accumulate (and leak) every user's tokens.
|
|
28
|
-
* Persisting just the refresh token (not the whole multi-KB MSAL cache) is what
|
|
29
|
-
* keeps the session in a small cookie with no server-side token store.
|
|
30
|
-
*/
|
|
31
|
-
const createConfidentialClient = () => new ConfidentialClientApplication({ auth: {
|
|
32
|
-
clientId: serverEnv.ENTRA_CLIENT_ID,
|
|
33
|
-
clientSecret: serverEnv.ENTRA_CLIENT_SECRET,
|
|
34
|
-
authority: ENTRA_AUTHORITY
|
|
35
|
-
} });
|
|
36
|
-
/**
|
|
37
|
-
* Pulls the refresh-token secret out of a client's in-memory MSAL cache. MSAL
|
|
38
|
-
* intentionally hides refresh tokens, so reading the serialized cache is the only
|
|
39
|
-
* way to persist just the RT (instead of the whole cache) in the session cookie.
|
|
40
|
-
*/
|
|
41
|
-
function extractRefreshToken(client) {
|
|
42
|
-
const cache = JSON.parse(client.getTokenCache().serialize());
|
|
43
|
-
return Object.values(cache.RefreshToken ?? {})[0]?.secret;
|
|
44
|
-
}
|
|
45
|
-
/** First leg of the auth-code flow: the URL to redirect the browser to. */
|
|
46
|
-
function buildAuthCodeUrl(opts) {
|
|
47
|
-
return createConfidentialClient().getAuthCodeUrl({
|
|
48
|
-
scopes: LOGIN_SCOPES,
|
|
49
|
-
redirectUri: opts.redirectUri,
|
|
50
|
-
responseMode: "query",
|
|
51
|
-
state: opts.state,
|
|
52
|
-
codeChallenge: opts.codeChallenge,
|
|
53
|
-
codeChallengeMethod: "S256"
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Second leg of the auth-code flow: exchange the code for tokens, returning the
|
|
58
|
-
* refresh token and the id-token claims to persist in the session.
|
|
59
|
-
*/
|
|
60
|
-
async function exchangeCodeForSession(opts) {
|
|
61
|
-
const client = createConfidentialClient();
|
|
62
|
-
const result = await client.acquireTokenByCode({
|
|
63
|
-
code: opts.code,
|
|
64
|
-
scopes: LOGIN_SCOPES,
|
|
65
|
-
redirectUri: opts.redirectUri,
|
|
66
|
-
codeVerifier: opts.codeVerifier
|
|
67
|
-
});
|
|
68
|
-
const refreshToken = extractRefreshToken(client);
|
|
69
|
-
if (!refreshToken) throw new Error("No refresh token returned (is the offline_access scope granted?)");
|
|
70
|
-
return {
|
|
71
|
-
refreshToken,
|
|
72
|
-
claims: result.idTokenClaims ?? {}
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Acquires a delegated access token for `scopes` from the stored refresh token.
|
|
77
|
-
* Entra rotates the refresh token on each use, so the (possibly new) refresh
|
|
78
|
-
* token is returned for the caller to persist. Throws when the refresh token is
|
|
79
|
-
* expired/revoked and interaction is required.
|
|
80
|
-
*/
|
|
81
|
-
/** The refresh token is expired/revoked — the user must sign in interactively. */
|
|
82
|
-
var SessionExpiredError = class extends Error {};
|
|
83
|
-
async function acquireDelegatedToken(opts) {
|
|
84
|
-
const client = createConfidentialClient();
|
|
85
|
-
let result;
|
|
86
|
-
try {
|
|
87
|
-
result = await client.acquireTokenByRefreshToken({
|
|
88
|
-
refreshToken: opts.refreshToken,
|
|
89
|
-
scopes: [...opts.scopes],
|
|
90
|
-
forceCache: true
|
|
91
|
-
});
|
|
92
|
-
} catch (error) {
|
|
93
|
-
if (error instanceof InteractionRequiredAuthError && error.subError !== "consent_required" || error instanceof ServerError && error.errorCode === "invalid_grant") throw new SessionExpiredError(error.message);
|
|
94
|
-
throw error;
|
|
95
|
-
}
|
|
96
|
-
if (!result) throw new Error("Failed to acquire token from refresh token");
|
|
97
|
-
return {
|
|
98
|
-
accessToken: result.accessToken,
|
|
99
|
-
refreshToken: extractRefreshToken(client) ?? opts.refreshToken
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
/** Entra's front-channel logout endpoint, which clears the user's IdP session. */
|
|
103
|
-
function buildLogoutUrl(postLogoutRedirectUri) {
|
|
104
|
-
return `${`${ENTRA_AUTHORITY}/oauth2/v2.0/logout`}?post_logout_redirect_uri=${encodeURIComponent(postLogoutRedirectUri)}`;
|
|
105
|
-
}
|
|
106
|
-
//#endregion
|
|
107
|
-
export { SessionExpiredError, acquireDelegatedToken, buildAuthCodeUrl, buildLogoutUrl, createConfidentialClient, cryptoProvider, exchangeCodeForSession };
|
|
108
|
-
|
|
109
|
-
//# sourceMappingURL=entra-CJSyeQsx.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"entra-CJSyeQsx.mjs","names":[],"sources":["../src/lib/auth/entra.ts"],"sourcesContent":["import {\n ConfidentialClientApplication,\n CryptoProvider,\n InteractionRequiredAuthError,\n ServerError,\n} from \"@azure/msal-node\";\nimport type { TokenPayload } from \"~/models/TokenPayload\";\nimport { serverEnv } from \"~/env\";\n\n/**\n * Scopes requested during the interactive login. `offline_access` yields the\n * refresh token that the session is built around; `User.Read` lets us read the\n * user's Graph profile (e.g. avatar). Resource API scopes (file, approval, …) are\n * acquired on demand via {@link acquireDelegatedToken} using the multi-resource\n * refresh token.\n */\nexport const LOGIN_SCOPES = [\"openid\", \"profile\", \"offline_access\", \"User.Read\"];\n\n/** Entra authority for this tenant. */\nexport const ENTRA_AUTHORITY = `https://login.microsoftonline.com/${serverEnv.ENTRA_TENANT_ID}`;\n\n/** Shared across login/callback/refresh calls — stateless and cheap to reuse. */\nexport const cryptoProvider = new CryptoProvider();\n\n/**\n * Creates a confidential client (no persistent cache plugin).\n *\n * The interactive/refresh flows below deliberately use a FRESH client per token\n * operation rather than a singleton: the client's in-memory cache then holds only\n * that operation's tokens, so {@link extractRefreshToken} reads the correct user's\n * refresh token — a shared client would accumulate (and leak) every user's tokens.\n * Persisting just the refresh token (not the whole multi-KB MSAL cache) is what\n * keeps the session in a small cookie with no server-side token store.\n */\nexport const createConfidentialClient = (): ConfidentialClientApplication =>\n new ConfidentialClientApplication({\n auth: {\n clientId: serverEnv.ENTRA_CLIENT_ID,\n clientSecret: serverEnv.ENTRA_CLIENT_SECRET,\n authority: ENTRA_AUTHORITY,\n },\n });\n\n/**\n * Pulls the refresh-token secret out of a client's in-memory MSAL cache. MSAL\n * intentionally hides refresh tokens, so reading the serialized cache is the only\n * way to persist just the RT (instead of the whole cache) in the session cookie.\n */\nfunction extractRefreshToken(client: ConfidentialClientApplication): string | undefined {\n const cache = JSON.parse(client.getTokenCache().serialize()) as {\n RefreshToken?: Record<string, { secret?: string }>;\n };\n return Object.values(cache.RefreshToken ?? {})[0]?.secret;\n}\n\n/** First leg of the auth-code flow: the URL to redirect the browser to. */\nexport function buildAuthCodeUrl(opts: {\n redirectUri: string;\n state: string;\n codeChallenge: string;\n}): Promise<string> {\n return createConfidentialClient().getAuthCodeUrl({\n scopes: LOGIN_SCOPES,\n redirectUri: opts.redirectUri,\n responseMode: \"query\",\n state: opts.state,\n codeChallenge: opts.codeChallenge,\n codeChallengeMethod: \"S256\",\n });\n}\n\n/**\n * Second leg of the auth-code flow: exchange the code for tokens, returning the\n * refresh token and the id-token claims to persist in the session.\n */\nexport async function exchangeCodeForSession(opts: {\n code: string;\n redirectUri: string;\n codeVerifier: string;\n}): Promise<{ refreshToken: string; claims: TokenPayload }> {\n const client = createConfidentialClient();\n const result = await client.acquireTokenByCode({\n code: opts.code,\n scopes: LOGIN_SCOPES,\n redirectUri: opts.redirectUri,\n codeVerifier: opts.codeVerifier,\n });\n\n const refreshToken = extractRefreshToken(client);\n if (!refreshToken)\n throw new Error(\"No refresh token returned (is the offline_access scope granted?)\");\n\n return { refreshToken, claims: (result.idTokenClaims ?? {}) as TokenPayload };\n}\n\n/**\n * Acquires a delegated access token for `scopes` from the stored refresh token.\n * Entra rotates the refresh token on each use, so the (possibly new) refresh\n * token is returned for the caller to persist. Throws when the refresh token is\n * expired/revoked and interaction is required.\n */\n/** The refresh token is expired/revoked — the user must sign in interactively. */\nexport class SessionExpiredError extends Error {}\n\nexport async function acquireDelegatedToken(opts: {\n refreshToken: string;\n scopes: ReadonlyArray<string>;\n}): Promise<{ accessToken: string; refreshToken: string }> {\n const client = createConfidentialClient();\n let result;\n try {\n result = await client.acquireTokenByRefreshToken({\n refreshToken: opts.refreshToken,\n scopes: [...opts.scopes],\n forceCache: true,\n });\n } catch (error) {\n // Revocation, inactivity expiry (AADSTS70008/700082/50173) and Conditional\n // Access sign-in frequency (AADSTS70043) all surface as interaction-required\n // or invalid_grant — the session is dead, only an interactive login helps.\n // Missing consent for the requested resource (AADSTS65001) looks the same to\n // MSAL but is a configuration bug, not a dead session — let it surface as-is.\n if (\n (error instanceof InteractionRequiredAuthError && error.subError !== \"consent_required\") ||\n (error instanceof ServerError && error.errorCode === \"invalid_grant\")\n )\n throw new SessionExpiredError(error.message);\n throw error;\n }\n if (!result) throw new Error(\"Failed to acquire token from refresh token\");\n\n return {\n accessToken: result.accessToken,\n refreshToken: extractRefreshToken(client) ?? opts.refreshToken,\n };\n}\n\n/** Entra's front-channel logout endpoint, which clears the user's IdP session. */\nexport function buildLogoutUrl(postLogoutRedirectUri: string): string {\n const base = `${ENTRA_AUTHORITY}/oauth2/v2.0/logout`;\n return `${base}?post_logout_redirect_uri=${encodeURIComponent(postLogoutRedirectUri)}`;\n}\n"],"mappings":";;;;;;;;;;AAgBA,MAAa,eAAe;CAAC;CAAU;CAAW;CAAkB;AAAW;;AAG/E,MAAa,kBAAkB,qCAAqC,UAAU;;AAG9E,MAAa,iBAAiB,IAAI,eAAe;;;;;;;;;;;AAYjD,MAAa,iCACX,IAAI,8BAA8B,EAChC,MAAM;CACJ,UAAU,UAAU;CACpB,cAAc,UAAU;CACxB,WAAW;AACb,EACF,CAAC;;;;;;AAOH,SAAS,oBAAoB,QAA2D;CACtF,MAAM,QAAQ,KAAK,MAAM,OAAO,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
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-BWcNzq55.mjs","names":[],"sources":["../src/lib/createApi.ts","../src/data/server/file.ts"],"sourcesContent":["import { createServerOnlyFn } from \"@tanstack/react-start\";\nimport axios, { AxiosError, type AxiosInstance } from \"axios\";\nimport https from \"node:https\";\nimport type { serverEnv } from \"virtual:wcz-layout\";\nimport { scopes as definedScopes } from \"virtual:wcz-layout\";\nimport { getAppToken } from \"~/lib/auth/msalServer\";\nimport { getAccessToken, getSessionUser } from \"~/lib/auth/user\";\n\nexport interface ApiOptions {\n baseURL: keyof typeof serverEnv & `${string}BASE_URL${string}`;\n scopeKey: keyof typeof definedScopes;\n}\n\nconst httpsAgent = new https.Agent({\n rejectUnauthorized: false,\n});\n\nexport const createApi = createServerOnlyFn(\n async ({ baseURL, scopeKey }: ApiOptions): Promise<AxiosInstance> => {\n const resolvedBaseURL = process.env[baseURL];\n if (!resolvedBaseURL) throw new Error(`\"${baseURL}\" env variable is not set.`);\n\n const accessToken = (await getSessionUser())\n ? await getAccessToken(scopeKey)\n : await getAppToken(scopeKey);\n\n const api = axios.create({\n baseURL: resolvedBaseURL,\n httpsAgent,\n headers: { Authorization: `Bearer ${accessToken}` },\n });\n\n api.interceptors.response.use(undefined, (error: unknown) => {\n if (error instanceof AxiosError)\n throw new Error(error.response?.data?.message ?? error.message);\n throw error;\n });\n\n return api;\n },\n);\n","import { createServerOnlyFn } from \"@tanstack/react-start\";\r\nimport type { AxiosResponse } from \"axios\";\r\nimport https from \"node:https\";\r\nimport { Readable } from \"node:stream\";\r\nimport { DefaultHttpStack, Upload } from \"tus-js-client\";\r\nimport { z } from \"zod\";\r\nimport { serverEnv } from \"~/env\";\r\nimport { uuidv7 } from \"~/exports/utils\";\r\nimport { getAppToken } from \"~/lib/auth/msalServer\";\r\nimport { getAccessToken, getSessionUser } from \"~/lib/auth/user\";\r\nimport { createApi } from \"~/lib/createApi\";\r\nimport type { FileMeta } from \"~/models/file/FileMeta\";\r\nimport { FileMetaSchema } from \"~/models/file/FileMeta\";\r\n\r\nexport const GetFileMetasSchema = z.object({\r\n appName: z.string().min(1).max(255),\r\n subId: z.uuid(),\r\n});\r\n\r\nexport const FileSchema = z.object({\r\n appName: z.string().min(1).max(255),\r\n id: z.uuid(),\r\n});\r\n\r\nexport const UpdateFileMetaSchema = FileMetaSchema.extend({\r\n fileName: z.string().min(1).max(255),\r\n});\r\n\r\nconst DeleteFileSchema = FileSchema;\r\n\r\nconst BatchDeleteFilesSchema = GetFileMetasSchema;\r\n\r\nexport interface UploadFileResult {\r\n id: string;\r\n appName: string;\r\n subId: string;\r\n fileName: string;\r\n}\r\n\r\nexport const UploadFileMetaSchema = z.object({\r\n id: z.uuid().default(uuidv7),\r\n appName: z.string().min(1).max(255),\r\n subId: z.uuid(),\r\n file: z.instanceof(File),\r\n});\r\n\r\nconst fileApi = () => createApi({ baseURL: \"FILE_BASE_URL\", scopeKey: \"file\" });\r\n\r\nfunction toFileResponse(response: AxiosResponse<Readable>, disposition?: string): Response {\r\n const headers = new Headers({\r\n \"Cache-Control\": \"private, max-age=3600, immutable\",\r\n \"Content-Type\": String(response.headers[\"content-type\"] ?? \"application/octet-stream\"),\r\n });\r\n const contentLength = response.headers[\"content-length\"];\r\n if (contentLength) headers.set(\"Content-Length\", String(contentLength));\r\n if (disposition) headers.set(\"Content-Disposition\", disposition);\r\n\r\n return new Response(Readable.toWeb(response.data) as ReadableStream, { headers });\r\n}\r\n\r\nexport const getFileMetas = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof GetFileMetasSchema> }): Promise<Array<FileMeta>> => {\r\n const input = GetFileMetasSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"subId\", input.subId);\r\n\r\n const api = await fileApi();\r\n const { data: fileMetas } = await api.request<Array<FileMeta>>({\r\n url: `/v1/meta?${queryParams.toString()}`,\r\n method: \"GET\",\r\n });\r\n return fileMetas;\r\n },\r\n);\r\n\r\nexport const getFileThumbnail = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof FileSchema> }): Promise<Response> => {\r\n const input = FileSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"id\", input.id);\r\n\r\n const api = await fileApi();\r\n const response = await api.request<Readable>({\r\n url: `/v1/thumbnail?${queryParams.toString()}`,\r\n method: \"GET\",\r\n responseType: \"stream\",\r\n });\r\n\r\n return toFileResponse(response);\r\n },\r\n);\r\n\r\nexport const getFile = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof FileSchema> }): Promise<Response> => {\r\n const input = FileSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"id\", input.id);\r\n\r\n const api = await fileApi();\r\n const response = await api.request<Readable>({\r\n url: `/v1?${queryParams.toString()}`,\r\n method: \"GET\",\r\n responseType: \"stream\",\r\n });\r\n\r\n return toFileResponse(response, \"inline\");\r\n },\r\n);\r\n\r\nexport const downloadFile = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof FileSchema> }): Promise<Response> => {\r\n const input = FileSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"id\", input.id);\r\n\r\n const api = await fileApi();\r\n const response = await api.request<Readable>({\r\n url: `/v1/download?${queryParams.toString()}`,\r\n method: \"GET\",\r\n responseType: \"stream\",\r\n });\r\n\r\n return toFileResponse(response);\r\n },\r\n);\r\n\r\nexport const updateFileMeta = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof UpdateFileMetaSchema> }): Promise<void> => {\r\n const input = UpdateFileMetaSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"id\", input.id);\r\n\r\n const api = await fileApi();\r\n await api.request({ url: `/v1/meta?${queryParams.toString()}`, method: \"PUT\", data: input });\r\n },\r\n);\r\n\r\nexport const deleteFile = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof DeleteFileSchema> }): Promise<void> => {\r\n const input = DeleteFileSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"id\", input.id);\r\n\r\n const api = await fileApi();\r\n await api.request({ url: `/v1?${queryParams.toString()}`, method: \"DELETE\" });\r\n },\r\n);\r\n\r\nexport const batchDeleteFiles = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof BatchDeleteFilesSchema> }): Promise<void> => {\r\n const input = BatchDeleteFilesSchema.parse(data);\r\n const queryParams = new URLSearchParams();\r\n queryParams.append(\"appName\", input.appName);\r\n queryParams.append(\"subId\", input.subId);\r\n\r\n const api = await fileApi();\r\n await api.request({ url: `/v1?${queryParams.toString()}`, method: \"DELETE\" });\r\n },\r\n);\r\n\r\nconst insecureHttpsAgent = new https.Agent({ rejectUnauthorized: false });\r\n\r\nexport const uploadFile = createServerOnlyFn(\r\n async ({ data }: { data: z.input<typeof UploadFileMetaSchema> }): Promise<UploadFileResult> => {\r\n const input = UploadFileMetaSchema.parse(data);\r\n const accessToken = (await getSessionUser())\r\n ? await getAccessToken(\"file\")\r\n : await getAppToken(\"file\");\r\n const stream = Readable.fromWeb(\r\n input.file.stream() as import(\"node:stream/web\").ReadableStream,\r\n );\r\n\r\n await new Promise<void>((resolve, reject) => {\r\n const upload = new Upload(stream, {\r\n endpoint: `${serverEnv.FILE_BASE_URL}/v1/upload`,\r\n httpStack: new DefaultHttpStack({ agent: insecureHttpsAgent }),\r\n uploadSize: input.file.size,\r\n chunkSize: 1_048_576,\r\n metadata: {\r\n id: input.id,\r\n appName: input.appName,\r\n subId: input.subId,\r\n filename: input.file.name,\r\n filetype: input.file.type,\r\n },\r\n headers: { Authorization: `Bearer ${accessToken}` },\r\n onError: reject,\r\n onSuccess: () => resolve(),\r\n });\r\n upload.start();\r\n });\r\n\r\n return {\r\n id: input.id,\r\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AEA,MAAa,mBAAmB,mBAC9B,OAAO,EAAE,WAA4E;CACnF,MAAM,QAAQ,uBAAuB,MAAM,IAAI;CAC/C,MAAM,cAAc,IAAI,gBAAgB;CACxC,YAAY,OAAO,WAAW,MAAM,OAAO;CAC3C,YAAY,OAAO,SAAS,MAAM,KAAK;CAGvC,OAAM,MADY,QAAQ,EAAA,CAChB,QAAQ;EAAE,KAAK,OAAO,YAAY,SAAS;EAAK,QAAQ;CAAS,CAAC;AAC9E,CACF;AAEA,MAAM,qBAAqB,IAAI,MAAM,MAAM,EAAE,oBAAoB,MAAM,CAAC;AAExE,MAAa,aAAa,mBACxB,OAAO,EAAE,WAAsF;CAC7F,MAAM,QAAQ,qBAAqB,MAAM,IAAI;CAC7C,MAAM,cAAe,MAAM,eAAe,IACtC,MAAM,eAAe,MAAM,IAC3B,MAAM,YAAY,MAAM;CAC5B,MAAM,SAAS,SAAS,QACtB,MAAM,KAAK,OAAO,CACpB;CAEA,MAAM,IAAI,SAAe,SAAS,WAAW;EAiB3C,IAhBmB,OAAO,QAAQ;GAChC,UAAU,GAAG,UAAU,cAAa;GACpC,WAAW,IAAI,iBAAiB,EAAE,OAAO,mBAAmB,CAAC;GAC7D,YAAY,MAAM,KAAK;GACvB,WAAW;GACX,UAAU;IACR,IAAI,MAAM;IACV,SAAS,MAAM;IACf,OAAO,MAAM;IACb,UAAU,MAAM,KAAK;IACrB,UAAU,MAAM,KAAK;GACvB;GACA,SAAS,EAAE,eAAe,UAAU,cAAc;GAClD,SAAS;GACT,iBAAiB,QAAQ;EAC3B,CACA,CAAM,CAAC,MAAM;CACf,CAAC;CAED,OAAO;EACL,IAAI,MAAM;EACV,SAAS,MAAM;EACf,OAAO,MAAM;EACb,UAAU,MAAM,KAAK;CACvB;AACF,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-DimNsRly.mjs","names":[],"sources":["../src/server/actions/file.ts","../src/data/client/file.ts"],"sourcesContent":["import { createServerFn } from \"@tanstack/react-start\";\nimport { serverEnv } from \"~/env\";\nimport { getAppToken } from \"~/lib/auth/msalServer\";\nimport { getAccessToken } from \"~/lib/auth/user\";\nimport { authenticationMiddleware } from \"~/middleware/authMiddleware\";\n\nexport const getFileUploadToken = createServerFn({ method: \"GET\" })\n .middleware([authenticationMiddleware({ optional: true })])\n .handler(async ({ context }) => ({\n token: context.user ? await getAccessToken(\"file\") : await getAppToken(\"file\"),\n endpoint: `${serverEnv.FILE_BASE_URL}/v1/upload`,\n }));\n","import { mutationOptions, queryOptions } from \"@tanstack/react-query\";\r\nimport { createServerFn } from \"@tanstack/react-start\";\r\nimport { Upload } from \"tus-js-client\";\r\nimport { uuidv7 } from \"uuidv7\";\r\nimport type { z } from \"zod\";\r\nimport type { UploadFileMetaSchema, UploadFileResult } from \"~/data/server/file\";\r\nimport {\r\n FileSchema,\r\n GetFileMetasSchema,\r\n UpdateFileMetaSchema,\r\n batchDeleteFiles,\r\n deleteFile,\r\n downloadFile,\r\n getFile,\r\n getFileMetas,\r\n getFileThumbnail,\r\n updateFileMeta,\r\n} from \"~/data/server/file\";\r\nimport type { QueryClientParam } from \"~/models/QueryClientParam\";\r\nimport { getFileUploadToken } from \"~/server/actions/file\";\r\n\r\nconst QUERY_KEY = \"file\";\r\nconst HOUR = 1000 * 60 * 60;\r\n\r\nconst getFileMetasRpc = createServerFn({ method: \"GET\" })\r\n .validator(GetFileMetasSchema)\r\n .handler(({ data }) => getFileMetas({ data }));\r\n\r\nconst getFileThumbnailRpc = createServerFn({ method: \"GET\" })\r\n .validator(FileSchema)\r\n .handler(({ data }) => getFileThumbnail({ data }));\r\n\r\nconst getFileRpc = createServerFn({ method: \"GET\" })\r\n .validator(FileSchema)\r\n .handler(({ data }) => getFile({ data }));\r\n\r\nconst downloadFileRpc = createServerFn({ method: \"GET\" })\r\n .validator(FileSchema)\r\n .handler(({ data }) => downloadFile({ data }));\r\n\r\nconst updateFileMetaRpc = createServerFn({ method: \"POST\" })\r\n .validator(UpdateFileMetaSchema)\r\n .handler(({ data }) => updateFileMeta({ data }));\r\n\r\nconst deleteFileRpc = createServerFn({ method: \"POST\" })\r\n .validator(FileSchema)\r\n .handler(({ data }) => deleteFile({ data }));\r\n\r\nconst batchDeleteFilesRpc = createServerFn({ method: \"POST\" })\r\n .validator(GetFileMetasSchema)\r\n .handler(({ data }) => batchDeleteFiles({ data }));\r\n\r\nconst baseOptions = {\r\n staleTime: HOUR,\r\n gcTime: HOUR,\r\n refetchOnWindowFocus: false,\r\n};\r\n\r\nasync function responseToObjectUrl(response: Response): Promise<string> {\r\n const blob = await response.blob();\r\n return URL.createObjectURL(blob);\r\n}\r\n\r\nfunction saveBlob(blob: Blob, fileName: string): void {\r\n const url = URL.createObjectURL(blob);\r\n const anchor = document.createElement(\"a\");\r\n anchor.href = url;\r\n anchor.download = fileName;\r\n anchor.click();\r\n URL.revokeObjectURL(url);\r\n}\r\n\r\nexport const fileMetasQueryOptions = (params: z.input<typeof GetFileMetasSchema>) =>\r\n queryOptions({\r\n queryKey: [QUERY_KEY, \"meta\", params.appName, params.subId],\r\n queryFn: () => getFileMetasRpc({ data: params }),\r\n ...baseOptions,\r\n });\r\n\r\nexport const fileThumbnailQueryOptions = (params: z.input<typeof FileSchema>) =>\r\n queryOptions({\r\n queryKey: [QUERY_KEY, \"thumbnail\", params.appName, params.id],\r\n queryFn: async () => responseToObjectUrl(await getFileThumbnailRpc({ data: params })),\r\n enabled: !!params.id,\r\n ...baseOptions,\r\n });\r\n\r\nexport const fileQueryOptions = (params: z.input<typeof FileSchema>) =>\r\n queryOptions({\r\n queryKey: [QUERY_KEY, params.appName, params.id],\r\n queryFn: async () => responseToObjectUrl(await downloadFileRpc({ data: params })),\r\n enabled: !!params.id,\r\n ...baseOptions,\r\n });\r\n\r\nexport const downloadFileMutationOptions = () =>\r\n mutationOptions({\r\n mutationFn: async (\r\n data: z.input<typeof FileSchema> & { fileName: string; fileExtension: string },\r\n ) => {\r\n const response = await downloadFileRpc({ data });\r\n saveBlob(await response.blob(), `${data.fileName}.${data.fileExtension}`);\r\n },\r\n });\r\n\r\nexport const openFileMutationOptions = ({ target }: { target: { current: Window | null } }) =>\r\n mutationOptions<string, Error, z.input<typeof FileSchema>>({\r\n mutationFn: async (data) => responseToObjectUrl(await getFileRpc({ data })),\r\n onSuccess: (source) => {\r\n const popup = target.current;\r\n target.current = null;\r\n\r\n if (popup) {\r\n popup.opener = null;\r\n popup.location.href = source;\r\n } else {\r\n window.open(source, \"_blank\");\r\n }\r\n },\r\n onError: () => {\r\n target.current?.close();\r\n target.current = null;\r\n },\r\n });\r\n\r\nexport const updateFileMetaMutationOptions = ({ queryClient }: QueryClientParam) =>\r\n mutationOptions({\r\n mutationFn: (data: z.input<typeof UpdateFileMetaSchema>) => updateFileMetaRpc({ data }),\r\n onSettled: () => queryClient.invalidateQueries({ queryKey: [QUERY_KEY, \"meta\"], exact: false }),\r\n });\r\n\r\nexport const deleteFileMutationOptions = ({ queryClient }: QueryClientParam) =>\r\n mutationOptions({\r\n mutationFn: (data: z.input<typeof FileSchema>) => deleteFileRpc({ data }),\r\n onSettled: () => queryClient.invalidateQueries({ queryKey: [QUERY_KEY, \"meta\"], exact: false }),\r\n });\r\n\r\nexport const batchDeleteFilesMutationOptions = ({ queryClient }: QueryClientParam) =>\r\n mutationOptions({\r\n mutationFn: (data: z.input<typeof GetFileMetasSchema>) => batchDeleteFilesRpc({ data }),\r\n onSettled: () => queryClient.invalidateQueries({ queryKey: [QUERY_KEY, \"meta\"], exact: false }),\r\n });\r\n\r\nexport const uploadFileMutationOptions = ({ queryClient }: QueryClientParam) =>\r\n mutationOptions({\r\n mutationFn: async ({\r\n id = uuidv7(),\r\n appName,\r\n subId,\r\n file,\r\n setProgress,\r\n }: z.input<typeof UploadFileMetaSchema> & {\r\n setProgress?: (progress: number) => void;\r\n }): Promise<UploadFileResult> => {\r\n const { token, endpoint } = await getFileUploadToken();\r\n\r\n await new Promise<void>((resolve, reject) => {\r\n const upload = new Upload(file, {\r\n endpoint,\r\n chunkSize: 1_048_576,\r\n metadata: {\r\n id,\r\n appName: appName,\r\n subId: subId,\r\n filename: file.name,\r\n filetype: file.type,\r\n },\r\n headers: { Authorization: `Bearer ${token}` },\r\n onProgress: (bytesUploaded, bytesTotal) =>\r\n setProgress?.((bytesUploaded / bytesTotal) * 100),\r\n onError: reject,\r\n onSuccess: () => resolve(),\r\n });\r\n upload.start();\r\n });\r\n\r\n return { id, appName, subId, fileName: file.name };\r\n },\r\n onSuccess: (result) =>\r\n queryClient.invalidateQueries({\r\n queryKey: [QUERY_KEY, \"meta\", result.appName, result.subId],\r\n exact: false,\r\n }),\r\n });\r\n"],"mappings":";;;;;;;;;AAMA,MAAa,qBAAqB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CAChE,WAAW,CAAC,yBAAyB,EAAE,UAAU,KAAK,CAAC,CAAC,CAAC,CAAC,CAC1D,QAAQ,OAAO,EAAE,eAAe;CAC/B,OAAO,QAAQ,OAAO,MAAM,eAAe,MAAM,IAAI,MAAM,YAAY,MAAM;CAC7E,UAAU,GAAG,UAAU,cAAa;AACtC,EAAE;;;ACUJ,MAAM,YAAY;AAClB,MAAM,OAAO;AAEb,MAAM,kBAAkB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CACtD,UAAU,kBAAkB,CAAC,CAC7B,SAAS,EAAE,WAAW,aAAa,EAAE,KAAK,CAAC,CAAC;AAE/C,MAAM,sBAAsB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CAC1D,UAAU,UAAU,CAAC,CACrB,SAAS,EAAE,WAAW,iBAAiB,EAAE,KAAK,CAAC,CAAC;AAEnD,MAAM,aAAa,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CACjD,UAAU,UAAU,CAAC,CACrB,SAAS,EAAE,WAAW,QAAQ,EAAE,KAAK,CAAC,CAAC;AAE1C,MAAM,kBAAkB,eAAe,EAAE,QAAQ,MAAM,CAAC,CAAC,CACtD,UAAU,UAAU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;AAChG,CAAC;AAEH,MAAa,6BAA6B,EAAE,kBAC1C,gBAAgB;CACd,YAAY,OAAO,EACjB,KAAK,OAAO,GACZ,SACA,OACA,MACA,kBAG+B;EAC/B,MAAM,EAAE,OAAO,aAAa,MAAM,mBAAmB;EAErD,MAAM,IAAI,SAAe,SAAS,WAAW;GAiB3C,IAhBmB,OAAO,MAAM;IAC9B;IACA,WAAW;IACX,UAAU;KACR;KACS;KACF;KACP,UAAU,KAAK;KACf,UAAU,KAAK;IACjB;IACA,SAAS,EAAE,eAAe,UAAU,QAAQ;IAC5C,aAAa,eAAe,eAC1B,cAAe,gBAAgB,aAAc,GAAG;IAClD,SAAS;IACT,iBAAiB,QAAQ;GAC3B,CACA,CAAM,CAAC,MAAM;EACf,CAAC;EAED,OAAO;GAAE;GAAI;GAAS;GAAO,UAAU,KAAK;EAAK;CACnD;CACA,YAAY,WACV,YAAY,kBAAkB;EAC5B,UAAU;GAAC;GAAW;GAAQ,OAAO;GAAS,OAAO;EAAK;EAC1D,OAAO;CACT,CAAC;AACL,CAAC"}
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { scopes } from "virtual:wcz-layout";
|
|
2
|
-
import { createServerOnlyFn } from "@tanstack/react-start";
|
|
3
|
-
//#region src/lib/auth/msalServer.ts
|
|
4
|
-
let ccaInstance = null;
|
|
5
|
-
const getCCA = async () => {
|
|
6
|
-
if (!ccaInstance) {
|
|
7
|
-
const { createConfidentialClient } = await import("./entra-CJSyeQsx.mjs");
|
|
8
|
-
ccaInstance = createConfidentialClient();
|
|
9
|
-
}
|
|
10
|
-
return ccaInstance;
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* Client Credentials flow: Get app-only token (no user context)
|
|
14
|
-
* Use when: Background jobs, scheduled tasks, service-to-service calls
|
|
15
|
-
*/
|
|
16
|
-
const getAppToken = createServerOnlyFn(async (scopeKey) => {
|
|
17
|
-
const cca = await getCCA();
|
|
18
|
-
const defaultScopes = scopes[scopeKey].map((scope) => {
|
|
19
|
-
const lastSlash = scope.lastIndexOf("/");
|
|
20
|
-
return `${scope.substring(0, lastSlash)}/.default`;
|
|
21
|
-
});
|
|
22
|
-
const uniqueScopes = [...new Set(defaultScopes)];
|
|
23
|
-
const result = await cca.acquireTokenByClientCredential({ scopes: uniqueScopes });
|
|
24
|
-
if (!result) throw new Error("Failed to acquire app token");
|
|
25
|
-
return result.accessToken;
|
|
26
|
-
});
|
|
27
|
-
//#endregion
|
|
28
|
-
export { getAppToken as t };
|
|
29
|
-
|
|
30
|
-
//# sourceMappingURL=msalServer-DLwA7_ta.mjs.map
|