franchising 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +96 -2
  3. package/dist/accounts-B4bnTXUd.js +242 -0
  4. package/dist/accounts-B4bnTXUd.js.map +1 -0
  5. package/dist/accounts-TyMPSHM0.cjs +313 -0
  6. package/dist/accounts-TyMPSHM0.cjs.map +1 -0
  7. package/dist/adapters-DM59AJfR.d.cts +216 -0
  8. package/dist/adapters-DM59AJfR.d.ts +216 -0
  9. package/dist/cli/template-assets/api/src/errors/codes.ts +17 -0
  10. package/dist/cli/template-assets/api/src/errors/index.ts +16 -0
  11. package/dist/cli/template-assets/api/src/filters/exception.ts +53 -0
  12. package/dist/cli/template-assets/api/src/main.ts +189 -0
  13. package/dist/cli/template-assets/api/src/modules/health/controller.ts +23 -0
  14. package/dist/cli/template-assets/api/src/modules/health/dto/response.dto.ts +23 -0
  15. package/dist/cli/template-assets/api/src/modules/health/module.ts +12 -0
  16. package/dist/cli/template-assets/api/src/modules/health/service.ts +54 -0
  17. package/dist/cli/template-assets/api/src/modules/messaging/module.ts +7 -0
  18. package/dist/cli/template-assets/api/src/modules/messaging/service.ts +74 -0
  19. package/dist/cli/template-assets/api/src/shared/exceptions.ts +40 -0
  20. package/dist/cli/template-assets/api/src/shared/response.ts +31 -0
  21. package/dist/cli/template-assets/api/src/telemetry.ts +59 -0
  22. package/dist/cli/template-assets/api/src/types.ts +8 -0
  23. package/dist/cli/template-assets/cloudflare/cache.service.ts +23 -0
  24. package/dist/cli/template-assets/cloudflare/queue.service.ts +22 -0
  25. package/dist/cli/template-assets/cloudflare/worker.ts +33 -0
  26. package/dist/cli/template-assets/packages/jobs/src/index.ts +49 -0
  27. package/dist/cli/template-assets/packages/queue-runtime/src/index.ts +54 -0
  28. package/dist/cli/template-assets/root/dot-dockerignore +11 -0
  29. package/dist/cli/template-assets/root/dot-editorconfig +13 -0
  30. package/dist/cli/template-assets/root/dot-oxfmtrc.json +9 -0
  31. package/dist/cli/template-assets/root/dot-oxlintrc.json +47 -0
  32. package/dist/cli/template-assets/root/lefthook.yml +18 -0
  33. package/dist/cli/template-assets/web/postcss.config.mjs +9 -0
  34. package/dist/cli/template-assets/web/src/app/(app)/dashboard/page.tsx +5 -0
  35. package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +25 -0
  36. package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +75 -0
  37. package/dist/cli/template-assets/web/src/app/globals.css +48 -0
  38. package/dist/cli/template-assets/web/src/app/layout.tsx +30 -0
  39. package/dist/cli/template-assets/web/src/app/page.tsx +20 -0
  40. package/dist/cli/template-assets/web/src/components/overview/overview-panel.tsx +27 -0
  41. package/dist/cli/template-assets/web/src/components/shell/app-shell.tsx +37 -0
  42. package/dist/cli/template-assets/web/src/components/shell/providers.tsx +22 -0
  43. package/dist/cli/template-assets/web/src/lib/api-client.ts +57 -0
  44. package/dist/cli/template-assets/web/src/lib/auth-client.ts +15 -0
  45. package/dist/cli/template-assets/web/src/lib/server-auth.ts +38 -0
  46. package/dist/cli/template-assets/web/src/types/api.ts +18 -0
  47. package/dist/cli/template-assets/worker/src/app.module.ts +5 -0
  48. package/dist/cli/template-assets/worker/src/env.ts +8 -0
  49. package/dist/cli/template-assets/worker/src/main.ts +25 -0
  50. package/dist/cli/template-assets/worker/src/modules/queue/config.ts +16 -0
  51. package/dist/cli/template-assets/worker/src/modules/queue/module.ts +11 -0
  52. package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +105 -0
  53. package/dist/cli/template-assets/worker/src/modules/queue/repository.ts +16 -0
  54. package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +17 -0
  55. package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +12 -0
  56. package/dist/cli/template-assets/worker-messaging/jobs-messaging.ts +12 -0
  57. package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +39 -0
  58. package/dist/cli/template-assets/worker-messaging/src/env.ts +14 -0
  59. package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +59 -0
  60. package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +8 -0
  61. package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +113 -0
  62. package/dist/cli.js +1218 -0
  63. package/dist/cn-BVOnrSza.js +1 -0
  64. package/dist/constants-C4iP0--i.js +38 -0
  65. package/dist/constants-C4iP0--i.js.map +1 -0
  66. package/dist/constants-rCR-LNSN.cjs +91 -0
  67. package/dist/constants-rCR-LNSN.cjs.map +1 -0
  68. package/dist/core-BidJDmSN.cjs +759 -0
  69. package/dist/core-BidJDmSN.cjs.map +1 -0
  70. package/dist/core-C-EFrEd6.js +710 -0
  71. package/dist/core-C-EFrEd6.js.map +1 -0
  72. package/dist/decorate-BR5FVX5x.js +14 -0
  73. package/dist/decorate-R-oqksAh.cjs +25 -0
  74. package/dist/decorateParam-BFJPEGKJ.cjs +13 -0
  75. package/dist/decorateParam-CKE7_J1s.js +8 -0
  76. package/dist/define-adapter-Cc0QrfKt.cjs +16 -0
  77. package/dist/define-adapter-Cc0QrfKt.cjs.map +1 -0
  78. package/dist/define-adapter-DRcXno3j.js +11 -0
  79. package/dist/define-adapter-DRcXno3j.js.map +1 -0
  80. package/dist/dispatcher-BsD7cO2w.cjs +84 -0
  81. package/dist/dispatcher-BsD7cO2w.cjs.map +1 -0
  82. package/dist/dispatcher-DA_l1Vkv.js +73 -0
  83. package/dist/dispatcher-DA_l1Vkv.js.map +1 -0
  84. package/dist/errors-DxHoXrLd.d.cts +46 -0
  85. package/dist/errors-DxHoXrLd.d.ts +46 -0
  86. package/dist/http/index.cjs +440 -0
  87. package/dist/http/index.cjs.map +1 -0
  88. package/dist/http/index.d.cts +257 -0
  89. package/dist/http/index.d.ts +257 -0
  90. package/dist/http/index.js +400 -0
  91. package/dist/http/index.js.map +1 -0
  92. package/dist/http/swagger.cjs +122 -0
  93. package/dist/http/swagger.cjs.map +1 -0
  94. package/dist/http/swagger.d.cts +59 -0
  95. package/dist/http/swagger.d.ts +59 -0
  96. package/dist/http/swagger.js +117 -0
  97. package/dist/http/swagger.js.map +1 -0
  98. package/dist/index--EJQTnHy.d.cts +174 -0
  99. package/dist/index-B3aVdDMV.d.cts +51 -0
  100. package/dist/index-BDYdEWl2.d.cts +833 -0
  101. package/dist/index-BDYdEWl2.d.ts +833 -0
  102. package/dist/index-Bdl0AiNM.d.ts +1262 -0
  103. package/dist/index-By8b4ksT.d.ts +25 -0
  104. package/dist/index-ByS2IC02.d.ts +51 -0
  105. package/dist/index-DDSaLjXV.d.cts +25 -0
  106. package/dist/index-FTrYdHfq.d.cts +1262 -0
  107. package/dist/index-u3ArUXO0.d.ts +174 -0
  108. package/dist/index.cjs +1 -0
  109. package/dist/index.d.cts +4 -0
  110. package/dist/index.d.ts +4 -0
  111. package/dist/index.js +1 -0
  112. package/dist/label-BqmJoVE-.cjs +1 -0
  113. package/dist/label-XeChe1Bu.js +1 -0
  114. package/dist/messaging/index.cjs +1 -0
  115. package/dist/messaging/index.d.cts +1775 -0
  116. package/dist/messaging/index.d.ts +1775 -0
  117. package/dist/messaging/index.js +1 -0
  118. package/dist/misc-BpM_lMTx.js +1 -0
  119. package/dist/misc-DkqJOm1V.cjs +1 -0
  120. package/dist/operational-CnxdBwVG.d.cts +13 -0
  121. package/dist/operational-CnxdBwVG.d.ts +13 -0
  122. package/dist/redaction-DhuHTlHA.js +124 -0
  123. package/dist/redaction-DhuHTlHA.js.map +1 -0
  124. package/dist/redaction-uRIQbTwZ.cjs +171 -0
  125. package/dist/redaction-uRIQbTwZ.cjs.map +1 -0
  126. package/dist/rolldown-runtime-auK_WOaK.cjs +1 -0
  127. package/dist/rolldown-runtime-xuxB8TGW.cjs +32 -0
  128. package/dist/sdk-B2Lp3JCz.cjs +45 -0
  129. package/dist/sdk-B2Lp3JCz.cjs.map +1 -0
  130. package/dist/sdk-IGOHpAeG.js +22 -0
  131. package/dist/sdk-IGOHpAeG.js.map +1 -0
  132. package/dist/skills-C1uwr9Pp.js +4 -0
  133. package/dist/skills-DuE-XnBp.js +1 -0
  134. package/dist/sso/client.cjs +37 -0
  135. package/dist/sso/client.cjs.map +1 -0
  136. package/dist/sso/client.d.cts +89 -0
  137. package/dist/sso/client.d.ts +89 -0
  138. package/dist/sso/client.js +36 -0
  139. package/dist/sso/client.js.map +1 -0
  140. package/dist/sso/index.cjs +833 -0
  141. package/dist/sso/index.cjs.map +1 -0
  142. package/dist/sso/index.d.cts +2 -0
  143. package/dist/sso/index.d.ts +2 -0
  144. package/dist/sso/index.js +821 -0
  145. package/dist/sso/index.js.map +1 -0
  146. package/dist/sso/nestjs.cjs +169 -0
  147. package/dist/sso/nestjs.cjs.map +1 -0
  148. package/dist/sso/nestjs.d.cts +92 -0
  149. package/dist/sso/nestjs.d.ts +92 -0
  150. package/dist/sso/nestjs.js +151 -0
  151. package/dist/sso/nestjs.js.map +1 -0
  152. package/dist/sso/resource.cjs +124 -0
  153. package/dist/sso/resource.cjs.map +1 -0
  154. package/dist/sso/resource.d.cts +3 -0
  155. package/dist/sso/resource.d.ts +3 -0
  156. package/dist/sso/resource.js +114 -0
  157. package/dist/sso/resource.js.map +1 -0
  158. package/dist/status-CRvlFPIs.js +13 -0
  159. package/dist/status-CRvlFPIs.js.map +1 -0
  160. package/dist/status-DtK6OHtj.cjs +24 -0
  161. package/dist/status-DtK6OHtj.cjs.map +1 -0
  162. package/dist/telemetry/adapters.cjs +6 -0
  163. package/dist/telemetry/adapters.d.cts +3 -0
  164. package/dist/telemetry/adapters.d.ts +3 -0
  165. package/dist/telemetry/adapters.js +4 -0
  166. package/dist/telemetry/betterstack.cjs +74 -0
  167. package/dist/telemetry/betterstack.cjs.map +1 -0
  168. package/dist/telemetry/betterstack.d.cts +12 -0
  169. package/dist/telemetry/betterstack.d.ts +12 -0
  170. package/dist/telemetry/betterstack.js +71 -0
  171. package/dist/telemetry/betterstack.js.map +1 -0
  172. package/dist/telemetry/core.cjs +11 -0
  173. package/dist/telemetry/core.d.cts +4 -0
  174. package/dist/telemetry/core.d.ts +4 -0
  175. package/dist/telemetry/core.js +5 -0
  176. package/dist/telemetry/index.cjs +524 -0
  177. package/dist/telemetry/index.cjs.map +1 -0
  178. package/dist/telemetry/index.d.cts +68 -0
  179. package/dist/telemetry/index.d.ts +68 -0
  180. package/dist/telemetry/index.js +499 -0
  181. package/dist/telemetry/index.js.map +1 -0
  182. package/dist/telemetry/posthog.cjs +72 -0
  183. package/dist/telemetry/posthog.cjs.map +1 -0
  184. package/dist/telemetry/posthog.d.cts +10 -0
  185. package/dist/telemetry/posthog.d.ts +10 -0
  186. package/dist/telemetry/posthog.js +71 -0
  187. package/dist/telemetry/posthog.js.map +1 -0
  188. package/dist/telemetry/register.cjs +88 -0
  189. package/dist/telemetry/register.cjs.map +1 -0
  190. package/dist/telemetry/register.d.cts +14 -0
  191. package/dist/telemetry/register.d.ts +14 -0
  192. package/dist/telemetry/register.js +85 -0
  193. package/dist/telemetry/register.js.map +1 -0
  194. package/dist/telemetry/testing.cjs +54 -0
  195. package/dist/telemetry/testing.cjs.map +1 -0
  196. package/dist/telemetry/testing.d.cts +15 -0
  197. package/dist/telemetry/testing.d.ts +15 -0
  198. package/dist/telemetry/testing.js +52 -0
  199. package/dist/telemetry/testing.js.map +1 -0
  200. package/dist/telemetry.mock-BSsx7L6S.cjs +45 -0
  201. package/dist/telemetry.mock-BSsx7L6S.cjs.map +1 -0
  202. package/dist/telemetry.mock-BZRpy63c.js +40 -0
  203. package/dist/telemetry.mock-BZRpy63c.js.map +1 -0
  204. package/dist/telemetry.mock-C1wXuf-M.d.cts +4 -0
  205. package/dist/telemetry.mock-CdaxofJ7.d.ts +4 -0
  206. package/dist/ui/chart.cjs +6 -0
  207. package/dist/ui/chart.d.cts +34 -0
  208. package/dist/ui/chart.d.ts +34 -0
  209. package/dist/ui/chart.js +6 -0
  210. package/dist/ui/form.cjs +1 -0
  211. package/dist/ui/form.d.cts +23 -0
  212. package/dist/ui/form.d.ts +23 -0
  213. package/dist/ui/form.js +1 -0
  214. package/dist/ui/hooks.cjs +1 -0
  215. package/dist/ui/hooks.d.cts +66 -0
  216. package/dist/ui/hooks.d.ts +66 -0
  217. package/dist/ui/hooks.js +1 -0
  218. package/dist/ui/index.cjs +1 -0
  219. package/dist/ui/index.d.cts +3 -0
  220. package/dist/ui/index.d.ts +3 -0
  221. package/dist/ui/index.js +1 -0
  222. package/dist/ui/styles.css +2 -0
  223. package/dist/ui/utils.cjs +1 -0
  224. package/dist/ui/utils.d.cts +199 -0
  225. package/dist/ui/utils.d.ts +199 -0
  226. package/dist/ui/utils.js +1 -0
  227. package/dist/use-mobile-BbeIMRgE.cjs +1 -0
  228. package/dist/use-mobile-Cdd4Lp7p.js +1 -0
  229. package/dist/use-mobile-ecpyXWz3.d.cts +10 -0
  230. package/dist/use-mobile-ecpyXWz3.d.ts +10 -0
  231. package/dist/verifier-BIBtPCVi.cjs +119 -0
  232. package/dist/verifier-BIBtPCVi.cjs.map +1 -0
  233. package/dist/verifier-DNdy5Ynw.js +90 -0
  234. package/dist/verifier-DNdy5Ynw.js.map +1 -0
  235. package/dist/version-B0ADow60.js +1 -0
  236. package/dist/version-CMkha8JJ.cjs +1 -0
  237. package/package.json +539 -5
@@ -0,0 +1,40 @@
1
+ import {
2
+ BadGatewayException,
3
+ BadRequestException,
4
+ ConflictException,
5
+ ForbiddenException,
6
+ InternalServerErrorException,
7
+ NotFoundException,
8
+ UnauthorizedException,
9
+ } from '@nestjs/common';
10
+ import type { ErrorCode } from '../errors';
11
+ import { error } from './response';
12
+
13
+ export function badRequest(code: ErrorCode, errors?: unknown) {
14
+ return new BadRequestException(error(code, errors));
15
+ }
16
+
17
+ export function unauthorized(code: ErrorCode) {
18
+ return new UnauthorizedException(error(code));
19
+ }
20
+
21
+ export function forbidden(code: ErrorCode) {
22
+ return new ForbiddenException(error(code));
23
+ }
24
+
25
+ export function notFound(code: ErrorCode) {
26
+ return new NotFoundException(error(code));
27
+ }
28
+
29
+ export function conflict(code: ErrorCode, errors?: unknown) {
30
+ return new ConflictException(error(code, errors));
31
+ }
32
+
33
+ /** Falha de um servico externo, e nao da requisicao de quem chamou. */
34
+ export function upstreamFailed(code: ErrorCode) {
35
+ return new BadGatewayException(error(code));
36
+ }
37
+
38
+ export function internalError(code: ErrorCode) {
39
+ return new InternalServerErrorException(error(code));
40
+ }
@@ -0,0 +1,31 @@
1
+ import { type ErrorCode, ErrorMessages } from '../errors';
2
+
3
+ /**
4
+ * Envelope de sucesso.
5
+ *
6
+ * @remarks
7
+ * Toda resposta sai como `{ ok, ... }` para o cliente distinguir sucesso de
8
+ * erro por um campo so, sem depender do status HTTP — que se perde em proxy,
9
+ * retentativa e log.
10
+ */
11
+ export function ok<Data>(data: Data) {
12
+ return { ok: true as const, data };
13
+ }
14
+
15
+ /**
16
+ * Envelope de erro.
17
+ *
18
+ * @remarks
19
+ * Unico lugar que monta corpo de erro. Os atalhos de `shared/exceptions` e o
20
+ * filtro global chamam esta funcao: se cada um montasse o objeto na mao, o
21
+ * formato divergiria entre a excecao lancada por uma regra e a resposta de uma
22
+ * falha inesperada, e o cliente precisaria tratar dois contratos.
23
+ */
24
+ export function error(code: ErrorCode, errors?: unknown) {
25
+ return {
26
+ ok: false as const,
27
+ code,
28
+ message: ErrorMessages[code],
29
+ ...(errors === undefined ? {} : { errors }),
30
+ };
31
+ }
@@ -0,0 +1,59 @@
1
+ // #if posthog
2
+ import { posthog } from 'franchising/telemetry/posthog';
3
+ // #endif
4
+ // #if betterstack
5
+ import { betterstack } from 'franchising/telemetry/betterstack';
6
+ // #endif
7
+ import { registerTelemetry } from 'franchising/telemetry/register';
8
+ import { env } from './env';
9
+
10
+ /**
11
+ * Destinos externos dos sinais de telemetria.
12
+ *
13
+ * @remarks
14
+ * Sem credencial a lista fica vazia e a biblioteca vira no-op: os logs seguem
15
+ * saindo em JSON no stdout, e tracing, metricas e error tracking se desligam
16
+ * sozinhos. E o que faz o ambiente de desenvolvimento nao precisar de conta em
17
+ * provedor nenhum.
18
+ */
19
+ export const adapters = [
20
+ // #if posthog
21
+ /*
22
+ * O PostHog recebe evento de produto (`telemetry.event`) e excecao. Log
23
+ * tecnico — debug, info, warn e error — nao vai para ele de proposito:
24
+ * analytics e diagnostico operacional sao coisas diferentes.
25
+ */
26
+ ...(env.POSTHOG_API_KEY
27
+ ? [
28
+ posthog({
29
+ apiKey: env.POSTHOG_API_KEY,
30
+ host: env.POSTHOG_HOST,
31
+ }),
32
+ ]
33
+ : []),
34
+ // #endif
35
+ // #if betterstack
36
+ /*
37
+ * O Better Stack recebe os cinco sinais. O token da source fica no
38
+ * Collector, nunca no repositorio: aqui so entra o endereco dele.
39
+ */
40
+ ...(env.BETTERSTACK_OTLP_ENDPOINT
41
+ ? [
42
+ betterstack({
43
+ otlp: { endpoint: env.BETTERSTACK_OTLP_ENDPOINT },
44
+ ...(env.BETTERSTACK_ERRORS_DSN
45
+ ? { errors: { dsn: env.BETTERSTACK_ERRORS_DSN } }
46
+ : {}),
47
+ }),
48
+ ]
49
+ : []),
50
+ // #endif
51
+ ];
52
+
53
+ /*
54
+ * Roda no import, e nao numa funcao chamada depois: a auto-instrumentacao so
55
+ * consegue interceptar o Nest, o driver do banco e os clients HTTP se for
56
+ * registrada antes de esses modulos serem avaliados. Por isso `main.ts` importa
57
+ * este arquivo antes de qualquer `@nestjs/*`.
58
+ */
59
+ registerTelemetry({ adapters });
@@ -0,0 +1,8 @@
1
+ /** Versao da API. Toda rota de aplicacao vive sob este prefixo. */
2
+ export const API_VERSION = '1';
3
+
4
+ /** Prefixo que aparece na URL: `/v1`. */
5
+ export const API_VERSION_PREFIX = `v${API_VERSION}`;
6
+
7
+ /** Caminho da referencia do Scalar. */
8
+ export const API_DOCS_PATH = `${API_VERSION_PREFIX}/docs`;
@@ -0,0 +1,23 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { env } from 'cloudflare:workers';
3
+
4
+ @Injectable()
5
+ export class CacheService {
6
+ private get namespace() {
7
+ return (env as { CACHE?: KVNamespace }).CACHE;
8
+ }
9
+ async get(key: string): Promise<string | null> {
10
+ return this.namespace ? this.namespace.get(key) : null;
11
+ }
12
+ async set(key: string, value: string, ttlInSeconds?: number): Promise<void> {
13
+ await this.namespace?.put(key, value, ttlInSeconds === undefined ? undefined : { expirationTtl: Math.max(60, ttlInSeconds) });
14
+ }
15
+ async del(key: string): Promise<void> {
16
+ await this.namespace?.delete(key);
17
+ }
18
+ async ping(): Promise<string> {
19
+ if (!this.namespace) return 'disabled';
20
+ await this.namespace.get('__health');
21
+ return 'up';
22
+ }
23
+ }
@@ -0,0 +1,22 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { env } from 'cloudflare:workers';
3
+
4
+ export const queueBindings = __ROCK_QUEUE_BINDINGS__ as const;
5
+ export type JobQueue = keyof typeof queueBindings;
6
+ export type Job = { type: string; data: Record<string, unknown> };
7
+
8
+ @Injectable()
9
+ export class QueueService {
10
+ async send(queue: JobQueue, job: Job): Promise<void> {
11
+ const bindings = env as unknown as Record<string, Queue<Job>>;
12
+ const binding = bindings[queueBindings[queue]];
13
+ if (!binding) throw new Error('Queue binding is missing.');
14
+ await binding.send(job);
15
+ }
16
+ }
17
+
18
+ /** Replace this handler with the application's job processing. Throw to retry. */
19
+ export async function processJob(queue: string, job: Job): Promise<void> {
20
+ if (!Object.hasOwn(queueBindings, queue)) throw new Error('Unknown queue.');
21
+ console.info({ event: 'job.received', queue, type: job.type });
22
+ }
@@ -0,0 +1,33 @@
1
+ import { httpServerHandler } from 'cloudflare:node';
2
+ import type { Server } from 'node:http';
3
+ import { createApplication } from './main';
4
+
5
+ /** Cloudflare owns HTTP adaptation; each invocation owns its Nest providers. */
6
+ export default {
7
+ async fetch(
8
+ request: Request<unknown, IncomingRequestCfProperties>,
9
+ bindings: unknown,
10
+ context: ExecutionContext,
11
+ ): Promise<Response> {
12
+ const app = await createApplication();
13
+ const server = app.getHttpServer() as Server;
14
+ let cleanup: Promise<void> | undefined;
15
+ const close = () => (cleanup ??= app.close());
16
+ const release = () => context.waitUntil(close());
17
+ server.once('request', (_request, response) => {
18
+ response.once('finish', release);
19
+ response.once('close', release);
20
+ });
21
+ try {
22
+ /* `address()` do Node tambem devolve string (pipe); o Worker nunca usa pipe. */
23
+ const handler = httpServerHandler(
24
+ server as unknown as Parameters<typeof httpServerHandler>[0],
25
+ );
26
+ if (!handler.fetch) throw new Error('Cloudflare HTTP handler is unavailable.');
27
+ return await handler.fetch(request, bindings, context);
28
+ } catch (error) {
29
+ await close();
30
+ throw error;
31
+ }
32
+ },
33
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Nomes de fila e ajudantes de enfileiramento.
3
+ *
4
+ * @remarks
5
+ * Produtor e consumidor precisam concordar no nome e no prefixo da fila. Com
6
+ * as constantes aqui, renomear uma fila e uma mudanca so; com string literal
7
+ * dos dois lados, um lado renomeia e o outro passa a consumir uma fila vazia
8
+ * sem erro nenhum.
9
+ */
10
+
11
+ /** Identificador de job estavel, para o mesmo evento nao entrar duas vezes. */
12
+ export function jobId(parts: ReadonlyArray<string | number>): string {
13
+ /*
14
+ * O BullMQ recusa `:` em id customizado — justamente o separador obvio.
15
+ * Cada parte vai codificada para que um valor com ponto ou barra nao mude
16
+ * o significado do id.
17
+ */
18
+ return parts.map((part) => encodeURIComponent(String(part))).join('.');
19
+ }
20
+
21
+ /**
22
+ * Prefixo com hashtag por fila.
23
+ *
24
+ * @remarks
25
+ * Os scripts Lua do BullMQ tocam varias chaves de uma vez, e num Redis em modo
26
+ * cluster isso so e atomico se as chaves cairem no mesmo slot. A hashtag em
27
+ * volta do par prefixo/fila garante isso sem jogar todas as filas no mesmo
28
+ * shard.
29
+ */
30
+ export function queuePrefix(prefix: string, queueName: string): string {
31
+ const normalizedPrefix = prefix.trim().replace(/:+$/, '');
32
+ const normalizedQueue = queueName.trim();
33
+
34
+ if (!(normalizedPrefix && normalizedQueue)) {
35
+ throw new Error('QUEUE_PREFIX_AND_NAME_REQUIRED');
36
+ }
37
+
38
+ return `{${normalizedPrefix}:${normalizedQueue}}`;
39
+ }
40
+
41
+ /** Politica padrao de retentativa das filas do projeto. */
42
+ export const DEFAULT_JOB_OPTIONS = {
43
+ attempts: 5,
44
+ backoff: { type: 'exponential', delay: 1000 },
45
+ removeOnComplete: { age: 3600, count: 1000 },
46
+ removeOnFail: { age: 86_400 },
47
+ } as const;
48
+
49
+ export * from './queues';
@@ -0,0 +1,54 @@
1
+ import IORedis, { type Redis } from 'ioredis';
2
+
3
+ export type QueueRedisConnection = {
4
+ client: Redis;
5
+ close: () => Promise<void>;
6
+ };
7
+
8
+ /*
9
+ * `maxRetriesPerRequest: null` e exigencia do BullMQ para a conexao que fica
10
+ * bloqueada esperando job: com um teto, o ioredis derruba o comando e o worker
11
+ * para de consumir sem erro visivel.
12
+ */
13
+ const WORKER_OPTIONS = {
14
+ maxRetriesPerRequest: null,
15
+ enableReadyCheck: false,
16
+ } as const;
17
+
18
+ const PRODUCER_OPTIONS = {
19
+ maxRetriesPerRequest: 3,
20
+ } as const;
21
+
22
+ function connect(url: string, options: object): QueueRedisConnection {
23
+ const client = new IORedis(url, options);
24
+
25
+ return {
26
+ client,
27
+ close: async () => {
28
+ await client.quit();
29
+ },
30
+ };
31
+ }
32
+
33
+ /** Conexao de quem enfileira. */
34
+ export function createProducerRedisConnection(
35
+ url: string,
36
+ ): QueueRedisConnection {
37
+ return connect(url, PRODUCER_OPTIONS);
38
+ }
39
+
40
+ /** Conexao de quem consome. */
41
+ export function createWorkerRedisConnection(
42
+ url: string,
43
+ ): QueueRedisConnection {
44
+ return connect(url, WORKER_OPTIONS);
45
+ }
46
+
47
+ /** Motivo legivel da falha, para o log estruturado. */
48
+ export function failureReason(error: unknown): string {
49
+ if (error instanceof Error) {
50
+ return error.message;
51
+ }
52
+
53
+ return typeof error === 'string' ? error : 'unknown';
54
+ }
@@ -0,0 +1,11 @@
1
+ .git
2
+ .github
3
+ .code-review-graph
4
+ **/.env
5
+ **/.env.*
6
+ **/.next
7
+ **/.turbo
8
+ **/coverage
9
+ **/dist
10
+ **/node_modules
11
+ *.log
@@ -0,0 +1,13 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ indent_style = tab
9
+ indent_size = 4
10
+
11
+ [*.{yml,yaml}]
12
+ indent_style = space
13
+ indent_size = 2
@@ -0,0 +1,9 @@
1
+ {
2
+ "useTabs": true,
3
+ "tabWidth": 4,
4
+ "printWidth": 80,
5
+ "singleQuote": true,
6
+ "semi": true,
7
+ "endOfLine": "lf",
8
+ "sortImports": true
9
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/npm/oxlint/configuration_schema.json",
3
+ "categories": {
4
+ "correctness": "error",
5
+ "suspicious": "error",
6
+ "perf": "error"
7
+ },
8
+ "plugins": [
9
+ "import",
10
+ "oxc",
11
+ "typescript",
12
+ "unicorn"
13
+ // #if hasWeb
14
+ ,
15
+ "jsx-a11y",
16
+ "react",
17
+ "nextjs"
18
+ // #endif
19
+ ],
20
+ "rules": {
21
+ "typescript/consistent-type-imports": "off",
22
+ // #if hasWeb
23
+ "react/react-in-jsx-scope": "off",
24
+ // #endif
25
+ // #if hasApi
26
+ "typescript/no-extraneous-class": ["error", { "allowWithDecorator": true }],
27
+ // #endif
28
+ "import/no-unassigned-import": [
29
+ "error",
30
+ {
31
+ "allow": [
32
+ "reflect-metadata",
33
+ "dotenv/config",
34
+ "./telemetry",
35
+ "**/*.css"
36
+ ]
37
+ }
38
+ ]
39
+ },
40
+ "ignorePatterns": [
41
+ "**/dist",
42
+ "**/.next",
43
+ "**/coverage",
44
+ "**/drizzle/meta",
45
+ "**/next-env.d.ts"
46
+ ]
47
+ }
@@ -0,0 +1,18 @@
1
+ pre-commit:
2
+ parallel: false
3
+ commands:
4
+ format:
5
+ glob: '*.{ts,tsx,js,jsx,json,jsonc,css,md}'
6
+ run: __ROCK_PM_EXEC__ ultracite fix {staged_files}
7
+ stage_fixed: true
8
+ types:
9
+ run: __ROCK_PM__ run typecheck
10
+ test:
11
+ run: __ROCK_PM__ run test
12
+ pre-push:
13
+ parallel: false
14
+ commands:
15
+ types:
16
+ run: __ROCK_PM__ run typecheck
17
+ test:
18
+ run: __ROCK_PM__ run test
@@ -0,0 +1,9 @@
1
+ /*
2
+ * O franchising/ui publica o CSS ja compilado, entao o Tailwind aqui serve para
3
+ * os utilitarios que esta app escrever por conta propria.
4
+ */
5
+ const config = {
6
+ plugins: ['@tailwindcss/postcss'],
7
+ };
8
+
9
+ export default config;
@@ -0,0 +1,5 @@
1
+ import { OverviewPanel } from '@/components/overview/overview-panel';
2
+
3
+ export default function DashboardPage() {
4
+ return <OverviewPanel />;
5
+ }
@@ -0,0 +1,25 @@
1
+ import { redirect } from 'next/navigation';
2
+ import type { ReactNode } from 'react';
3
+ import { AppShell } from '@/components/shell/app-shell';
4
+ import { getSession } from '@/lib/server-auth';
5
+
6
+ /*
7
+ * A sessao e lida no servidor e o redirecionamento acontece antes de qualquer
8
+ * render: checar no cliente deixaria o painel aparecer por um instante para
9
+ * quem nao esta autenticado.
10
+ */
11
+ export const dynamic = 'force-dynamic';
12
+
13
+ export default async function AppLayout({
14
+ children,
15
+ }: {
16
+ children: ReactNode;
17
+ }) {
18
+ const session = await getSession();
19
+
20
+ if (!session) {
21
+ redirect('/login');
22
+ }
23
+
24
+ return <AppShell>{children}</AppShell>;
25
+ }
@@ -0,0 +1,75 @@
1
+ 'use client';
2
+
3
+ import {
4
+ Login,
5
+ // #if magicLink
6
+ LoginMagicLink,
7
+ // #endif
8
+ // #if hasSocial
9
+ LoginProvider,
10
+ // #endif
11
+ } from 'franchising/ui';
12
+ import Image from 'next/image';
13
+ import Link from 'next/link';
14
+ import { useRouter } from 'next/navigation';
15
+ import { useState } from 'react';
16
+ import { authClient } from '@/lib/auth-client';
17
+
18
+ export default function LoginPage() {
19
+ const router = useRouter();
20
+ const [error, setError] = useState<string | null>(null);
21
+
22
+ return (
23
+ <Login
24
+ headline="Bem-vindo de volta."
25
+ headlineHighlight="volta"
26
+ subtitle="Use o email e a senha da sua conta."
27
+ error={error}
28
+ /* A lib nao importa `next/*`: o interop de imagem e link vem por prop. */
29
+ imageComponent={Image}
30
+ linkComponent={Link}
31
+ onSubmit={async ({ email, password }) => {
32
+ setError(null);
33
+
34
+ const { error: signInError } = await authClient.signIn.email({
35
+ email,
36
+ password,
37
+ });
38
+
39
+ if (signInError) {
40
+ setError(signInError.message ?? 'Nao foi possivel entrar.');
41
+
42
+ return;
43
+ }
44
+
45
+ router.push('/dashboard');
46
+ }}
47
+ >
48
+ // #if google
49
+ <LoginProvider
50
+ onSelect={() =>
51
+ authClient.signIn.social({ provider: 'google' })
52
+ }
53
+ >
54
+ Entrar com Google
55
+ </LoginProvider>
56
+ // #endif
57
+ // #if github
58
+ <LoginProvider
59
+ onSelect={() =>
60
+ authClient.signIn.social({ provider: 'github' })
61
+ }
62
+ >
63
+ Entrar com GitHub
64
+ </LoginProvider>
65
+ // #endif
66
+ // #if magicLink
67
+ <LoginMagicLink
68
+ onRequest={async (email) => {
69
+ await authClient.signIn.magicLink({ email });
70
+ }}
71
+ />
72
+ // #endif
73
+ </Login>
74
+ );
75
+ }
@@ -0,0 +1,48 @@
1
+ /*
2
+ * A folha do franchising/ui vem primeiro: ela traz o preflight, os tokens e as
3
+ * classes dos componentes. O CSS da app fica depois para poder sobrescrever.
4
+ */
5
+ @import 'franchising/ui/styles.css';
6
+ @import 'tailwindcss';
7
+
8
+ /*
9
+ * O pacote publica Tailwind ja compilado, entao ele carrega `--primary` e os
10
+ * demais tokens, mas nao os `--color-*` — esses saem do `@theme inline`, que o
11
+ * Tailwind resolve em tempo de build e nao emite. Sem o bloco abaixo, um
12
+ * `bg-primary` escrito nesta app nao resolveria para cor nenhuma.
13
+ */
14
+ @theme inline {
15
+ --color-background: var(--background);
16
+ --color-foreground: var(--foreground);
17
+ --color-card: var(--card);
18
+ --color-card-foreground: var(--card-foreground);
19
+ --color-popover: var(--popover);
20
+ --color-popover-foreground: var(--popover-foreground);
21
+ --color-primary: var(--primary);
22
+ --color-primary-foreground: var(--primary-foreground);
23
+ --color-secondary: var(--secondary);
24
+ --color-secondary-foreground: var(--secondary-foreground);
25
+ --color-muted: var(--muted);
26
+ --color-muted-foreground: var(--muted-foreground);
27
+ --color-accent: var(--accent);
28
+ --color-accent-foreground: var(--accent-foreground);
29
+ --color-destructive: var(--destructive);
30
+ --color-destructive-foreground: var(--destructive-foreground);
31
+ --color-border: var(--border);
32
+ --color-input: var(--input);
33
+ --color-ring: var(--ring);
34
+ --color-sidebar: var(--sidebar);
35
+ --color-sidebar-foreground: var(--sidebar-foreground);
36
+ --color-sidebar-border: var(--sidebar-border);
37
+ --radius-sm: var(--radius-sm);
38
+ --radius-md: var(--radius-md);
39
+ --radius-lg: var(--radius-lg);
40
+ --font-sans: var(--font-sans);
41
+ --font-mono: var(--font-mono);
42
+ }
43
+
44
+ :root {
45
+ /* Aponta os tokens de fonte da biblioteca para as fontes desta app. */
46
+ --font-inter: var(--font-app-sans);
47
+ --font-jetbrains-mono: var(--font-app-mono);
48
+ }
@@ -0,0 +1,30 @@
1
+ import type { Metadata } from 'next';
2
+ import { Inter, JetBrains_Mono } from 'next/font/google';
3
+ import type { ReactNode } from 'react';
4
+ import { Providers } from '@/components/shell/providers';
5
+ import './globals.css';
6
+
7
+ const sans = Inter({
8
+ subsets: ['latin'],
9
+ variable: '--font-app-sans',
10
+ });
11
+
12
+ const mono = JetBrains_Mono({
13
+ subsets: ['latin'],
14
+ variable: '--font-app-mono',
15
+ });
16
+
17
+ export const metadata: Metadata = {
18
+ title: '__ROCK_PROJECT_NAME__',
19
+ description: 'Aplicacao __ROCK_PROJECT_NAME__.',
20
+ };
21
+
22
+ export default function RootLayout({ children }: { children: ReactNode }) {
23
+ return (
24
+ <html lang="pt-BR" className={`${sans.variable} ${mono.variable}`}>
25
+ <body>
26
+ <Providers>{children}</Providers>
27
+ </body>
28
+ </html>
29
+ );
30
+ }
@@ -0,0 +1,20 @@
1
+ // #if betterAuth
2
+ import { redirect } from 'next/navigation';
3
+
4
+ export default function HomePage() {
5
+ redirect('/dashboard');
6
+ }
7
+ // #else
8
+ export default function HomePage() {
9
+ return (
10
+ <main className="flex min-h-dvh flex-col items-center justify-center gap-2 p-8 text-center">
11
+ <h1 className="font-semibold text-2xl tracking-tight">
12
+ __ROCK_PROJECT_NAME__
13
+ </h1>
14
+ <p className="text-muted-foreground text-sm">
15
+ Edite src/app/page.tsx para comecar.
16
+ </p>
17
+ </main>
18
+ );
19
+ }
20
+ // #endif
@@ -0,0 +1,27 @@
1
+ 'use client';
2
+
3
+ import { Card, CardContent, CardHeader, CardTitle } from 'franchising/ui';
4
+
5
+ /**
6
+ * Tela do painel.
7
+ *
8
+ * @remarks
9
+ * Componente de cliente porque usa o franchising/ui, cujos componentes dependem
10
+ * de contexto do React. A pagina em `app/` fica so com a rota e delega para
11
+ * ca — e por isso o arquivo de rota nao vira o lugar onde a tela inteira mora.
12
+ */
13
+ export function OverviewPanel() {
14
+ return (
15
+ <main className="flex flex-col gap-6 p-6">
16
+ <h1 className="font-semibold text-2xl">Painel</h1>
17
+ <Card>
18
+ <CardHeader>
19
+ <CardTitle>Comece por aqui</CardTitle>
20
+ </CardHeader>
21
+ <CardContent className="text-muted-foreground text-sm">
22
+ Substitua este cartao pelo primeiro indicador do produto.
23
+ </CardContent>
24
+ </Card>
25
+ </main>
26
+ );
27
+ }