strapi-typed-client 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -1
- package/dist/cli/commands/generate.d.ts.map +1 -1
- package/dist/cli/commands/generate.js +8 -25
- package/dist/cli/commands/generate.js.map +1 -1
- package/dist/cli/commands/init.d.ts +76 -0
- package/dist/cli/commands/init.d.ts.map +1 -0
- package/dist/cli/commands/init.js +400 -0
- package/dist/cli/commands/init.js.map +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +5 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/utils/file-writer.d.ts +12 -0
- package/dist/cli/utils/file-writer.d.ts.map +1 -1
- package/dist/cli/utils/file-writer.js +21 -0
- package/dist/cli/utils/file-writer.js.map +1 -1
- package/dist/cli/utils/prompt.d.ts +20 -0
- package/dist/cli/utils/prompt.d.ts.map +1 -0
- package/dist/cli/utils/prompt.js +119 -0
- package/dist/cli/utils/prompt.js.map +1 -0
- package/dist/generator/auth-api-generator.d.ts +3 -2
- package/dist/generator/auth-api-generator.d.ts.map +1 -1
- package/dist/generator/auth-api-generator.js +138 -15
- package/dist/generator/auth-api-generator.js.map +1 -1
- package/dist/generator/client-generator.d.ts +2 -1
- package/dist/generator/client-generator.d.ts.map +1 -1
- package/dist/generator/client-generator.js +278 -11
- package/dist/generator/client-generator.js.map +1 -1
- package/dist/generator/index.d.ts +2 -1
- package/dist/generator/index.d.ts.map +1 -1
- package/dist/generator/index.js +2 -2
- package/dist/generator/index.js.map +1 -1
- package/dist/plugin/server/src/index.d.ts +1 -0
- package/dist/plugin/server/src/index.d.ts.map +1 -1
- package/dist/plugin/server/src/services/schema.d.ts +6 -1
- package/dist/plugin/server/src/services/schema.d.ts.map +1 -1
- package/dist/plugin/server/src/services/schema.js +19 -3
- package/dist/plugin/server/src/services/schema.js.map +1 -1
- package/dist/shared/strapi-schema-types.d.ts +8 -0
- package/dist/shared/strapi-schema-types.d.ts.map +1 -1
- package/package.json +7 -5
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# strapi-typed-client
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/strapi-typed-client) [](https://deepwiki.com/BoxLab-Ltd/strapi-typed-client) [](https://gitmcp.io/BoxLab-Ltd/strapi-typed-client)
|
|
4
|
+
|
|
3
5
|
Automatic TypeScript type generation and a fully typed API client for **Strapi v5**. Install a Strapi plugin, run a single CLI command, and get clean TypeScript interfaces plus a ready-to-use fetch client with full autocomplete.
|
|
4
6
|
|
|
5
7
|
**[Documentation](https://boxlab-ltd.github.io/strapi-typed-client/)**
|
|
@@ -25,7 +27,14 @@ export default {
|
|
|
25
27
|
|
|
26
28
|
### 3. Generate types
|
|
27
29
|
|
|
28
|
-
|
|
30
|
+
Scaffold the workflow (adds `strapi:generate` / `strapi:check` scripts to your `package.json`), then generate into your source tree and commit the result:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npx strapi-types init
|
|
34
|
+
npm run strapi:generate
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or run the generator directly:
|
|
29
38
|
|
|
30
39
|
```bash
|
|
31
40
|
npx strapi-types generate --url http://localhost:1337 --output ./src/strapi
|
|
@@ -56,6 +65,7 @@ articles[0].category.name // fully typed
|
|
|
56
65
|
- Typed API client — `find`, `findOne`, `create`, `update`, `delete`
|
|
57
66
|
- Built-in upload plugin support — `client.upload.upload/find/findOne/destroy`
|
|
58
67
|
- Typed errors with `isStrapiErrorOf` for discriminated narrowing
|
|
68
|
+
- Session auth (Strapi 5.43+ `jwtManagement: 'refresh'`) — auto-detected, with transparent token refresh
|
|
59
69
|
- Automatic type inference for `populate` — no manual casting
|
|
60
70
|
- Nested populate with unlimited depth
|
|
61
71
|
- Separate Input types for create/update (relations as IDs)
|
|
@@ -66,6 +76,24 @@ articles[0].category.name // fully typed
|
|
|
66
76
|
- Schema hashing — skips regeneration when nothing changed
|
|
67
77
|
- Framework-agnostic — works with any TypeScript project
|
|
68
78
|
|
|
79
|
+
## Session auth (Strapi 5.43+)
|
|
80
|
+
|
|
81
|
+
When your backend runs users-permissions with `jwtManagement: 'refresh'` (short-lived access JWT + rotating refresh token in an httpOnly cookie), the generator detects it automatically and bakes the session flow into the client — no config needed:
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
const strapi = new StrapiClient({
|
|
85
|
+
baseURL: 'http://localhost:1337',
|
|
86
|
+
credentials: 'include', // let the refresh cookie travel
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
await strapi.auth.login({ identifier, password }) // access token kept in memory
|
|
90
|
+
await strapi.auth.refresh() // bootstrap the session on page load
|
|
91
|
+
await strapi.articles.find() // expired token? refreshed & retried transparently
|
|
92
|
+
await strapi.auth.logout() // revoke the session server-side
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
On a 401 — or a 403 from an anonymous request, which is what Strapi actually answers when a protected route is hit with no credentials (the page-reload bootstrap case) — the client performs a single-flight `POST /api/auth/refresh` and retries the request once; a dead session surfaces the original error. The flow is browser-only (server-side code keeps using API tokens) and steps aside whenever you manage the `Authorization` header yourself. Legacy backends are untouched — the generated client behaves exactly as before. See [Authentication](https://boxlab-ltd.github.io/strapi-typed-client/advanced/authentication) for details.
|
|
96
|
+
|
|
69
97
|
## Requirements
|
|
70
98
|
|
|
71
99
|
- **Strapi v5**
|
|
@@ -84,6 +112,26 @@ Full documentation is available at **[boxlab-ltd.github.io/strapi-typed-client](
|
|
|
84
112
|
- [Plugin Config](https://boxlab-ltd.github.io/strapi-typed-client/advanced/plugin-config) — requireAuth, endpoints, schema hashing
|
|
85
113
|
- [API Reference](https://boxlab-ltd.github.io/strapi-typed-client/reference/api) — full StrapiClient API
|
|
86
114
|
|
|
115
|
+
## Use with AI tools
|
|
116
|
+
|
|
117
|
+
The docs are published in agent-friendly formats so AI coding assistants answer questions about this library accurately:
|
|
118
|
+
|
|
119
|
+
- **llms.txt** — [`/llms.txt`](https://boxlab-ltd.github.io/strapi-typed-client/llms.txt) and [`/llms-full.txt`](https://boxlab-ltd.github.io/strapi-typed-client/llms-full.txt). Add the docs root `https://boxlab-ltd.github.io/strapi-typed-client/` to Cursor (`@Docs`), Continue (`@docs`), or any tool that indexes docs by URL.
|
|
120
|
+
- **context7** — indexed at [`/boxlab-ltd/strapi-typed-client`](https://context7.com/boxlab-ltd/strapi-typed-client); the docs site also embeds the context7 chat widget.
|
|
121
|
+
- **GitMCP** — point any MCP-capable agent at `https://gitmcp.io/BoxLab-Ltd/strapi-typed-client`:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"mcpServers": {
|
|
126
|
+
"strapi-typed-client": {
|
|
127
|
+
"url": "https://gitmcp.io/BoxLab-Ltd/strapi-typed-client"
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- **DeepWiki** — browse or query the auto-generated wiki at [deepwiki.com/BoxLab-Ltd/strapi-typed-client](https://deepwiki.com/BoxLab-Ltd/strapi-typed-client), or connect its MCP at `https://mcp.deepwiki.com/mcp`.
|
|
134
|
+
|
|
87
135
|
## Issues & Contributing
|
|
88
136
|
|
|
89
137
|
Found a bug or have a feature request? [Open an issue](https://github.com/BoxLab-Ltd/strapi-typed-client/issues) on GitHub.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/generate.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;
|
|
1
|
+
{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/generate.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAYxC,MAAM,WAAW,eAAe;IAC5B,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,IAAI,GAAG,IAAI,CAAA;IACpB,SAAS,CAAC,EAAE,OAAO,CAAA;CACtB;AAID,MAAM,WAAW,cAAc;IAC3B,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,OAAO,CAAA;CACpB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE;IAC3C,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3B,UAAU,EAAE,MAAM,CAAA;IAClB,aAAa,EAAE,OAAO,CAAA;CACzB,GAAG,OAAO,CAOV;AAED;;GAEG;AACH,wBAAsB,QAAQ,CAC1B,OAAO,EAAE,eAAe,GACzB,OAAO,CAAC,cAAc,CAAC,CAwLzB;AAYD;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA2D5D"}
|
|
@@ -4,31 +4,9 @@
|
|
|
4
4
|
import * as fs from 'fs';
|
|
5
5
|
import * as path from 'path';
|
|
6
6
|
import { createApiClient } from '../utils/api-client.js';
|
|
7
|
-
import { readLocalSchemaHash, readLocalGeneratorVersion, requireOutputDir, } from '../utils/file-writer.js';
|
|
8
|
-
import { Generator } from '../../generator/index.js';
|
|
7
|
+
import { readLocalSchemaHash, readLocalGeneratorVersion, requireOutputDir, isInsideNodeModules, assertOutputDirForFormat, } from '../utils/file-writer.js';
|
|
9
8
|
import { transformSchema } from '../../core/schema-transformer.js';
|
|
10
9
|
import { getGeneratorVersion } from '../../shared/version.js';
|
|
11
|
-
/**
|
|
12
|
-
* Output that lands inside node_modules is ephemeral — a reinstall wipes it,
|
|
13
|
-
* so the types must be regenerated. Used to bar `--format ts` from it and to
|
|
14
|
-
* nudge `--format js` users toward a durable, committable output directory.
|
|
15
|
-
*/
|
|
16
|
-
function isInsideNodeModules(outputDir) {
|
|
17
|
-
return path.resolve(outputDir).split(path.sep).includes('node_modules');
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Shipping raw .ts into node_modules breaks at runtime: Node can't require
|
|
21
|
-
* .ts files and the package.json exports still point at the missing .js.
|
|
22
|
-
* Force consumers to pick a source-tree output instead.
|
|
23
|
-
*/
|
|
24
|
-
function assertOutputDirForFormat(outputDir, format) {
|
|
25
|
-
if (format !== 'ts')
|
|
26
|
-
return;
|
|
27
|
-
if (isInsideNodeModules(outputDir)) {
|
|
28
|
-
throw new Error(`--format ts cannot write into node_modules (${outputDir}). ` +
|
|
29
|
-
`Point --output at your source tree (e.g. ./src/strapi).`);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
10
|
const dim = (s) => `\x1b[2m${s}\x1b[0m`;
|
|
33
11
|
/**
|
|
34
12
|
* Whether committed output can be reused without regenerating. Requires the
|
|
@@ -120,7 +98,7 @@ export async function generate(options) {
|
|
|
120
98
|
if (!options.silent) {
|
|
121
99
|
console.log(`Fetching schema from ${baseUrl}...`);
|
|
122
100
|
}
|
|
123
|
-
const { schema, endpoints: apiEndpoints, pluginEndpoints, extraTypes, hash, } = await client.getSchema();
|
|
101
|
+
const { schema, endpoints: apiEndpoints, pluginEndpoints, extraTypes, authMode, hash, } = await client.getSchema();
|
|
124
102
|
// Merge API and plugin endpoints for generation
|
|
125
103
|
const endpoints = [...(apiEndpoints || []), ...(pluginEndpoints || [])];
|
|
126
104
|
if (!options.silent) {
|
|
@@ -132,6 +110,9 @@ export async function generate(options) {
|
|
|
132
110
|
if (extraTypes && extraTypes.length > 0) {
|
|
133
111
|
console.log(` Extra types: ${extraTypes.length}`);
|
|
134
112
|
}
|
|
113
|
+
if (authMode === 'refresh') {
|
|
114
|
+
console.log(' Auth mode: refresh (session flow enabled)');
|
|
115
|
+
}
|
|
135
116
|
}
|
|
136
117
|
// Transform JSON schema to ParsedSchema format
|
|
137
118
|
const parsedSchema = transformSchema(schema);
|
|
@@ -139,8 +120,10 @@ export async function generate(options) {
|
|
|
139
120
|
if (!options.silent) {
|
|
140
121
|
console.log('Generating TypeScript types...');
|
|
141
122
|
}
|
|
123
|
+
// lazy: keeps the typescript compiler out of init/check/--help startup
|
|
124
|
+
const { Generator } = await import('../../generator/index.js');
|
|
142
125
|
const generator = new Generator(outputDir);
|
|
143
|
-
await generator.generate(parsedSchema, endpoints, extraTypes, hash, getGeneratorVersion(), format, options.typecheck ?? true);
|
|
126
|
+
await generator.generate(parsedSchema, endpoints, extraTypes, hash, getGeneratorVersion(), format, options.typecheck ?? true, authMode ?? 'legacy');
|
|
144
127
|
// Track generated files
|
|
145
128
|
const emittedFiles = format === 'ts'
|
|
146
129
|
? ['types.ts', 'client.ts', 'index.ts']
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../../src/cli/commands/generate.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AACxB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EACH,mBAAmB,EACnB,yBAAyB,EACzB,gBAAgB,
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../../src/cli/commands/generate.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AACxB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,OA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flow: validates the
|
|
3
|
+
* url/output/format choices and writes strapi:generate / strapi:check
|
|
4
|
+
* scripts into the consumer's package.json
|
|
5
|
+
*/
|
|
6
|
+
import type { Command } from 'commander';
|
|
7
|
+
import { type Prompter } from '../utils/prompt.js';
|
|
8
|
+
export interface InitOptions {
|
|
9
|
+
url?: string;
|
|
10
|
+
output?: string;
|
|
11
|
+
format?: string;
|
|
12
|
+
yes?: boolean;
|
|
13
|
+
force?: boolean;
|
|
14
|
+
silent?: boolean;
|
|
15
|
+
cwd?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ScriptConflict {
|
|
18
|
+
name: string;
|
|
19
|
+
current: string;
|
|
20
|
+
proposed: string;
|
|
21
|
+
}
|
|
22
|
+
export interface InitResult {
|
|
23
|
+
success: boolean;
|
|
24
|
+
error?: string;
|
|
25
|
+
packageJsonPath?: string;
|
|
26
|
+
scriptsAdded: string[];
|
|
27
|
+
scriptsOverwritten: string[];
|
|
28
|
+
scriptsSkipped: string[];
|
|
29
|
+
conflicts: ScriptConflict[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Validate a URL destined for a committed script. `new URL` alone accepts
|
|
33
|
+
* scheme-less strings like 'localhost:1337' ('localhost:' parses as the
|
|
34
|
+
* protocol), so the scheme must be checked explicitly.
|
|
35
|
+
*/
|
|
36
|
+
export declare function validateStrapiUrl(raw: string): string;
|
|
37
|
+
/**
|
|
38
|
+
* Normalize an output path for embedding into a committed script: POSIX
|
|
39
|
+
* separators and a ./ prefix so the script works for every teammate.
|
|
40
|
+
* Absolute paths are relativized against cwd (or rejected when outside it) —
|
|
41
|
+
* a committed absolute path only works on the machine that ran init.
|
|
42
|
+
*/
|
|
43
|
+
export declare function normalizeOutputForScript(output: string, cwd: string): string;
|
|
44
|
+
export interface InitScriptValues {
|
|
45
|
+
output: string;
|
|
46
|
+
format: 'js' | 'ts';
|
|
47
|
+
url?: string;
|
|
48
|
+
}
|
|
49
|
+
export declare function buildInitScripts(values: InitScriptValues): Record<string, string>;
|
|
50
|
+
export interface ApplyScriptsResult {
|
|
51
|
+
content: string;
|
|
52
|
+
changed: boolean;
|
|
53
|
+
added: string[];
|
|
54
|
+
overwritten: string[];
|
|
55
|
+
skipped: string[];
|
|
56
|
+
conflicts: ScriptConflict[];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Add scripts to a package.json string while keeping the file's own dialect
|
|
60
|
+
* (BOM, CRLF, indent, trailing newline) so the resulting diff is only the
|
|
61
|
+
* added lines. Returns the original content untouched when nothing changed,
|
|
62
|
+
* which is what makes re-runs byte-identical.
|
|
63
|
+
*/
|
|
64
|
+
export declare function applyScriptsToPackageJson(raw: string, scripts: Record<string, string>, force: boolean): ApplyScriptsResult;
|
|
65
|
+
/**
|
|
66
|
+
* Scaffold the committed-codegen setup. Never throws and never exits — errors
|
|
67
|
+
* come back in the result (exit codes live in the commander wrapper).
|
|
68
|
+
* `prompter` is injectable for tests; the terminal implementation is only
|
|
69
|
+
* created when prompting will actually happen.
|
|
70
|
+
*/
|
|
71
|
+
export declare function init(options: InitOptions, prompter?: Prompter): Promise<InitResult>;
|
|
72
|
+
/**
|
|
73
|
+
* CLI handler for init command
|
|
74
|
+
*/
|
|
75
|
+
export declare function createInitCommand(program: Command): void;
|
|
76
|
+
//# sourceMappingURL=init.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/cli/commands/init.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAExC,OAAO,EAOH,KAAK,QAAQ,EAEhB,MAAM,oBAAoB,CAAA;AAE3B,MAAM,WAAW,WAAW;IACxB,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,K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,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/B,KAAK,EAAE,OAAO,GACf,kBAAkB,CA0EpB;AAkHD;;;;;GAKG;AACH,wBAAsB,IAAI,CACtB,OAAO,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACpB,OAAO,CAAC,UAAU,CAAC,CA6KrB;AAWD;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA0CxD"}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Init command - scaffolds the committed-codegen workflow: validates the
|
|
3
|
+
* url/output/format choices and writes strapi:generate / strapi:check
|
|
4
|
+
* scripts into the consumer's package.json
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from 'fs';
|
|
7
|
+
import * as path from 'path';
|
|
8
|
+
import { isInsideNodeModules } from '../utils/file-writer.js';
|
|
9
|
+
import { bold, cyan, dim, green, yellow, createTerminalPrompter, } from '../utils/prompt.js';
|
|
10
|
+
const DEFAULT_URL = 'http://localhost:1337';
|
|
11
|
+
const DEFAULT_OUTPUT = './src/strapi';
|
|
12
|
+
/**
|
|
13
|
+
* Validate a URL destined for a committed script. `new URL` alone accepts
|
|
14
|
+
* scheme-less strings like 'localhost:1337' ('localhost:' parses as the
|
|
15
|
+
* protocol), so the scheme must be checked explicitly.
|
|
16
|
+
*/
|
|
17
|
+
export function validateStrapiUrl(raw) {
|
|
18
|
+
const url = raw.trim().replace(/\/+$/, '');
|
|
19
|
+
let parsed;
|
|
20
|
+
try {
|
|
21
|
+
parsed = new URL(url);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
parsed = undefined;
|
|
25
|
+
}
|
|
26
|
+
if (!parsed ||
|
|
27
|
+
(parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
|
|
28
|
+
throw new Error(`Invalid Strapi URL "${raw.trim()}" — it must start with http:// or https:// (e.g. ${DEFAULT_URL}).`);
|
|
29
|
+
}
|
|
30
|
+
return url;
|
|
31
|
+
}
|
|
32
|
+
function isDefaultUrl(url) {
|
|
33
|
+
return new URL(url).href === new URL(DEFAULT_URL).href;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Normalize an output path for embedding into a committed script: POSIX
|
|
37
|
+
* separators and a ./ prefix so the script works for every teammate.
|
|
38
|
+
* Absolute paths are relativized against cwd (or rejected when outside it) —
|
|
39
|
+
* a committed absolute path only works on the machine that ran init.
|
|
40
|
+
*/
|
|
41
|
+
export function normalizeOutputForScript(output, cwd) {
|
|
42
|
+
const raw = output.trim();
|
|
43
|
+
if (path.isAbsolute(raw)) {
|
|
44
|
+
const rel = path.relative(cwd, raw);
|
|
45
|
+
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
46
|
+
throw new Error(`--output must be inside your project (got ${raw}). ` +
|
|
47
|
+
`Use a relative path in your source tree, e.g. ${DEFAULT_OUTPUT}.`);
|
|
48
|
+
}
|
|
49
|
+
return toPosixRelative(rel === '' ? '.' : rel);
|
|
50
|
+
}
|
|
51
|
+
return toPosixRelative(raw);
|
|
52
|
+
}
|
|
53
|
+
function toPosixRelative(p) {
|
|
54
|
+
const posix = p.replace(/\\/g, '/');
|
|
55
|
+
if (posix === '.' ||
|
|
56
|
+
posix === '..' ||
|
|
57
|
+
posix.startsWith('./') ||
|
|
58
|
+
posix.startsWith('../')) {
|
|
59
|
+
return posix;
|
|
60
|
+
}
|
|
61
|
+
return `./${posix}`;
|
|
62
|
+
}
|
|
63
|
+
export function buildInitScripts(values) {
|
|
64
|
+
// quote by allowlist, not just whitespace — npm run hands these to sh/cmd
|
|
65
|
+
const arg = (v) => (/^[A-Za-z0-9_./:@=-]+$/.test(v) ? v : `"${v}"`);
|
|
66
|
+
const output = ` --output ${arg(values.output)}`;
|
|
67
|
+
const format = values.format === 'ts' ? ' --format ts' : '';
|
|
68
|
+
const url = values.url ? ` --url ${arg(values.url)}` : '';
|
|
69
|
+
return {
|
|
70
|
+
'strapi:generate': `strapi-types generate${output}${format}${url}`,
|
|
71
|
+
'strapi:check': `strapi-types check${output}${url}`,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function stripBom(raw) {
|
|
75
|
+
return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Add scripts to a package.json string while keeping the file's own dialect
|
|
79
|
+
* (BOM, CRLF, indent, trailing newline) so the resulting diff is only the
|
|
80
|
+
* added lines. Returns the original content untouched when nothing changed,
|
|
81
|
+
* which is what makes re-runs byte-identical.
|
|
82
|
+
*/
|
|
83
|
+
export function applyScriptsToPackageJson(raw, scripts, force) {
|
|
84
|
+
const body = stripBom(raw);
|
|
85
|
+
const bom = raw.slice(0, raw.length - body.length);
|
|
86
|
+
let pkg;
|
|
87
|
+
try {
|
|
88
|
+
pkg = JSON.parse(body);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new Error('package.json is not valid JSON — fix it and re-run init.');
|
|
92
|
+
}
|
|
93
|
+
if (typeof pkg !== 'object' || pkg === null || Array.isArray(pkg)) {
|
|
94
|
+
throw new Error('package.json must contain a JSON object at the top level.');
|
|
95
|
+
}
|
|
96
|
+
const record = pkg;
|
|
97
|
+
if (record.scripts !== undefined &&
|
|
98
|
+
(typeof record.scripts !== 'object' ||
|
|
99
|
+
record.scripts === null ||
|
|
100
|
+
Array.isArray(record.scripts))) {
|
|
101
|
+
throw new Error('package.json has a non-object "scripts" field — fix it and re-run init.');
|
|
102
|
+
}
|
|
103
|
+
const target = record.scripts ?? {};
|
|
104
|
+
record.scripts = target;
|
|
105
|
+
const added = [];
|
|
106
|
+
const overwritten = [];
|
|
107
|
+
const skipped = [];
|
|
108
|
+
const conflicts = [];
|
|
109
|
+
for (const [name, proposed] of Object.entries(scripts)) {
|
|
110
|
+
const current = target[name];
|
|
111
|
+
if (current === undefined) {
|
|
112
|
+
target[name] = proposed;
|
|
113
|
+
added.push(name);
|
|
114
|
+
}
|
|
115
|
+
else if (current === proposed) {
|
|
116
|
+
skipped.push(name);
|
|
117
|
+
}
|
|
118
|
+
else if (force) {
|
|
119
|
+
target[name] = proposed;
|
|
120
|
+
overwritten.push(name);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
conflicts.push({ name, current: String(current), proposed });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const changed = added.length > 0 || overwritten.length > 0;
|
|
127
|
+
if (!changed) {
|
|
128
|
+
return { content: raw, changed, added, overwritten, skipped, conflicts };
|
|
129
|
+
}
|
|
130
|
+
const eol = body.includes('\r\n') ? '\r\n' : '\n';
|
|
131
|
+
const indent = body.match(/^([ \t]+)"/m)?.[1] ?? ' ';
|
|
132
|
+
let out = JSON.stringify(pkg, null, indent);
|
|
133
|
+
if (eol === '\r\n') {
|
|
134
|
+
out = out.replace(/\n/g, eol);
|
|
135
|
+
}
|
|
136
|
+
if (/\r?\n$/.test(body)) {
|
|
137
|
+
out += eol;
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
content: bom + out,
|
|
141
|
+
changed,
|
|
142
|
+
added,
|
|
143
|
+
overwritten,
|
|
144
|
+
skipped,
|
|
145
|
+
conflicts,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
function normalizeFormat(raw) {
|
|
149
|
+
const value = raw.trim().toLowerCase();
|
|
150
|
+
return value === 'js' || value === 'ts' ? value : null;
|
|
151
|
+
}
|
|
152
|
+
function resolveOutput(rawOutput, cwd) {
|
|
153
|
+
if (!rawOutput.trim()) {
|
|
154
|
+
throw new Error(`No output directory specified. Pass --output pointing at your source tree, e.g. --output ${DEFAULT_OUTPUT}.`);
|
|
155
|
+
}
|
|
156
|
+
const normalized = normalizeOutputForScript(rawOutput, cwd);
|
|
157
|
+
if (isInsideNodeModules(path.resolve(cwd, normalized))) {
|
|
158
|
+
throw new Error(`init sets up committed codegen — --output cannot point inside node_modules (${rawOutput.trim()}). ` +
|
|
159
|
+
`Choose a directory in your source tree, e.g. ${DEFAULT_OUTPUT}.`);
|
|
160
|
+
}
|
|
161
|
+
return normalized;
|
|
162
|
+
}
|
|
163
|
+
const FORMAT_CHOICES = [
|
|
164
|
+
{ value: 'js', label: 'js', hint: 'compiled .js + .d.ts, no build step' },
|
|
165
|
+
{ value: 'ts', label: 'ts', hint: 'raw .ts for bundlers and monorepos' },
|
|
166
|
+
];
|
|
167
|
+
function askFormat(prompter) {
|
|
168
|
+
return prompter.select('Output format', FORMAT_CHOICES, 'js');
|
|
169
|
+
}
|
|
170
|
+
async function askOutput(prompter, cwd) {
|
|
171
|
+
for (;;) {
|
|
172
|
+
const answer = (await prompter.text('Output directory', DEFAULT_OUTPUT)).trim();
|
|
173
|
+
try {
|
|
174
|
+
return resolveOutput(answer === '' ? DEFAULT_OUTPUT : answer, cwd);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
console.error(error.message);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Returns undefined when the user accepts the bracket default (empty answer):
|
|
183
|
+
* env-derived and default URLs must stay out of committed scripts, otherwise
|
|
184
|
+
* one developer's STRAPI_URL gets frozen for the whole team and shadows env
|
|
185
|
+
* at generate time (flags take precedence over env).
|
|
186
|
+
*/
|
|
187
|
+
async function askUrl(prompter) {
|
|
188
|
+
const shown = process.env.STRAPI_URL || DEFAULT_URL;
|
|
189
|
+
for (;;) {
|
|
190
|
+
const answer = (await prompter.text('Strapi URL', shown)).trim();
|
|
191
|
+
if (answer === '')
|
|
192
|
+
return undefined;
|
|
193
|
+
try {
|
|
194
|
+
return validateStrapiUrl(answer);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
console.error(error.message);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
function detectPackageManager(pkg) {
|
|
202
|
+
const pm = typeof pkg.packageManager === 'string' ? pkg.packageManager : '';
|
|
203
|
+
if (pm.startsWith('yarn')) {
|
|
204
|
+
return { install: 'yarn add -D', run: s => `yarn ${s}` };
|
|
205
|
+
}
|
|
206
|
+
if (pm.startsWith('pnpm')) {
|
|
207
|
+
return { install: 'pnpm add -D', run: s => `pnpm ${s}` };
|
|
208
|
+
}
|
|
209
|
+
if (pm.startsWith('bun')) {
|
|
210
|
+
return { install: 'bun add -d', run: s => `bun run ${s}` };
|
|
211
|
+
}
|
|
212
|
+
return { install: 'npm install -D', run: s => `npm run ${s}` };
|
|
213
|
+
}
|
|
214
|
+
function hasDependency(pkg, name) {
|
|
215
|
+
for (const key of ['dependencies', 'devDependencies']) {
|
|
216
|
+
const deps = pkg[key];
|
|
217
|
+
if (deps && typeof deps === 'object' && name in deps)
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
function printNextSteps(pkg, output) {
|
|
223
|
+
const pm = detectPackageManager(pkg);
|
|
224
|
+
const steps = [];
|
|
225
|
+
if (!hasDependency(pkg, 'strapi-typed-client')) {
|
|
226
|
+
steps.push(`Install the package: ${pm.install} strapi-typed-client`);
|
|
227
|
+
}
|
|
228
|
+
steps.push(`Enable the plugin in your Strapi project: config/plugins.ts → 'strapi-typed-client': { enabled: true }`, `With Strapi running: ${pm.run('strapi:generate')}`, `Commit the generated directory (${output})`);
|
|
229
|
+
console.log(`\n${bold('Next steps:')}`);
|
|
230
|
+
steps.forEach((step, i) => console.log(` ${cyan(`${i + 1}.`)} ${step}`));
|
|
231
|
+
console.log('\n' +
|
|
232
|
+
dim('Tips: set STRAPI_TOKEN if the schema API requires auth. ' +
|
|
233
|
+
'During development `strapi-types watch` regenerates on schema changes. ' +
|
|
234
|
+
'Next.js: the withStrapiTypes wrapper regenerates automatically on dev/build ' +
|
|
235
|
+
'(https://boxlab-ltd.github.io/strapi-typed-client/guide/nextjs) — ' +
|
|
236
|
+
'the scripts above remain useful for CI checks and manual runs.'));
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Scaffold the committed-codegen setup. Never throws and never exits — errors
|
|
240
|
+
* come back in the result (exit codes live in the commander wrapper).
|
|
241
|
+
* `prompter` is injectable for tests; the terminal implementation is only
|
|
242
|
+
* created when prompting will actually happen.
|
|
243
|
+
*/
|
|
244
|
+
export async function init(options, prompter) {
|
|
245
|
+
const fail = (error) => ({
|
|
246
|
+
success: false,
|
|
247
|
+
error,
|
|
248
|
+
scriptsAdded: [],
|
|
249
|
+
scriptsOverwritten: [],
|
|
250
|
+
scriptsSkipped: [],
|
|
251
|
+
conflicts: [],
|
|
252
|
+
});
|
|
253
|
+
const cwd = options.cwd ?? process.cwd();
|
|
254
|
+
const packageJsonPath = path.join(cwd, 'package.json');
|
|
255
|
+
let raw;
|
|
256
|
+
try {
|
|
257
|
+
raw = fs.readFileSync(packageJsonPath, 'utf-8');
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (error.code === 'ENOENT') {
|
|
261
|
+
return fail(`No package.json found in ${cwd}. Run strapi-types init from your project root.`);
|
|
262
|
+
}
|
|
263
|
+
return fail(`Could not read ${packageJsonPath}: ${error.message}`);
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
JSON.parse(stripBom(raw));
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
return fail('package.json is not valid JSON — fix it and re-run init.');
|
|
270
|
+
}
|
|
271
|
+
// Validate flag-provided values up front so a typo'd flag fails fast
|
|
272
|
+
// instead of after the user has answered the interactive prompts
|
|
273
|
+
let scriptUrl;
|
|
274
|
+
if (options.url !== undefined) {
|
|
275
|
+
try {
|
|
276
|
+
scriptUrl = validateStrapiUrl(options.url);
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
return fail(error.message);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
let output;
|
|
283
|
+
if (options.output !== undefined) {
|
|
284
|
+
try {
|
|
285
|
+
output = resolveOutput(options.output, cwd);
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
return fail(error.message);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
let format;
|
|
292
|
+
if (options.format !== undefined) {
|
|
293
|
+
const value = normalizeFormat(options.format);
|
|
294
|
+
if (!value) {
|
|
295
|
+
return fail(`Invalid --format value: ${options.format}. Expected 'js' or 'ts'.`);
|
|
296
|
+
}
|
|
297
|
+
format = value;
|
|
298
|
+
}
|
|
299
|
+
const wantsPrompt = !options.yes && !options.silent;
|
|
300
|
+
const canPrompt = prompter !== undefined ||
|
|
301
|
+
(process.stdin.isTTY === true && process.stdout.isTTY === true);
|
|
302
|
+
const missing = options.url === undefined ||
|
|
303
|
+
options.output === undefined ||
|
|
304
|
+
options.format === undefined;
|
|
305
|
+
if (wantsPrompt && !canPrompt && missing && !options.silent) {
|
|
306
|
+
console.log('Non-interactive terminal — using defaults (pass --url/--output/--format or -y to silence this).');
|
|
307
|
+
}
|
|
308
|
+
const prompting = wantsPrompt && canPrompt && missing;
|
|
309
|
+
const prompts = prompter ?? (prompting ? createTerminalPrompter() : undefined);
|
|
310
|
+
if (prompting && !options.silent) {
|
|
311
|
+
console.log(`\n${bold('strapi-types init')} ${dim('— committed-codegen setup')}`);
|
|
312
|
+
}
|
|
313
|
+
if (options.url === undefined && prompting && prompts) {
|
|
314
|
+
scriptUrl = await askUrl(prompts);
|
|
315
|
+
}
|
|
316
|
+
if (scriptUrl && isDefaultUrl(scriptUrl)) {
|
|
317
|
+
scriptUrl = undefined;
|
|
318
|
+
}
|
|
319
|
+
if (output === undefined) {
|
|
320
|
+
output =
|
|
321
|
+
prompting && prompts
|
|
322
|
+
? await askOutput(prompts, cwd)
|
|
323
|
+
: DEFAULT_OUTPUT;
|
|
324
|
+
}
|
|
325
|
+
if (format === undefined) {
|
|
326
|
+
format = prompting && prompts ? await askFormat(prompts) : 'js';
|
|
327
|
+
}
|
|
328
|
+
if (scriptUrl &&
|
|
329
|
+
new URL(scriptUrl).pathname.endsWith('/api') &&
|
|
330
|
+
!options.silent) {
|
|
331
|
+
console.warn(`${yellow('▲')} Note: the URL should be the Strapi root, not .../api (got ${scriptUrl}).`);
|
|
332
|
+
}
|
|
333
|
+
const scripts = buildInitScripts({ output, format, url: scriptUrl });
|
|
334
|
+
let applied;
|
|
335
|
+
try {
|
|
336
|
+
applied = applyScriptsToPackageJson(raw, scripts, options.force ?? false);
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
return fail(error.message);
|
|
340
|
+
}
|
|
341
|
+
if (applied.changed) {
|
|
342
|
+
try {
|
|
343
|
+
fs.writeFileSync(packageJsonPath, applied.content, 'utf-8');
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
return fail(`Could not write ${packageJsonPath}: ${error.message}`);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (applied.conflicts.length > 0) {
|
|
350
|
+
// stderr on purpose: --silent must not be able to hide a not-applied state
|
|
351
|
+
console.error(`${yellow('▲')} Existing scripts in ${packageJsonPath} differ from what init proposes:`);
|
|
352
|
+
for (const conflict of applied.conflicts) {
|
|
353
|
+
console.error(` "${conflict.name}"\n current: ${conflict.current}\n proposed: ${conflict.proposed}`);
|
|
354
|
+
}
|
|
355
|
+
console.error('Re-run with --force to overwrite them.');
|
|
356
|
+
}
|
|
357
|
+
if (!options.silent) {
|
|
358
|
+
const touched = [...applied.added, ...applied.overwritten];
|
|
359
|
+
if (touched.length > 0) {
|
|
360
|
+
console.log(`${green('✔')} Updated ${packageJsonPath}: ${touched.map(n => `"${n}"`).join(', ')}`);
|
|
361
|
+
}
|
|
362
|
+
else if (applied.conflicts.length === 0) {
|
|
363
|
+
console.log(`${green('✔')} Already configured — ${packageJsonPath} left untouched.`);
|
|
364
|
+
}
|
|
365
|
+
printNextSteps(JSON.parse(stripBom(raw)), output);
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
success: true,
|
|
369
|
+
packageJsonPath,
|
|
370
|
+
scriptsAdded: applied.added,
|
|
371
|
+
scriptsOverwritten: applied.overwritten,
|
|
372
|
+
scriptsSkipped: applied.skipped,
|
|
373
|
+
conflicts: applied.conflicts,
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* CLI handler for init command
|
|
378
|
+
*/
|
|
379
|
+
export function createInitCommand(program) {
|
|
380
|
+
program
|
|
381
|
+
.command('init')
|
|
382
|
+
.description('Set up the committed-codegen workflow: add strapi:generate / strapi:check scripts to package.json')
|
|
383
|
+
.option('-u, --url <url>', `Strapi API URL to bake into the scripts (omit to rely on STRAPI_URL env or ${DEFAULT_URL})`)
|
|
384
|
+
.option('-o, --output <path>', `Output directory for generated types (default: ${DEFAULT_OUTPUT})`)
|
|
385
|
+
.option('--format <js|ts>', 'Output format: js (compiled .js + .d.ts, default) or ts (raw .ts for bundlers/monorepos)')
|
|
386
|
+
.option('-y, --yes', 'Accept defaults for any option not passed; never prompt')
|
|
387
|
+
.option('-f, --force', 'Overwrite conflicting strapi:* scripts in package.json (other keys are never touched)')
|
|
388
|
+
.option('-s, --silent', 'Suppress output messages (also skips prompts, like --yes)')
|
|
389
|
+
.action(async (opts) => {
|
|
390
|
+
const result = await init(opts);
|
|
391
|
+
if (!result.success) {
|
|
392
|
+
console.error('Init failed:', result.error);
|
|
393
|
+
process.exit(1);
|
|
394
|
+
}
|
|
395
|
+
if (result.conflicts.length > 0) {
|
|
396
|
+
process.exit(1);
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
//# sourceMappingURL=init.js.map
|