openadminjs 0.2.0 → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/README.md +106 -151
  2. package/dist/adapt-package-manager.js +4 -1
  3. package/dist/create-project.d.ts +46 -0
  4. package/dist/create-project.js +417 -150
  5. package/dist/doctor.d.ts +13 -0
  6. package/dist/doctor.js +35 -6
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +257 -39
  9. package/dist/render-schema.d.ts +0 -17
  10. package/dist/render-schema.js +25 -29
  11. package/dist/resource-slug.d.ts +1 -0
  12. package/dist/resource-slug.js +7 -0
  13. package/dist/runtime-mode.d.ts +16 -0
  14. package/dist/runtime-mode.js +138 -0
  15. package/dist/upgrade.d.ts +10 -0
  16. package/dist/upgrade.js +133 -0
  17. package/package.json +14 -11
  18. package/template/.dockerignore +15 -0
  19. package/template/.env.production.example +5 -0
  20. package/template/Dockerfile +12 -0
  21. package/template/README.md +4 -3
  22. package/template/apps/admin/app/api/auth/login/route.ts +9 -9
  23. package/template/apps/admin/app/api/auth/logout/route.ts +11 -3
  24. package/template/apps/admin/app/api/auth/oidc/callback/route.ts +19 -0
  25. package/template/apps/admin/app/api/auth/oidc/start/route.ts +11 -0
  26. package/template/apps/admin/app/api/auth/oidc/status/route.ts +6 -0
  27. package/template/apps/admin/app/api/auth/refresh/route.ts +18 -11
  28. package/template/apps/admin/app/api/backend/[...path]/route.ts +48 -0
  29. package/template/apps/admin/app/api-tokens/page.tsx +39 -39
  30. package/template/apps/admin/app/assistant/page.tsx +11 -0
  31. package/template/apps/admin/app/dashboard/page.tsx +45 -462
  32. package/template/apps/admin/app/globals.css +52 -16
  33. package/template/apps/admin/app/layout.tsx +1 -1
  34. package/template/apps/admin/app/login/page.tsx +13 -145
  35. package/template/apps/admin/app/plugins/page.tsx +16 -402
  36. package/template/apps/admin/app/profile/page.tsx +5 -2
  37. package/template/apps/admin/app/settings/page.tsx +14 -265
  38. package/template/apps/admin/components/ai-assistant-widget.tsx +3 -6
  39. package/template/apps/admin/components/app-shell.tsx +25 -373
  40. package/template/apps/admin/components/auth-guard.tsx +8 -28
  41. package/template/apps/admin/components/logo.tsx +1 -30
  42. package/template/apps/admin/components/resource-form.tsx +3 -3
  43. package/template/apps/admin/components/resource-table.tsx +12 -8
  44. package/template/apps/admin/lib/api.ts +45 -107
  45. package/template/apps/admin/lib/resource-table-prefs.ts +1 -57
  46. package/template/apps/admin/lib/server-api.ts +7 -0
  47. package/template/apps/admin/lib/tokens.ts +9 -81
  48. package/template/apps/admin/middleware.ts +9 -50
  49. package/template/apps/admin/next.config.mjs +4 -0
  50. package/template/apps/admin/package.json +2 -1
  51. package/template/apps/admin/public/brand/favicon.svg +4 -1
  52. package/template/apps/admin/tailwind.config.ts +9 -8
  53. package/template/apps/api/package.json +10 -6
  54. package/template/apps/api/src/access/catalog.ts +4 -0
  55. package/template/apps/api/src/admin/admin-ai.controller.ts +15 -125
  56. package/template/apps/api/src/admin/admin-analytics.service.ts +16 -148
  57. package/template/apps/api/src/admin/admin-logs.controller.ts +4 -1
  58. package/template/apps/api/src/admin/admin-plugins.controller.ts +8 -8
  59. package/template/apps/api/src/admin/admin-plugins.service.ts +15 -259
  60. package/template/apps/api/src/admin/admin-resource.service.ts +105 -254
  61. package/template/apps/api/src/admin/admin.controller.ts +17 -4
  62. package/template/apps/api/src/admin/admin.module.ts +2 -2
  63. package/template/apps/api/src/admin/resource-policy.ts +1 -0
  64. package/template/apps/api/src/admin/resource-query.ts +1 -0
  65. package/template/apps/api/src/admin/safe-ai.service.ts +43 -0
  66. package/template/apps/api/src/admin/validate-resource-payload.ts +2 -0
  67. package/template/apps/api/src/auth/auth.controller.ts +4 -2
  68. package/template/apps/api/src/auth/auth.service.ts +68 -83
  69. package/template/apps/api/src/auth/sso-oidc.controller.ts +12 -74
  70. package/template/apps/api/src/auth/sso-oidc.service.ts +51 -268
  71. package/template/apps/api/src/common/api-exception.filter.ts +1 -0
  72. package/template/apps/api/src/common/auth.guard.ts +66 -39
  73. package/template/apps/api/src/common/json-field-codec.ts +12 -13
  74. package/template/apps/api/src/common/prisma.service.ts +9 -17
  75. package/template/apps/api/src/common/request-logging.interceptor.ts +8 -3
  76. package/template/apps/api/src/graphql/graphql.module.ts +5 -4
  77. package/template/apps/api/src/health/health.controller.ts +6 -0
  78. package/template/apps/api/src/main.ts +11 -2
  79. package/template/apps/api/src/plugins/plugin-loader.ts +5 -3
  80. package/template/apps/api/src/resources/commerce.resource.ts +3 -34
  81. package/template/apps/api/src/resources/operations.resource.ts +1 -0
  82. package/template/apps/api/src/store/payment/payment.controller.ts +15 -92
  83. package/template/apps/api/src/store/payment/payment.module.ts +2 -3
  84. package/template/apps/api/src/store/payment/payment.service.ts +121 -227
  85. package/template/apps/api/webpack.config.cjs +2 -1
  86. package/template/apps/web/next.config.mjs +4 -0
  87. package/template/apps/web/public/brand/favicon.svg +4 -1
  88. package/template/compose.yaml +56 -0
  89. package/template/examples/crm-admin/README.md +31 -0
  90. package/template/examples/crm-admin/package.json +17 -0
  91. package/template/examples/crm-admin/prisma/models.fragment.prisma +50 -0
  92. package/template/examples/crm-admin/src/index.ts +7 -0
  93. package/template/examples/crm-admin/src/resources/activities.resource.ts +29 -0
  94. package/template/examples/crm-admin/src/resources/companies.resource.ts +21 -0
  95. package/template/examples/crm-admin/src/resources/contacts.resource.ts +24 -0
  96. package/template/examples/crm-admin/src/resources/deals.resource.ts +30 -0
  97. package/template/examples/crm-admin/tsconfig.json +7 -0
  98. package/template/package.json +6 -1
  99. package/template/packages/admin-client/package.json +18 -0
  100. package/template/packages/admin-client/src/contracts.ts +29 -0
  101. package/template/packages/admin-client/src/index.ts +2 -0
  102. package/template/packages/admin-client/src/preferences.ts +57 -0
  103. package/template/packages/admin-client/tsconfig.json +12 -0
  104. package/template/packages/auth/package.json +1 -1
  105. package/template/packages/brand/site/assets/brand/favicon.svg +4 -1
  106. package/template/packages/brand/src/generate-assets.mjs +17 -186
  107. package/template/packages/core/package.json +1 -1
  108. package/template/packages/mail/package.json +1 -1
  109. package/template/packages/nest/package.json +22 -0
  110. package/template/packages/nest/src/api-exception.filter.ts +23 -0
  111. package/template/packages/nest/src/index.ts +3 -0
  112. package/template/packages/nest/src/resource-policy.ts +64 -0
  113. package/template/packages/nest/src/resource-query.ts +103 -0
  114. package/template/packages/nest/tsconfig.json +12 -0
  115. package/template/packages/notifications/package.json +1 -1
  116. package/template/packages/payments/package.json +1 -1
  117. package/template/packages/permissions/package.json +1 -1
  118. package/template/packages/permissions/src/index.ts +2 -2
  119. package/template/packages/plugin-sdk/package.json +1 -1
  120. package/template/packages/plugin-sdk/src/index.ts +2 -2
  121. package/template/packages/prisma/package.json +21 -0
  122. package/template/packages/prisma/schema/ai.prisma +36 -0
  123. package/template/packages/prisma/schema/audit.prisma +13 -0
  124. package/template/packages/prisma/schema/commerce.prisma +79 -0
  125. package/template/packages/prisma/schema/content.prisma +27 -0
  126. package/template/packages/prisma/schema/core.prisma +106 -0
  127. package/template/packages/prisma/schema/header.prisma +8 -0
  128. package/template/packages/prisma/schema/jobs.prisma +9 -0
  129. package/template/packages/prisma/schema/media.prisma +9 -0
  130. package/template/packages/prisma/schema/modules.json +47 -0
  131. package/template/packages/prisma/schema/notifications.prisma +9 -0
  132. package/template/packages/prisma/schema/settings.prisma +8 -0
  133. package/template/packages/prisma/schema/tokens.prisma +10 -0
  134. package/template/packages/prisma/src/index.d.ts +12 -0
  135. package/template/packages/prisma/src/index.mjs +138 -0
  136. package/template/packages/queue/package.json +1 -1
  137. package/template/packages/resource/package.json +1 -1
  138. package/template/packages/resource/src/index.ts +1 -0
  139. package/template/packages/storage/package.json +1 -1
  140. package/template/packages/storage/src/index.ts +37 -0
  141. package/template/prisma/migrations/20261126130000_add_sessions/migration.sql +26 -0
  142. package/template/prisma/migrations/20261126140000_api_token_hash/migration.sql +3 -0
  143. package/template/prisma/migrations/20261126150000_payment_idempotency/migration.sql +6 -0
  144. package/template/prisma/schema.prisma +82 -54
  145. package/template/prisma/seed.ts +14 -38
  146. package/template/runtime-versions.json +15 -0
  147. package/template/scripts/db-init.mjs +33 -0
  148. package/template/scripts/install-crm.mjs +50 -0
  149. package/template/scripts/migrate-existing.mjs +65 -0
  150. package/template/scripts/schema.mjs +48 -0
  151. package/template/tsconfig.base.json +23 -5
  152. package/LICENSE +0 -21
  153. package/dist/adapt-package-manager.test.d.ts +0 -1
  154. package/dist/adapt-package-manager.test.js +0 -76
  155. package/dist/cli.e2e.test.d.ts +0 -1
  156. package/dist/cli.e2e.test.js +0 -87
  157. package/dist/create-project.test.d.ts +0 -1
  158. package/dist/create-project.test.js +0 -275
  159. package/dist/database-providers.integration.test.d.ts +0 -1
  160. package/dist/database-providers.integration.test.js +0 -64
  161. package/dist/db-commands.test.d.ts +0 -1
  162. package/dist/db-commands.test.js +0 -27
  163. package/dist/doctor.test.d.ts +0 -1
  164. package/dist/doctor.test.js +0 -102
  165. package/dist/index.test.d.ts +0 -1
  166. package/dist/index.test.js +0 -11
  167. package/dist/render-schema.test.d.ts +0 -1
  168. package/dist/render-schema.test.js +0 -57
  169. package/dist/resource-slug.test.d.ts +0 -1
  170. package/dist/resource-slug.test.js +0 -9
  171. package/dist/secrets.test.d.ts +0 -1
  172. package/dist/secrets.test.js +0 -36
  173. package/dist/security.test.d.ts +0 -1
  174. package/dist/security.test.js +0 -54
  175. package/dist/validate-name.test.d.ts +0 -1
  176. package/dist/validate-name.test.js +0 -63
  177. package/template/apps/admin/.storybook/main.ts +0 -12
  178. package/template/apps/admin/.storybook/preview.ts +0 -10
  179. package/template/apps/admin/app/login/page.test.tsx +0 -18
  180. package/template/apps/admin/components/auth-guard.test.tsx +0 -55
  181. package/template/apps/admin/components/logo.stories.tsx +0 -24
  182. package/template/apps/admin/lib/api.test.ts +0 -118
  183. package/template/apps/admin/lib/auth-flow.e2e.test.ts +0 -79
  184. package/template/apps/admin/vitest.config.ts +0 -7
  185. package/template/apps/api/src/access/derive-permissions.test.ts +0 -26
  186. package/template/apps/api/src/admin/admin-resource.service.test.ts +0 -118
  187. package/template/apps/api/src/admin/validate-resource-payload.test.ts +0 -44
  188. package/template/apps/api/src/app.module.test.ts +0 -12
  189. package/template/apps/api/src/auth/auth.service.test.ts +0 -78
  190. package/template/apps/api/src/auth/sso-oidc.service.test.ts +0 -84
  191. package/template/apps/api/src/common/auth.guard.test.ts +0 -62
  192. package/template/apps/api/src/common/casl-ability.factory.test.ts +0 -33
  193. package/template/apps/api/src/common/json-field-codec.test.ts +0 -76
  194. package/template/apps/api/src/common/prisma.service.test.ts +0 -19
  195. package/template/apps/api/src/common/request-logging.interceptor.test.ts +0 -39
  196. package/template/apps/api/src/graphql/admin-resources.resolver.test.ts +0 -45
  197. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +0 -44
  198. package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +0 -26
  199. package/template/apps/api/src/graphql/graphql-schema.test.ts +0 -26
  200. package/template/apps/api/src/plugins/manifest.schema.test.ts +0 -36
  201. package/template/apps/api/src/plugins/plugin-runtime.test.ts +0 -24
  202. package/template/apps/api/src/queue/queue.service.test.ts +0 -33
  203. package/template/apps/api/src/resources/resource-hooks.registry.test.ts +0 -72
  204. package/template/apps/api/vitest.config.ts +0 -21
  205. package/template/apps/web/lib/seo.test.ts +0 -41
  206. package/template/apps/web/vitest.config.ts +0 -19
  207. package/template/packages/auth/src/index.test.ts +0 -10
  208. package/template/packages/brand/src/index.test.ts +0 -9
  209. package/template/packages/core/src/index.test.ts +0 -27
  210. package/template/packages/core/vitest.config.ts +0 -9
  211. package/template/packages/mail/src/index.test.ts +0 -23
  212. package/template/packages/notifications/src/index.test.ts +0 -9
  213. package/template/packages/permissions/src/blueprints.test.ts +0 -62
  214. package/template/packages/permissions/src/index.test.ts +0 -34
  215. package/template/packages/plugin-sdk/src/sdk.test.ts +0 -13
  216. package/template/packages/plugin-sdk/vitest.config.ts +0 -5
  217. package/template/packages/queue/src/index.test.ts +0 -12
  218. package/template/packages/resource/src/index.test.ts +0 -196
  219. package/template/packages/storage/src/index.test.ts +0 -10
@@ -0,0 +1,138 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, writeFileSync, mkdirSync, renameSync, rmSync, copyFileSync } from "node:fs";
2
+ import { resolve, join, dirname, relative } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ const sha = (data) => createHash("sha256").update(data).digest("hex");
5
+ const json = (path) => JSON.parse(readFileSync(path, "utf8"));
6
+ const write = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + "\n");
7
+ const localName = (name) => name.slice("@openadminjs/".length);
8
+ export function migrateRuntime(root, template, flags = {}) {
9
+ const versions = json(join(template, "runtime-versions.json"));
10
+ const known = Object.keys(versions);
11
+ if (known.some(n => !/^@openadminjs\/[a-z-]+$/.test(n) || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/.test(versions[n])))
12
+ throw Error("Invalid bundled runtime versions");
13
+ const backup = join(root, ".openadminjs-runtime-backup"), archiveDir = join(root, ".openadminjs-runtime");
14
+ if (existsSync(backup) || existsSync(archiveDir))
15
+ throw Error("Runtime migration already performed; preserve or restore the backup before retrying");
16
+ const rootPkg = json(join(root, "package.json")), tsPath = join(root, "tsconfig.base.json"), ts = json(tsPath);
17
+ const conflicts = [];
18
+ const packageDirs = [];
19
+ function compare(local, expected) {
20
+ if (!existsSync(local) || lstatSync(local).isSymbolicLink()) {
21
+ conflicts.push(relative(root, local));
22
+ return;
23
+ }
24
+ for (const e of readdirSync(local, { withFileTypes: true })) {
25
+ if (["dist", "node_modules", "coverage", ".turbo"].includes(e.name) || e.name.endsWith(".tsbuildinfo"))
26
+ continue;
27
+ const a = join(local, e.name), b = join(expected, e.name);
28
+ if (e.isSymbolicLink()) {
29
+ conflicts.push(relative(root, a));
30
+ continue;
31
+ }
32
+ if (e.isDirectory()) {
33
+ if (!existsSync(b))
34
+ conflicts.push(relative(root, a));
35
+ else
36
+ compare(a, b);
37
+ }
38
+ else if (!existsSync(b) || sha(readFileSync(a)) !== sha(readFileSync(b)))
39
+ conflicts.push(relative(root, a));
40
+ }
41
+ }
42
+ for (const name of known) {
43
+ const local = join(root, "packages", localName(name));
44
+ if (existsSync(local)) {
45
+ if (lstatSync(local).isSymbolicLink())
46
+ throw Error("Symlinked runtime directory");
47
+ packageDirs.push(local);
48
+ if (!flags.initial)
49
+ compare(local, join(template, "packages", localName(name)));
50
+ }
51
+ }
52
+ if (!packageDirs.length)
53
+ throw Error("No copied runtime source directories found");
54
+ const manifests = [join(root, "package.json"), ...["apps", "examples"].flatMap(dir => existsSync(join(root, dir)) ? readdirSync(join(root, dir), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => join(root, dir, e.name, "package.json")).filter(existsSync) : [])];
55
+ const updates = new Map();
56
+ for (const file of manifests) {
57
+ const p = json(file);
58
+ for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
59
+ if (!p[section])
60
+ continue;
61
+ for (const name of known)
62
+ if (name in p[section])
63
+ p[section][name] = versions[name];
64
+ }
65
+ if (file === manifests[0]) {
66
+ p.dependencies = { ...p.dependencies, ...versions };
67
+ // Packages are pinned independently; no workspace wildcard for these dependencies.
68
+ if (flags.archives) {
69
+ if (!existsSync(join(root, "pnpm-workspace.yaml")))
70
+ throw Error("Candidate archive mode requires pnpm");
71
+ p.pnpm = { ...p.pnpm, overrides: { ...p.pnpm?.overrides, ...Object.fromEntries(known.map(name => [name, "file:./.openadminjs-runtime/" + localName(name) + ".tgz"])) } };
72
+ }
73
+ }
74
+ updates.set(file, p);
75
+ }
76
+ if (ts.compilerOptions?.paths)
77
+ for (const name of known)
78
+ delete ts.compilerOptions.paths[name];
79
+ updates.set(tsPath, ts);
80
+ const files = [];
81
+ if (flags.archives) {
82
+ const dir = resolve(flags.archives), manifest = json(join(dir, "runtime-manifest.json"));
83
+ for (const name of known) {
84
+ const entry = manifest[name];
85
+ if (!entry || entry.version !== versions[name] || entry.archive !== name.replace(/^@/, "").replace("/", "-") + "-" + entry.version + ".tgz" || !/^\w[\w.-]*\.tgz$/.test(entry.archive))
86
+ throw Error("Missing/mismatched archive " + name);
87
+ const source = join(dir, entry.archive);
88
+ if (sha(readFileSync(source)) !== entry.sha256)
89
+ throw Error("Archive checksum mismatch " + name);
90
+ files.push({ source, target: join(archiveDir, localName(name) + ".tgz") });
91
+ }
92
+ }
93
+ const result = { mode: flags.archives ? "archives" : "registry", versions, conflicts, plannedManifests: [...updates.keys()].map(p => relative(root, p)), backup: relative(root, backup), applied: false };
94
+ if (!flags.apply || conflicts.length && !flags.acceptLocalRuntime)
95
+ return result;
96
+ // All paths are constrained to known bundled package names. No DB or dependency installation.
97
+ mkdirSync(backup, { mode: 0o700 });
98
+ const saved = [], moved = [];
99
+ try {
100
+ for (const [file, data] of updates) {
101
+ const content = readFileSync(file);
102
+ const dest = join(backup, "manifests", relative(root, file));
103
+ mkdirSync(dirname(dest), { recursive: true });
104
+ writeFileSync(dest, content);
105
+ saved.push({ file, content });
106
+ write(file, data);
107
+ }
108
+ for (const from of packageDirs) {
109
+ const to = join(backup, "sources", relative(root, from));
110
+ mkdirSync(dirname(to), { recursive: true });
111
+ renameSync(from, to);
112
+ moved.push({ from, to });
113
+ }
114
+ if (files.length) {
115
+ mkdirSync(archiveDir);
116
+ for (const f of files)
117
+ copyFileSync(f.source, f.target);
118
+ }
119
+ write(join(backup, "migration.json"), { ...result, applied: true });
120
+ // Keep this backup out of Git and avoid accidental workspace discovery.
121
+ const ignore = join(root, ".gitignore");
122
+ if (existsSync(ignore) && !readFileSync(ignore, "utf8").includes(".openadminjs-runtime-backup/"))
123
+ writeFileSync(ignore, readFileSync(ignore, "utf8") + "\n.openadminjs-runtime-backup/\n");
124
+ if (flags.initial)
125
+ rmSync(backup, { recursive: true, force: true });
126
+ result.applied = true;
127
+ return result;
128
+ }
129
+ catch (e) {
130
+ for (const { from, to } of moved.reverse())
131
+ renameSync(to, from);
132
+ for (const { file, content } of saved)
133
+ writeFileSync(file, content);
134
+ rmSync(archiveDir, { recursive: true, force: true });
135
+ rmSync(backup, { recursive: true, force: true });
136
+ throw e;
137
+ }
138
+ }
@@ -0,0 +1,10 @@
1
+ type Change = {
2
+ path: string;
3
+ status: "update" | "conflict" | "manual" | "restored";
4
+ };
5
+ export declare function writeManagedBaseline(root: string): void;
6
+ export declare function upgradeManaged(root: string, template: string, flags?: {
7
+ apply?: boolean;
8
+ rollback?: boolean;
9
+ }): Change[];
10
+ export {};
@@ -0,0 +1,133 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join, dirname, resolve, relative } from "node:path";
4
+ const BASELINE = ".openadminjs-managed.json", BACKUP = ".openadminjs-patch-backup";
5
+ const roots = ["packages/resource/src", "packages/core/src", "packages/permissions/src", "packages/plugin-sdk/src", "packages/storage/src", "apps/admin/components", "apps/admin/lib"];
6
+ function permitted(path) {
7
+ return roots.some(root => path.startsWith(root + "/")) && /\.(ts|tsx|css)$/.test(path) && !/\.(test|spec|stories)\.[^.]+$/.test(path) && !path.split("/").some(x => !x || x === "." || x === ".." || x.startsWith("."));
8
+ }
9
+ function safe(root, path) {
10
+ if (!permitted(path))
11
+ throw Error("Not a managed file: " + path);
12
+ let p = resolve(root);
13
+ for (const segment of path.split("/")) {
14
+ p = join(p, segment);
15
+ if (existsSync(p) && lstatSync(p).isSymbolicLink())
16
+ throw Error("Symlink not allowed: " + path);
17
+ }
18
+ return p;
19
+ }
20
+ function digest(data) { return createHash("sha256").update(data).digest("hex"); }
21
+ function hashes(root) {
22
+ const out = {};
23
+ function walk(dir) {
24
+ if (!existsSync(dir))
25
+ return;
26
+ if (lstatSync(dir).isSymbolicLink())
27
+ throw Error("Managed root cannot be a symlink");
28
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
29
+ if (e.isSymbolicLink())
30
+ throw Error("Symlink in managed directory");
31
+ const p = join(dir, e.name);
32
+ if (e.isDirectory()) {
33
+ walk(p);
34
+ continue;
35
+ }
36
+ const path = relative(root, p).replaceAll("\\", "/");
37
+ if (e.isFile() && permitted(path))
38
+ out[path] = digest(readFileSync(safe(root, path)));
39
+ }
40
+ }
41
+ for (const dir of roots)
42
+ walk(join(root, dir));
43
+ return out;
44
+ }
45
+ function readManifest(path) {
46
+ if (lstatSync(path).isSymbolicLink())
47
+ throw Error("Symlinked manifest");
48
+ const data = JSON.parse(readFileSync(path, "utf8"));
49
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.entries(data).some(([p, h]) => !permitted(p) || typeof h !== "string" || !/^[a-f0-9]{64}$/.test(h)))
50
+ throw Error("Invalid managed baseline");
51
+ return data;
52
+ }
53
+ function atomic(path, bytes) {
54
+ const temporary = path + ".oajs-" + randomBytes(8).toString("hex");
55
+ writeFileSync(temporary, bytes, { flag: "wx", mode: 0o600 });
56
+ try {
57
+ renameSync(temporary, path);
58
+ }
59
+ catch (e) {
60
+ rmSync(temporary, { force: true });
61
+ throw e;
62
+ }
63
+ }
64
+ export function writeManagedBaseline(root) {
65
+ atomic(join(root, BASELINE), JSON.stringify(hashes(root), null, 2) + "\n");
66
+ }
67
+ export function upgradeManaged(root, template, flags = {}) {
68
+ if (flags.apply && flags.rollback)
69
+ throw Error("Choose apply or rollback");
70
+ const manifestPath = join(root, BASELINE), backup = join(root, BACKUP);
71
+ if (!existsSync(manifestPath))
72
+ throw Error("No baseline: use a manual reviewed upgrade for this project");
73
+ const baseline = readManifest(manifestPath);
74
+ if (flags.rollback) {
75
+ if (!existsSync(backup) || lstatSync(backup).isSymbolicLink())
76
+ throw Error("No valid patch backup");
77
+ const previous = readManifest(join(backup, "baseline.json")), applied = readManifest(join(backup, "applied.json"));
78
+ const entries = Object.keys(applied).filter(p => previous[p] !== applied[p]);
79
+ const changes = entries.map(p => ({ path: p, status: existsSync(safe(root, p)) && digest(readFileSync(safe(root, p))) === applied[p] ? "restored" : "conflict" }));
80
+ if (changes.some(p => p.status === "conflict"))
81
+ return changes;
82
+ const old = entries.map(p => { const content = readFileSync(safe(backup, p)); if (digest(content) !== previous[p])
83
+ throw Error("Backup checksum mismatch"); return { p, content }; });
84
+ for (const { p, content } of old)
85
+ atomic(safe(root, p), content);
86
+ atomic(manifestPath, JSON.stringify(previous, null, 2) + "\n");
87
+ rmSync(backup, { recursive: true, force: true });
88
+ return changes;
89
+ }
90
+ const candidate = hashes(template), plan = [];
91
+ for (const p of new Set([...Object.keys(baseline), ...Object.keys(candidate)])) {
92
+ if (candidate[p] === baseline[p])
93
+ continue;
94
+ if (!candidate[p] || !baseline[p]) {
95
+ plan.push({ path: p, status: "manual" });
96
+ continue;
97
+ }
98
+ const dest = safe(root, p);
99
+ plan.push({ path: p, status: existsSync(dest) && digest(readFileSync(dest)) === baseline[p] ? "update" : "conflict" });
100
+ }
101
+ if (!flags.apply || plan.some(p => p.status === "conflict" || p.status === "manual"))
102
+ return plan;
103
+ if (!plan.length)
104
+ return plan;
105
+ if (existsSync(backup))
106
+ throw Error("Previous patch backup exists; keep or roll it back before another patch");
107
+ mkdirSync(backup, { mode: 0o700 });
108
+ const next = { ...baseline };
109
+ const changed = [];
110
+ try {
111
+ for (const { path: p } of plan) {
112
+ const dest = safe(root, p), before = readFileSync(dest), after = readFileSync(safe(template, p));
113
+ if (digest(before) !== baseline[p] || digest(after) !== candidate[p])
114
+ throw Error("File changed during patch");
115
+ const saved = safe(backup, p);
116
+ mkdirSync(dirname(saved), { recursive: true });
117
+ writeFileSync(saved, before, { flag: "wx", mode: 0o600 });
118
+ changed.push({ p, before });
119
+ atomic(dest, after);
120
+ next[p] = candidate[p];
121
+ }
122
+ writeFileSync(join(backup, "baseline.json"), JSON.stringify(baseline), { mode: 0o600 });
123
+ writeFileSync(join(backup, "applied.json"), JSON.stringify(next), { mode: 0o600 });
124
+ atomic(manifestPath, JSON.stringify(next, null, 2) + "\n");
125
+ return plan;
126
+ }
127
+ catch (e) {
128
+ for (const { p, before } of changed.reverse())
129
+ atomic(safe(root, p), before);
130
+ rmSync(backup, { recursive: true, force: true });
131
+ throw e;
132
+ }
133
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openadminjs",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-rc.1",
4
4
  "description": "CLI scaffold generator for OpenAdminJS monorepos (NestJS, Prisma, Next.js). Not a runtime library — use npx openadminjs create.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -47,25 +47,28 @@
47
47
  },
48
48
  "files": [
49
49
  "dist",
50
+ "!dist/**/*.test.*",
51
+ "!dist/**/*.spec.*",
50
52
  "template",
51
53
  "README.md"
52
54
  ],
55
+ "scripts": {
56
+ "sync-template": "node ../../scripts/sync-template.mjs",
57
+ "prepack": "pnpm run build",
58
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && node ../../scripts/sync-template.mjs && tsc -p tsconfig.json && node ../../scripts/make-executable.mjs dist/index.js",
59
+ "lint": "tsc -p tsconfig.json --noEmit",
60
+ "typecheck": "tsc -p tsconfig.json --noEmit",
61
+ "test": "pnpm run sync-template && vitest run"
62
+ },
53
63
  "dependencies": {
54
64
  "@clack/prompts": "^0.8.2",
55
65
  "cac": "^6.7.14",
56
66
  "fs-extra": "^11.2.0",
57
- "picocolors": "^1.1.1"
67
+ "picocolors": "^1.1.1",
68
+ "typescript": "^5.7.2"
58
69
  },
59
70
  "devDependencies": {
60
71
  "@types/fs-extra": "^11.0.4",
61
- "typescript": "^5.7.2",
62
72
  "vitest": "^3.2.0"
63
- },
64
- "scripts": {
65
- "sync-template": "node ../../scripts/sync-template.mjs",
66
- "build": "node ../../scripts/sync-template.mjs && tsc -p tsconfig.json && node ../../scripts/make-executable.mjs dist/index.js",
67
- "lint": "tsc -p tsconfig.json --noEmit",
68
- "typecheck": "tsc -p tsconfig.json --noEmit",
69
- "test": "pnpm run sync-template && vitest run"
70
73
  }
71
- }
74
+ }
@@ -0,0 +1,15 @@
1
+ **/node_modules
2
+ **/dist
3
+ **/.next
4
+ **/.env
5
+ **/.env.*
6
+ !**/.env.example
7
+ .git
8
+ **/uploads
9
+ **/logs
10
+ **/*.db
11
+ **/*.sqlite
12
+ **/*.pem
13
+ **/*.key
14
+ **/*.tgz
15
+ **/coverage
@@ -0,0 +1,5 @@
1
+ # Copy to an ignored .env file. Use independent random secrets.
2
+ POSTGRES_PASSWORD=
3
+ DATABASE_URL=postgresql://openadmin:URL_ENCODED_PASSWORD@db:5432/openadmin
4
+ JWT_SECRET=
5
+ ADMIN_ORIGIN=https://admin.example.com
@@ -0,0 +1,12 @@
1
+ FROM node:22-bookworm-slim AS build
2
+ RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates && rm -rf /var/lib/apt/lists/* && corepack enable && corepack prepare pnpm@9.15.0 --activate
3
+ WORKDIR /app
4
+ COPY . .
5
+ RUN pnpm install --frozen-lockfile
6
+ ENV DATABASE_URL=postgresql://build:build@127.0.0.1:5432/build
7
+ RUN pnpm --filter @openadminjs/brand build && pnpm --filter @openadminjs/api... build && pnpm --filter @openadminjs/admin build
8
+ RUN mkdir -p /app/storage /app/apps/api/logs && chown -R node:node /app
9
+ USER node
10
+ ENV NODE_ENV=production
11
+ EXPOSE 3000 4000
12
+ CMD ["pnpm","--filter","@openadminjs/api","start"]
@@ -13,7 +13,7 @@ Generated by [OpenAdminJS](https://js-senpai.github.io/open-admin-js/).
13
13
 
14
14
  ```bash
15
15
  pnpm install
16
- pnpm db:migrate # required on first run (especially for MySQL/SQLite)
16
+ pnpm db:init # non-interactive provider-aware initialization
17
17
  pnpm db:seed
18
18
  pnpm dev
19
19
  ```
@@ -34,14 +34,15 @@ Real secrets live in **`apps/api/.env`** only. A tracked **`.env.example`** at t
34
34
  | MySQL | `mysql://USER:PASSWORD@localhost:3306/db` |
35
35
  | SQLite | `file:./dev.db` |
36
36
 
37
- On **SQLite**, `Json` columns are stored as `String` in the database; the API transparently JSON-encodes/decodes them at runtime.
37
+ New SQLite projects use native Prisma JSON. Existing legacy projects with JSON text columns need a reviewed schema upgrade.
38
38
 
39
39
  ## Useful commands
40
40
 
41
41
  | Command | Description |
42
42
  |---|---|
43
43
  | `pnpm dev` | Start API + admin in parallel |
44
- | `pnpm db:migrate` | Run Prisma migrations (`migrate dev`) |
44
+ | `pnpm db:init` | Initialize DB non-interactively; deploy reviewed history or safe development schema push |
45
+ | `pnpm db:migrate` | Development schema changes (provider-specific) |
45
46
  | `pnpm db:seed` | Seed database (creates superadmin) |
46
47
  | `pnpm db:studio` | Open Prisma Studio |
47
48
  | `pnpm build` | Build all workspaces |
@@ -1,27 +1,27 @@
1
1
  import { NextRequest, NextResponse } from "next/server";
2
2
  import { TOKEN_COOKIE_AT, TOKEN_COOKIE_RT } from "../../../../lib/tokens";
3
3
 
4
- const API_URL =
5
- typeof process !== "undefined" && process.env.NEXT_PUBLIC_API_URL
6
- ? process.env.NEXT_PUBLIC_API_URL
7
- : "http://localhost:4000";
4
+ import { API_URL, isSameOrigin } from "../../../../lib/server-api";
8
5
 
9
6
  const COOKIE_OPTS = {
10
7
  path: "/",
11
8
  maxAge: 60 * 60 * 24 * 7,
12
9
  sameSite: "lax" as const,
13
10
  secure: process.env.NODE_ENV === "production",
14
- httpOnly: false
11
+ httpOnly: true
15
12
  } as const;
16
13
 
17
14
  export async function POST(req: NextRequest) {
15
+ if (!isSameOrigin(req)) return NextResponse.json({ message: "Invalid origin" }, { status: 403 });
18
16
  const body = await req.json().catch(() => null);
19
17
  if (!body) return NextResponse.json({ message: "Invalid request body" }, { status: 400 });
20
18
 
21
19
  const upstream = await fetch(`${API_URL}/auth/login`, {
22
20
  method: "POST",
21
+ redirect: "error",
22
+ cache: "no-store",
23
23
  headers: { "content-type": "application/json" },
24
- body: JSON.stringify(body)
24
+ body: JSON.stringify({ email: body.email, password: body.password, realm: "admin" })
25
25
  }).catch(() => null);
26
26
 
27
27
  if (!upstream) {
@@ -40,12 +40,12 @@ export async function POST(req: NextRequest) {
40
40
  if (!upstream.ok || !data.accessToken || !data.refreshToken) {
41
41
  return NextResponse.json(
42
42
  { message: data.message ?? "Invalid credentials" },
43
- { status: upstream.status }
43
+ { status: upstream.ok ? 502 : upstream.status }
44
44
  );
45
45
  }
46
46
 
47
- const res = NextResponse.json({ ok: true });
48
- res.cookies.set(TOKEN_COOKIE_AT, data.accessToken, COOKIE_OPTS);
47
+ const res = NextResponse.json({ ok: true }, { headers: { "cache-control": "no-store" } });
48
+ res.cookies.set(TOKEN_COOKIE_AT, data.accessToken, { ...COOKIE_OPTS, maxAge: 900 });
49
49
  res.cookies.set(TOKEN_COOKIE_RT, data.refreshToken, COOKIE_OPTS);
50
50
  return res;
51
51
  }
@@ -1,9 +1,17 @@
1
- import { NextResponse } from "next/server";
1
+ import { NextRequest, NextResponse } from "next/server";
2
2
  import { TOKEN_COOKIE_AT, TOKEN_COOKIE_RT } from "../../../../lib/tokens";
3
+ import { API_URL, isSameOrigin } from "../../../../lib/server-api";
3
4
 
4
- const CLEAR_OPTS = { path: "/", maxAge: 0, sameSite: "lax" as const, httpOnly: false } as const;
5
+ const CLEAR_OPTS = { path: "/", maxAge: 0, sameSite: "lax" as const, httpOnly: true, secure: process.env.NODE_ENV === "production" } as const;
5
6
 
6
- export async function POST() {
7
+ export async function POST(req: NextRequest) {
8
+ if (!isSameOrigin(req)) return NextResponse.json({ message: "Invalid origin" }, { status: 403 });
9
+ const at = req.cookies.get(TOKEN_COOKIE_AT)?.value;
10
+ if (!at) return NextResponse.json({ message: "Session required" }, { status: 401 });
11
+ const upstream = await fetch(`${API_URL}/auth/logout`, {
12
+ method: "POST", headers: { authorization: `Bearer ${at}` }, cache: "no-store", redirect: "error"
13
+ }).catch(() => null);
14
+ if (!upstream?.ok) return NextResponse.json({ message: "Logout failed" }, { status: upstream?.status ?? 502 });
7
15
  const res = NextResponse.json({ ok: true });
8
16
  res.cookies.set(TOKEN_COOKIE_AT, "", CLEAR_OPTS);
9
17
  res.cookies.set(TOKEN_COOKIE_RT, "", CLEAR_OPTS);
@@ -0,0 +1,19 @@
1
+ import {NextRequest,NextResponse} from "next/server";
2
+ import {API_URL} from "../../../../../lib/server-api";
3
+ import {TOKEN_COOKIE_AT,TOKEN_COOKIE_RT} from "../../../../../lib/tokens";
4
+ export async function GET(req:NextRequest){
5
+ const origin=(process.env.ADMIN_ORIGIN||req.nextUrl.origin).split(",")[0]!.trim();
6
+ const cookieOpts={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax" as const,path:"/"};
7
+ const transaction=req.cookies.get("oajs_oidc")?.value;
8
+ const q=req.nextUrl.searchParams;
9
+ let data:{accessToken?:string;refreshToken?:string}={};
10
+ if(transaction&&q.getAll("code").length===1&&q.getAll("state").length===1&&!q.has("error")){
11
+ const r=await fetch(API_URL+"/auth/sso/oidc/exchange",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({transaction,code:q.get("code"),state:q.get("state"),iss:q.get("iss")||undefined}),cache:"no-store",redirect:"error"}).catch(()=>null);
12
+ if(r?.ok)data=await r.json().catch(()=>({}));
13
+ }
14
+ const ok=typeof data.accessToken==="string"&&typeof data.refreshToken==="string";
15
+ const res=NextResponse.redirect(new URL(ok?"/dashboard":"/login?sso_error=1",origin));
16
+ res.cookies.set("oajs_oidc","",{...cookieOpts,path:"/api/auth/oidc",maxAge:0});
17
+ if(ok){res.cookies.set(TOKEN_COOKIE_AT,data.accessToken!,{...cookieOpts,maxAge:900});res.cookies.set(TOKEN_COOKIE_RT,data.refreshToken!,{...cookieOpts,maxAge:604800});}
18
+ res.headers.set("cache-control","no-store");res.headers.set("referrer-policy","no-referrer");return res;
19
+ }
@@ -0,0 +1,11 @@
1
+ import {NextRequest,NextResponse} from "next/server";
2
+ import {API_URL} from "../../../../../lib/server-api";
3
+ export async function GET(req:NextRequest){
4
+ const origin=(process.env.ADMIN_ORIGIN||req.nextUrl.origin).split(",")[0]!.trim();
5
+ const failed=()=>NextResponse.redirect(new URL("/login?sso_error=1",origin));
6
+ const r=await fetch(API_URL+"/auth/sso/oidc/start",{method:"POST",cache:"no-store",redirect:"error"}).catch(()=>null);
7
+ if(!r?.ok)return failed();
8
+ const data=await r.json().catch(()=>({}));if(typeof data.authorizeUrl!=="string"||typeof data.transaction!=="string")return failed();
9
+ const url=new URL(data.authorizeUrl);if(url.protocol!=="https:")return failed();
10
+ const res=NextResponse.redirect(url);res.cookies.set("oajs_oidc",data.transaction,{path:"/api/auth/oidc",httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:600});res.headers.set("cache-control","no-store");return res;
11
+ }
@@ -0,0 +1,6 @@
1
+ import {NextResponse} from "next/server";
2
+ import {API_URL} from "../../../../../lib/server-api";
3
+ export async function GET(){
4
+ const r=await fetch(API_URL+"/auth/sso/oidc/status",{cache:"no-store",redirect:"error"}).catch(()=>null);
5
+ const data=r?.ok?await r.json().catch(()=>({})):{};return NextResponse.json({enabled:data.enabled===true},{headers:{"cache-control":"no-store"}});
6
+ }
@@ -1,30 +1,31 @@
1
1
  import { NextRequest, NextResponse } from "next/server";
2
2
  import { TOKEN_COOKIE_AT, TOKEN_COOKIE_RT } from "../../../../lib/tokens";
3
3
 
4
- const API_URL =
5
- typeof process !== "undefined" && process.env.NEXT_PUBLIC_API_URL
6
- ? process.env.NEXT_PUBLIC_API_URL
7
- : "http://localhost:4000";
4
+ import { API_URL, isSameOrigin } from "../../../../lib/server-api";
8
5
 
6
+ const noStore = { "cache-control": "no-store" };
9
7
  const COOKIE_OPTS = {
10
8
  path: "/",
11
9
  maxAge: 60 * 60 * 24 * 7,
12
10
  sameSite: "lax" as const,
13
11
  secure: process.env.NODE_ENV === "production",
14
- httpOnly: false
12
+ httpOnly: true
15
13
  } as const;
16
14
 
17
15
  export async function POST(req: NextRequest) {
16
+ if (!isSameOrigin(req)) return NextResponse.json({ message: "Invalid origin" }, { status: 403, headers: noStore });
18
17
  const rt = req.cookies.get(TOKEN_COOKIE_RT)?.value;
19
- if (!rt) return NextResponse.json({ message: "No refresh token" }, { status: 401 });
18
+ if (!rt) return NextResponse.json({ message: "No refresh token" }, { status: 401, headers: noStore });
20
19
 
21
20
  const upstream = await fetch(`${API_URL}/auth/refresh`, {
22
21
  method: "POST",
22
+ redirect: "error",
23
+ cache: "no-store",
23
24
  headers: { "content-type": "application/json" },
24
25
  body: JSON.stringify({ refreshToken: rt, realm: "admin" })
25
26
  }).catch(() => null);
26
27
 
27
- if (!upstream) return NextResponse.json({ message: "API unavailable" }, { status: 502 });
28
+ if (!upstream) return NextResponse.json({ message: "API unavailable" }, { status: 502, headers: noStore });
28
29
 
29
30
  const data = (await upstream.json().catch(() => ({}))) as {
30
31
  accessToken?: string;
@@ -32,15 +33,21 @@ export async function POST(req: NextRequest) {
32
33
  message?: string;
33
34
  };
34
35
 
35
- if (!upstream.ok || !data.accessToken || !data.refreshToken) {
36
- const res = NextResponse.json({ message: data.message ?? "Refresh failed" }, { status: 401 });
36
+ if (upstream.status === 401 || upstream.status === 403) {
37
+ const res = NextResponse.json({ message: "Session expired" }, { status: 401, headers: noStore });
37
38
  res.cookies.set(TOKEN_COOKIE_AT, "", { ...COOKIE_OPTS, maxAge: 0 });
38
39
  res.cookies.set(TOKEN_COOKIE_RT, "", { ...COOKIE_OPTS, maxAge: 0 });
39
40
  return res;
40
41
  }
41
42
 
42
- const res = NextResponse.json({ ok: true });
43
- res.cookies.set(TOKEN_COOKIE_AT, data.accessToken, COOKIE_OPTS);
43
+ if (!upstream.ok || typeof data?.accessToken !== "string" || !data.accessToken || typeof data.refreshToken !== "string" || !data.refreshToken) {
44
+ const headers = new Headers(noStore);
45
+ const retryAfter = upstream.headers.get("retry-after");
46
+ if (retryAfter) headers.set("retry-after", retryAfter);
47
+ return NextResponse.json({ message: "Session refresh temporarily unavailable" }, { status: upstream.status === 429 ? 429 : 502, headers });
48
+ }
49
+ const res = NextResponse.json({ ok: true }, { headers: noStore });
50
+ res.cookies.set(TOKEN_COOKIE_AT, data.accessToken, { ...COOKIE_OPTS, maxAge: 900 });
44
51
  res.cookies.set(TOKEN_COOKIE_RT, data.refreshToken, COOKIE_OPTS);
45
52
  return res;
46
53
  }
@@ -0,0 +1,48 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { API_URL, isSameOrigin } from "../../../../lib/server-api";
3
+ import { TOKEN_COOKIE_AT } from "../../../../lib/tokens";
4
+
5
+ type RouteContext = { params: Promise<{ path: string[] }> };
6
+ async function proxy(req: NextRequest, context: RouteContext) {
7
+ const { path } = await context.params;
8
+ if (!path.length || path.some(part => !/^[A-Za-z0-9_.@-]+$/.test(part) || part === "." || part === "..")) return NextResponse.json({ message: "Invalid path" }, { status: 400 });
9
+ const route = "/" + path.map(encodeURIComponent).join("/");
10
+ if (!(route.startsWith("/admin/") || route.startsWith("/jobs/") || route === "/auth/me" || route === "/auth/me/realms")) return NextResponse.json({ message: "Route not allowed" }, { status: 404 });
11
+ if (req.method !== "GET" && req.method !== "HEAD" && !isSameOrigin(req)) return NextResponse.json({ message: "Invalid origin" }, { status: 403 });
12
+ const token = req.cookies.get(TOKEN_COOKIE_AT)?.value;
13
+ if (!token) return NextResponse.json({ message: "Session required" }, { status: 401 });
14
+ const headers = new Headers({ authorization: `Bearer ${token}` });
15
+ const contentType = req.headers.get("content-type");
16
+ if (contentType) headers.set("content-type", contentType);
17
+ const init: RequestInit = { method: req.method, headers, cache: "no-store", redirect: "error" };
18
+ if (req.method !== "GET" && req.method !== "HEAD") {
19
+ const max = 15 * 1024 * 1024;
20
+ if (Number(req.headers.get("content-length") || 0) > max) return NextResponse.json({message:"Body too large"},{status:413});
21
+ const reader = req.body?.getReader();
22
+ if(reader) {
23
+ const chunks: Uint8Array[] = []; let total = 0;
24
+ for(;;) {
25
+ const {done,value}=await reader.read(); if(done) break;
26
+ total += value.byteLength;
27
+ if(total > max) {await reader.cancel();return NextResponse.json({message:"Body too large"},{status:413});}
28
+ chunks.push(value);
29
+ }
30
+ const data=new Uint8Array(total);let offset=0;
31
+ for(const chunk of chunks){data.set(chunk,offset);offset+=chunk.byteLength;}
32
+ init.body=data.buffer;
33
+ }
34
+ }
35
+ const response = await fetch(API_URL + route + req.nextUrl.search, init).catch(() => null);
36
+ if (!response) return NextResponse.json({ message: "API unavailable" }, { status: 502 });
37
+ const outgoing = new Headers({ "cache-control": "no-store", "x-content-type-options": "nosniff" });
38
+ for (const name of ["content-type", "content-disposition", "retry-after", "x-request-id"]) {
39
+ const value = response.headers.get(name);
40
+ if (value) outgoing.set(name, value);
41
+ }
42
+ return new NextResponse(response.body, { status: response.status, headers: outgoing });
43
+ }
44
+ export const GET = proxy;
45
+ export const POST = proxy;
46
+ export const PATCH = proxy;
47
+ export const PUT = proxy;
48
+ export const DELETE = proxy;