@neetru/sdk 3.1.14 → 3.1.15
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/build-guard.cjs +65 -0
- package/dist/build-guard.cjs.map +1 -0
- package/dist/build-guard.d.cts +32 -0
- package/dist/build-guard.d.ts +32 -0
- package/dist/build-guard.mjs +42 -0
- package/dist/build-guard.mjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -1
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var fs = require('fs');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
|
|
6
|
+
function _interopNamespace(e) {
|
|
7
|
+
if (e && e.__esModule) return e;
|
|
8
|
+
var n = Object.create(null);
|
|
9
|
+
if (e) {
|
|
10
|
+
Object.keys(e).forEach(function (k) {
|
|
11
|
+
if (k !== 'default') {
|
|
12
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
13
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function () { return e[k]; }
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
n.default = e;
|
|
21
|
+
return Object.freeze(n);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
25
|
+
var path__namespace = /*#__PURE__*/_interopNamespace(path);
|
|
26
|
+
|
|
27
|
+
// src/build-guard.ts
|
|
28
|
+
function withNeetruBuildGuard(nextConfig, options = {}) {
|
|
29
|
+
const prevWebpack = nextConfig.webpack;
|
|
30
|
+
return {
|
|
31
|
+
...nextConfig,
|
|
32
|
+
webpack(config, context) {
|
|
33
|
+
const result = typeof prevWebpack === "function" ? prevWebpack(config, context) : config;
|
|
34
|
+
if (!context.dev && context.isServer) {
|
|
35
|
+
try {
|
|
36
|
+
const outDir = path__namespace.resolve(process.cwd(), options.outputDir ?? ".next");
|
|
37
|
+
fs__namespace.mkdirSync(outDir, { recursive: true });
|
|
38
|
+
const manifest = {
|
|
39
|
+
builtEnv: process.env.NEXT_PUBLIC_NEETRU_ENV ?? null,
|
|
40
|
+
productId: process.env.NEXT_PUBLIC_NEETRU_PRODUCT_ID ?? null,
|
|
41
|
+
oidcClientId: process.env.NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID ?? null,
|
|
42
|
+
builtAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
43
|
+
};
|
|
44
|
+
fs__namespace.writeFileSync(
|
|
45
|
+
path__namespace.join(outDir, "neetru-build-manifest.json"),
|
|
46
|
+
JSON.stringify(manifest, null, 2),
|
|
47
|
+
"utf8"
|
|
48
|
+
);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (typeof console !== "undefined") {
|
|
51
|
+
console.warn(
|
|
52
|
+
"[neetru-sdk] withNeetruBuildGuard: falha ao gravar neetru-build-manifest.json (ignorado, build segue):",
|
|
53
|
+
err
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
exports.withNeetruBuildGuard = withNeetruBuildGuard;
|
|
64
|
+
//# sourceMappingURL=build-guard.cjs.map
|
|
65
|
+
//# sourceMappingURL=build-guard.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/build-guard.ts"],"names":["path","fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFO,SAAS,oBAAA,CACd,UAAA,EACA,OAAA,GAAuC,EAAC,EACrC;AACH,EAAA,MAAM,cAAc,UAAA,CAAW,OAAA;AAE/B,EAAA,OAA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config.mjs` que grava\r\n * `.next/neetru-build-manifest.json` ao final do build com os valores\r\n * `NEXT_PUBLIC_NEETRU_*` que realmente foram resolvidos pelo Next.js.\r\n *\r\n * Existe pra fechar um bug de precedência de env do Next.js (incidente\r\n * 2026-07-22, pdv-agiliza): `.env.local` (fica no disco do dev) vence\r\n * `.env.production` durante `next build` pra qualquer chave em comum —\r\n * então um build \"de prod\" podia compilar com `NEXT_PUBLIC_NEETRU_ENV=dev`\r\n * sem nenhum aviso, ativando `MockAuth` no bundle do browser em produção\r\n * (o botão \"Entrar com Neetru\" não fazia nada, porque `MockAuth.signIn()`\r\n * só finge um login em memória — nunca navega pro IdP real).\r\n *\r\n * O manifesto não inspeciona o JS compilado (minificação/webpack\r\n * `DefinePlugin` tornam isso frágil — o nome da chave some, só sobra o\r\n * literal). Em vez disso grava, em texto puro, o que o processo Node do\r\n * build efetivamente tinha em `process.env` no momento da compilação\r\n * server-side — reflete fielmente a resolução real do Next.js/dotenv,\r\n * incluindo qualquer override via spawn-env (`@neetru/cli` injeta\r\n * `NEXT_PUBLIC_NEETRU_ENV` assim desde a v2.26.2). `neetru build` lê este\r\n * arquivo depois do build e recusa empacotar o tarball se o valor não\r\n * bater com o ambiente esperado do deploy.\r\n *\r\n * Uso, em `next.config.mjs`:\r\n * ```js\r\n * import { withNeetruBuildGuard } from '@neetru/sdk/build-guard';\r\n * export default withNeetruBuildGuard({ ...nextConfig });\r\n * ```\r\n *\r\n * Subpath dedicado (`@neetru/sdk/build-guard`, não o barrel `.`) de\r\n * propósito: este arquivo é o único no SDK que importa `node:fs`/`node:path`\r\n * estaticamente. O entry `.` promete rodar em browser/Node/Edge sem Node\r\n * builtins — reexportar o guard ali vazaria essa dependência pro bundle\r\n * universal (achado real da revisão: `esbuild --platform=browser` falha com\r\n * \"Could not resolve fs/path\" se o guard entra no barrel principal).\r\n *\r\n * IMPORTANTE — isto NÃO é uma checagem universal de \"o env está certo\": o\r\n * guard grava literalmente as 3 env vars `NEXT_PUBLIC_NEETRU_ENV` /\r\n * `_PRODUCT_ID` / `_OIDC_CLIENT_ID`, que são a convenção recomendada de\r\n * bootstrap Next.js do ecossistema Neetru (o que `neetru-pdvagiliza` e\r\n * outros produtos usam em `src/lib/neetru/client.ts` pra montar\r\n * `createNeetruClient({env, productId, oidcClientId})`) — **não** é o mesmo\r\n * que o fallback interno `NEETRU_ENV`/`globalThis.NEETRU_ENV` que\r\n * `resolveEnv()` (`src/auth.ts`) usa quando NENHUM `env` é passado\r\n * explicitamente pro client. Se o seu produto bootstrap o client de outra\r\n * forma (nome de env var diferente, ou sem prefixo `NEXT_PUBLIC_`, ou\r\n * hardcoded), este guard não detecta drift pra esse caso — ele só confirma\r\n * que a convenção documentada acima foi respeitada.\r\n *\r\n * Composável com qualquer wrapper que já use a chave `webpack` do config\r\n * (ex: `next-pwa`) — a função `webpack` anterior, se houver, é chamada\r\n * primeiro e o retorno dela é repassado adiante sem alteração.\r\n */\r\nimport * as fs from 'node:fs';\r\nimport * as path from 'node:path';\r\n\r\n/** Formato do `.next/neetru-build-manifest.json`. */\r\nexport interface NeetruBuildManifest {\r\n /** `NEXT_PUBLIC_NEETRU_ENV` resolvido no momento do build (`dev|workspace|prod`), ou `null` se ausente. */\r\n builtEnv: string | null;\r\n /** `NEXT_PUBLIC_NEETRU_PRODUCT_ID` resolvido, ou `null`. */\r\n productId: string | null;\r\n /** `NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID` resolvido, ou `null`. */\r\n oidcClientId: string | null;\r\n /** ISO timestamp de quando o manifesto foi gravado. */\r\n builtAt: string;\r\n}\r\n\r\nexport interface WithNeetruBuildGuardOptions {\r\n /** Diretório de saída do Next (default `.next`, relativo ao cwd do build). */\r\n outputDir?: string;\r\n}\r\n\r\n/**\r\n * Formato mínimo de `next.config.mjs` que o wrapper precisa entender — só\r\n * o suficiente pra compor a chave `webpack` sem acoplar o SDK ao pacote\r\n * `next` como dependência de tipos.\r\n */\r\ntype MinimalWebpackContext = {\r\n buildId: string;\r\n dev: boolean;\r\n isServer: boolean;\r\n [key: string]: unknown;\r\n};\r\ntype MinimalNextConfig = Record<string, unknown> & {\r\n webpack?: (config: unknown, context: MinimalWebpackContext) => unknown;\r\n};\r\n\r\nexport function withNeetruBuildGuard<T extends MinimalNextConfig>(\r\n nextConfig: T,\r\n options: WithNeetruBuildGuardOptions = {},\r\n): T {\r\n const prevWebpack = nextConfig.webpack;\r\n\r\n return {\r\n ...nextConfig,\r\n webpack(config: unknown, context: MinimalWebpackContext): unknown {\r\n const result = typeof prevWebpack === 'function' ? prevWebpack(config, context) : config;\r\n\r\n // Grava só na passada server (roda 1x por build, diferente da passada\r\n // client que pode rodar múltiplas vezes) e só fora de `next dev` —\r\n // `next build` é sempre produção de artefato de deploy.\r\n if (!context.dev && context.isServer) {\r\n try {\r\n const outDir = path.resolve(process.cwd(), options.outputDir ?? '.next');\r\n fs.mkdirSync(outDir, { recursive: true });\r\n const manifest: NeetruBuildManifest = {\r\n builtEnv: process.env.NEXT_PUBLIC_NEETRU_ENV ?? null,\r\n productId: process.env.NEXT_PUBLIC_NEETRU_PRODUCT_ID ?? null,\r\n oidcClientId: process.env.NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID ?? null,\r\n builtAt: new Date().toISOString(),\r\n };\r\n fs.writeFileSync(\r\n path.join(outDir, 'neetru-build-manifest.json'),\r\n JSON.stringify(manifest, null, 2),\r\n 'utf8',\r\n );\r\n } catch (err) {\r\n // Best-effort — o guard nunca pode quebrar o build do produto,\r\n // mas uma falha de escrita silenciosa aqui esconderia o problema\r\n // (achado da revisão: sem log, ninguém percebe que o manifesto não\r\n // foi gravado e `neetru build` trata \"manifesto ausente\" como\r\n // aviso, não bloqueio — visibilidade aqui é a única forma de notar).\r\n if (typeof console !== 'undefined') {\r\n console.warn(\r\n '[neetru-sdk] withNeetruBuildGuard: falha ao gravar neetru-build-manifest.json (ignorado, build segue):',\r\n err,\r\n );\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n },\r\n } as T;\r\n}\r\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Formato do `.next/neetru-build-manifest.json`. */
|
|
2
|
+
interface NeetruBuildManifest {
|
|
3
|
+
/** `NEXT_PUBLIC_NEETRU_ENV` resolvido no momento do build (`dev|workspace|prod`), ou `null` se ausente. */
|
|
4
|
+
builtEnv: string | null;
|
|
5
|
+
/** `NEXT_PUBLIC_NEETRU_PRODUCT_ID` resolvido, ou `null`. */
|
|
6
|
+
productId: string | null;
|
|
7
|
+
/** `NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID` resolvido, ou `null`. */
|
|
8
|
+
oidcClientId: string | null;
|
|
9
|
+
/** ISO timestamp de quando o manifesto foi gravado. */
|
|
10
|
+
builtAt: string;
|
|
11
|
+
}
|
|
12
|
+
interface WithNeetruBuildGuardOptions {
|
|
13
|
+
/** Diretório de saída do Next (default `.next`, relativo ao cwd do build). */
|
|
14
|
+
outputDir?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Formato mínimo de `next.config.mjs` que o wrapper precisa entender — só
|
|
18
|
+
* o suficiente pra compor a chave `webpack` sem acoplar o SDK ao pacote
|
|
19
|
+
* `next` como dependência de tipos.
|
|
20
|
+
*/
|
|
21
|
+
type MinimalWebpackContext = {
|
|
22
|
+
buildId: string;
|
|
23
|
+
dev: boolean;
|
|
24
|
+
isServer: boolean;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
};
|
|
27
|
+
type MinimalNextConfig = Record<string, unknown> & {
|
|
28
|
+
webpack?: (config: unknown, context: MinimalWebpackContext) => unknown;
|
|
29
|
+
};
|
|
30
|
+
declare function withNeetruBuildGuard<T extends MinimalNextConfig>(nextConfig: T, options?: WithNeetruBuildGuardOptions): T;
|
|
31
|
+
|
|
32
|
+
export { type NeetruBuildManifest, type WithNeetruBuildGuardOptions, withNeetruBuildGuard };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Formato do `.next/neetru-build-manifest.json`. */
|
|
2
|
+
interface NeetruBuildManifest {
|
|
3
|
+
/** `NEXT_PUBLIC_NEETRU_ENV` resolvido no momento do build (`dev|workspace|prod`), ou `null` se ausente. */
|
|
4
|
+
builtEnv: string | null;
|
|
5
|
+
/** `NEXT_PUBLIC_NEETRU_PRODUCT_ID` resolvido, ou `null`. */
|
|
6
|
+
productId: string | null;
|
|
7
|
+
/** `NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID` resolvido, ou `null`. */
|
|
8
|
+
oidcClientId: string | null;
|
|
9
|
+
/** ISO timestamp de quando o manifesto foi gravado. */
|
|
10
|
+
builtAt: string;
|
|
11
|
+
}
|
|
12
|
+
interface WithNeetruBuildGuardOptions {
|
|
13
|
+
/** Diretório de saída do Next (default `.next`, relativo ao cwd do build). */
|
|
14
|
+
outputDir?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Formato mínimo de `next.config.mjs` que o wrapper precisa entender — só
|
|
18
|
+
* o suficiente pra compor a chave `webpack` sem acoplar o SDK ao pacote
|
|
19
|
+
* `next` como dependência de tipos.
|
|
20
|
+
*/
|
|
21
|
+
type MinimalWebpackContext = {
|
|
22
|
+
buildId: string;
|
|
23
|
+
dev: boolean;
|
|
24
|
+
isServer: boolean;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
};
|
|
27
|
+
type MinimalNextConfig = Record<string, unknown> & {
|
|
28
|
+
webpack?: (config: unknown, context: MinimalWebpackContext) => unknown;
|
|
29
|
+
};
|
|
30
|
+
declare function withNeetruBuildGuard<T extends MinimalNextConfig>(nextConfig: T, options?: WithNeetruBuildGuardOptions): T;
|
|
31
|
+
|
|
32
|
+
export { type NeetruBuildManifest, type WithNeetruBuildGuardOptions, withNeetruBuildGuard };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
|
|
4
|
+
// src/build-guard.ts
|
|
5
|
+
function withNeetruBuildGuard(nextConfig, options = {}) {
|
|
6
|
+
const prevWebpack = nextConfig.webpack;
|
|
7
|
+
return {
|
|
8
|
+
...nextConfig,
|
|
9
|
+
webpack(config, context) {
|
|
10
|
+
const result = typeof prevWebpack === "function" ? prevWebpack(config, context) : config;
|
|
11
|
+
if (!context.dev && context.isServer) {
|
|
12
|
+
try {
|
|
13
|
+
const outDir = path.resolve(process.cwd(), options.outputDir ?? ".next");
|
|
14
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
15
|
+
const manifest = {
|
|
16
|
+
builtEnv: process.env.NEXT_PUBLIC_NEETRU_ENV ?? null,
|
|
17
|
+
productId: process.env.NEXT_PUBLIC_NEETRU_PRODUCT_ID ?? null,
|
|
18
|
+
oidcClientId: process.env.NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID ?? null,
|
|
19
|
+
builtAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20
|
+
};
|
|
21
|
+
fs.writeFileSync(
|
|
22
|
+
path.join(outDir, "neetru-build-manifest.json"),
|
|
23
|
+
JSON.stringify(manifest, null, 2),
|
|
24
|
+
"utf8"
|
|
25
|
+
);
|
|
26
|
+
} catch (err) {
|
|
27
|
+
if (typeof console !== "undefined") {
|
|
28
|
+
console.warn(
|
|
29
|
+
"[neetru-sdk] withNeetruBuildGuard: falha ao gravar neetru-build-manifest.json (ignorado, build segue):",
|
|
30
|
+
err
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { withNeetruBuildGuard };
|
|
41
|
+
//# sourceMappingURL=build-guard.mjs.map
|
|
42
|
+
//# sourceMappingURL=build-guard.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/build-guard.ts"],"names":[],"mappings":";;;;AAwFO,SAAS,oBAAA,CACd,UAAA,EACA,OAAA,GAAuC,EAAC,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","file":"build-guard.mjs","sourcesContent":["/**\r\n * `withNeetruBuildGuard` — wrapper de `next.config.mjs` que grava\r\n * `.next/neetru-build-manifest.json` ao final do build com os valores\r\n * `NEXT_PUBLIC_NEETRU_*` que realmente foram resolvidos pelo Next.js.\r\n *\r\n * Existe pra fechar um bug de precedência de env do Next.js (incidente\r\n * 2026-07-22, pdv-agiliza): `.env.local` (fica no disco do dev) vence\r\n * `.env.production` durante `next build` pra qualquer chave em comum —\r\n * então um build \"de prod\" podia compilar com `NEXT_PUBLIC_NEETRU_ENV=dev`\r\n * sem nenhum aviso, ativando `MockAuth` no bundle do browser em produção\r\n * (o botão \"Entrar com Neetru\" não fazia nada, porque `MockAuth.signIn()`\r\n * só finge um login em memória — nunca navega pro IdP real).\r\n *\r\n * O manifesto não inspeciona o JS compilado (minificação/webpack\r\n * `DefinePlugin` tornam isso frágil — o nome da chave some, só sobra o\r\n * literal). Em vez disso grava, em texto puro, o que o processo Node do\r\n * build efetivamente tinha em `process.env` no momento da compilação\r\n * server-side — reflete fielmente a resolução real do Next.js/dotenv,\r\n * incluindo qualquer override via spawn-env (`@neetru/cli` injeta\r\n * `NEXT_PUBLIC_NEETRU_ENV` assim desde a v2.26.2). `neetru build` lê este\r\n * arquivo depois do build e recusa empacotar o tarball se o valor não\r\n * bater com o ambiente esperado do deploy.\r\n *\r\n * Uso, em `next.config.mjs`:\r\n * ```js\r\n * import { withNeetruBuildGuard } from '@neetru/sdk/build-guard';\r\n * export default withNeetruBuildGuard({ ...nextConfig });\r\n * ```\r\n *\r\n * Subpath dedicado (`@neetru/sdk/build-guard`, não o barrel `.`) de\r\n * propósito: este arquivo é o único no SDK que importa `node:fs`/`node:path`\r\n * estaticamente. O entry `.` promete rodar em browser/Node/Edge sem Node\r\n * builtins — reexportar o guard ali vazaria essa dependência pro bundle\r\n * universal (achado real da revisão: `esbuild --platform=browser` falha com\r\n * \"Could not resolve fs/path\" se o guard entra no barrel principal).\r\n *\r\n * IMPORTANTE — isto NÃO é uma checagem universal de \"o env está certo\": o\r\n * guard grava literalmente as 3 env vars `NEXT_PUBLIC_NEETRU_ENV` /\r\n * `_PRODUCT_ID` / `_OIDC_CLIENT_ID`, que são a convenção recomendada de\r\n * bootstrap Next.js do ecossistema Neetru (o que `neetru-pdvagiliza` e\r\n * outros produtos usam em `src/lib/neetru/client.ts` pra montar\r\n * `createNeetruClient({env, productId, oidcClientId})`) — **não** é o mesmo\r\n * que o fallback interno `NEETRU_ENV`/`globalThis.NEETRU_ENV` que\r\n * `resolveEnv()` (`src/auth.ts`) usa quando NENHUM `env` é passado\r\n * explicitamente pro client. Se o seu produto bootstrap o client de outra\r\n * forma (nome de env var diferente, ou sem prefixo `NEXT_PUBLIC_`, ou\r\n * hardcoded), este guard não detecta drift pra esse caso — ele só confirma\r\n * que a convenção documentada acima foi respeitada.\r\n *\r\n * Composável com qualquer wrapper que já use a chave `webpack` do config\r\n * (ex: `next-pwa`) — a função `webpack` anterior, se houver, é chamada\r\n * primeiro e o retorno dela é repassado adiante sem alteração.\r\n */\r\nimport * as fs from 'node:fs';\r\nimport * as path from 'node:path';\r\n\r\n/** Formato do `.next/neetru-build-manifest.json`. */\r\nexport interface NeetruBuildManifest {\r\n /** `NEXT_PUBLIC_NEETRU_ENV` resolvido no momento do build (`dev|workspace|prod`), ou `null` se ausente. */\r\n builtEnv: string | null;\r\n /** `NEXT_PUBLIC_NEETRU_PRODUCT_ID` resolvido, ou `null`. */\r\n productId: string | null;\r\n /** `NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID` resolvido, ou `null`. */\r\n oidcClientId: string | null;\r\n /** ISO timestamp de quando o manifesto foi gravado. */\r\n builtAt: string;\r\n}\r\n\r\nexport interface WithNeetruBuildGuardOptions {\r\n /** Diretório de saída do Next (default `.next`, relativo ao cwd do build). */\r\n outputDir?: string;\r\n}\r\n\r\n/**\r\n * Formato mínimo de `next.config.mjs` que o wrapper precisa entender — só\r\n * o suficiente pra compor a chave `webpack` sem acoplar o SDK ao pacote\r\n * `next` como dependência de tipos.\r\n */\r\ntype MinimalWebpackContext = {\r\n buildId: string;\r\n dev: boolean;\r\n isServer: boolean;\r\n [key: string]: unknown;\r\n};\r\ntype MinimalNextConfig = Record<string, unknown> & {\r\n webpack?: (config: unknown, context: MinimalWebpackContext) => unknown;\r\n};\r\n\r\nexport function withNeetruBuildGuard<T extends MinimalNextConfig>(\r\n nextConfig: T,\r\n options: WithNeetruBuildGuardOptions = {},\r\n): T {\r\n const prevWebpack = nextConfig.webpack;\r\n\r\n return {\r\n ...nextConfig,\r\n webpack(config: unknown, context: MinimalWebpackContext): unknown {\r\n const result = typeof prevWebpack === 'function' ? prevWebpack(config, context) : config;\r\n\r\n // Grava só na passada server (roda 1x por build, diferente da passada\r\n // client que pode rodar múltiplas vezes) e só fora de `next dev` —\r\n // `next build` é sempre produção de artefato de deploy.\r\n if (!context.dev && context.isServer) {\r\n try {\r\n const outDir = path.resolve(process.cwd(), options.outputDir ?? '.next');\r\n fs.mkdirSync(outDir, { recursive: true });\r\n const manifest: NeetruBuildManifest = {\r\n builtEnv: process.env.NEXT_PUBLIC_NEETRU_ENV ?? null,\r\n productId: process.env.NEXT_PUBLIC_NEETRU_PRODUCT_ID ?? null,\r\n oidcClientId: process.env.NEXT_PUBLIC_NEETRU_OIDC_CLIENT_ID ?? null,\r\n builtAt: new Date().toISOString(),\r\n };\r\n fs.writeFileSync(\r\n path.join(outDir, 'neetru-build-manifest.json'),\r\n JSON.stringify(manifest, null, 2),\r\n 'utf8',\r\n );\r\n } catch (err) {\r\n // Best-effort — o guard nunca pode quebrar o build do produto,\r\n // mas uma falha de escrita silenciosa aqui esconderia o problema\r\n // (achado da revisão: sem log, ninguém percebe que o manifesto não\r\n // foi gravado e `neetru build` trata \"manifesto ausente\" como\r\n // aviso, não bloqueio — visibilidade aqui é a única forma de notar).\r\n if (typeof console !== 'undefined') {\r\n console.warn(\r\n '[neetru-sdk] withNeetruBuildGuard: falha ao gravar neetru-build-manifest.json (ignorado, build segue):',\r\n err,\r\n );\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n },\r\n } as T;\r\n}\r\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -7122,7 +7122,7 @@ function createNeetruClient(config = {}) {
|
|
|
7122
7122
|
init_errors();
|
|
7123
7123
|
init_db_errors();
|
|
7124
7124
|
init_http();
|
|
7125
|
-
var VERSION = "3.1.
|
|
7125
|
+
var VERSION = "3.1.15";
|
|
7126
7126
|
|
|
7127
7127
|
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
|
|
7128
7128
|
exports.DEV_FIXTURE_USER = DEV_FIXTURE_USER;
|