@farm.js/strapi 0.1.72 → 0.1.74

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 CHANGED
@@ -42,6 +42,42 @@ A missing API URL fails while configuration loads instead of on the first conten
42
42
 
43
43
  Build the client once and reuse it in the integration and application server code.
44
44
 
45
+ When the Farm and Strapi projects share a repository, generate a declaration from Strapi's local
46
+ schemas:
47
+
48
+ ```json
49
+ {
50
+ "scripts": {
51
+ "strapi:types": "farm-strapi generate --strapi-root ../cms --output src/strapi.generated.d.ts",
52
+ "strapi:types:check": "farm-strapi generate --strapi-root ../cms --output src/strapi.generated.d.ts --check"
53
+ }
54
+ }
55
+ ```
56
+
57
+ Run `pnpm strapi:types` after a content model changes and commit the generated declaration. The
58
+ resource name and literal `fields` and `populate` arguments then determine each response type:
59
+
60
+ ```ts
61
+ import { createStrapiClient, createStrapiCollection, resolveStrapiConfig } from "@farm.js/strapi";
62
+
63
+ export const cms = createStrapiClient(resolveStrapiConfig({}));
64
+ export const articles = createStrapiCollection(cms, "articles");
65
+
66
+ const posts = await articles.find({
67
+ fields: ["title", "slug"],
68
+ populate: ["cover", "category"],
69
+ });
70
+ ```
71
+
72
+ Unpopulated relations and media are absent from the result type. Top-level population is inferred;
73
+ deep object or dotted-path population is deliberately `unknown` and must be validated at the
74
+ server-query boundary.
75
+ `--check` never writes and exits unsuccessfully when the declaration is missing or stale, so it can
76
+ run in CI. The generator reads only local `src/api/**/schema.json` and `src/components/**/*.json`
77
+ files and is available programmatically from the server-only `@farm.js/strapi/schema` entry.
78
+
79
+ You can still supply a manual document type when the Strapi project is not available locally:
80
+
45
81
  ```ts
46
82
  // src/lib/cms.server.ts
47
83
  import {
@@ -88,7 +124,7 @@ export const postsQuery = createServerQuery({
88
124
  });
89
125
  ```
90
126
 
91
- The generic describes the fields your application expects. Keep runtime validation on the server
127
+ The generated or manual type is a compile-time contract. Keep runtime validation on the server
92
128
  query boundary because Strapi's returned fields still depend on permissions and `populate`.
93
129
 
94
130
  ## Invalidate on publish
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+ import { generateStrapiTypes } from "./schema.js";
4
+ const usage = `Usage: farm-strapi generate [options]
5
+
6
+ Options:
7
+ --strapi-root <directory> Strapi project root (default: current directory)
8
+ --output <file> Generated declaration (default: src/strapi.generated.d.ts)
9
+ --check Fail when the declaration is stale or missing
10
+ --help Show this help`;
11
+ function takeValue(args, index, option) {
12
+ const value = args[index + 1];
13
+ if (!value || value.startsWith("--"))
14
+ throw new Error(`${option} requires a value`);
15
+ args.splice(index, 2);
16
+ return value;
17
+ }
18
+ async function main() {
19
+ const args = process.argv.slice(2);
20
+ if (args.includes("--help") || args.includes("-h")) {
21
+ process.stdout.write(`${usage}\n`);
22
+ return;
23
+ }
24
+ if (args.shift() !== "generate")
25
+ throw new Error(usage);
26
+ let strapiRoot = process.cwd();
27
+ let output = "src/strapi.generated.d.ts";
28
+ let check = false;
29
+ for (let index = 0; index < args.length;) {
30
+ const option = args[index];
31
+ if (option === "--strapi-root") {
32
+ strapiRoot = takeValue(args, index, option);
33
+ }
34
+ else if (option === "--output") {
35
+ output = takeValue(args, index, option);
36
+ }
37
+ else if (option === "--check") {
38
+ check = true;
39
+ args.splice(index, 1);
40
+ }
41
+ else {
42
+ throw new Error(`Unknown option: ${option}\n\n${usage}`);
43
+ }
44
+ }
45
+ const result = await generateStrapiTypes({ strapiRoot, outFile: output, check });
46
+ process.stdout.write(`${check ? "Verified" : result.changed ? "Generated" : "Unchanged"} ${result.outFile} (${result.contentTypes} content types, ${result.components} components)\n`);
47
+ }
48
+ main().catch((error) => {
49
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
50
+ process.exitCode = 1;
51
+ });
package/dist/image.d.ts CHANGED
@@ -3,10 +3,16 @@ export interface StrapiMediaFormat {
3
3
  width: number;
4
4
  height: number;
5
5
  }
6
- export interface StrapiMediaAsset extends StrapiMediaFormat {
6
+ /** A populated Strapi upload, including non-image files without dimensions. */
7
+ export interface StrapiMediaFile {
8
+ url: string;
9
+ width?: number | null;
10
+ height?: number | null;
7
11
  alternativeText?: string | null;
8
12
  formats?: Record<string, StrapiMediaFormat | null | undefined> | null;
9
13
  }
14
+ /** A Strapi image upload with dimensions suitable for `getStrapiImageProps`. */
15
+ export type StrapiMediaAsset = StrapiMediaFile & StrapiMediaFormat;
10
16
  export interface StrapiImageOptions {
11
17
  /** Public media origin used to resolve relative upload URLs. */
12
18
  mediaUrl?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../src/image.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAiB,SAAQ,iBAAiB;IACzD,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC;CACvE;AAED,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,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AAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC;IAC1B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAqCD;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,kBAAuB,GAC/B,gBAAgB,CAiClB"}
package/dist/index.d.ts CHANGED
@@ -11,9 +11,10 @@ export { createStrapiClient } from "./client.js";
11
11
  export { DEFAULT_STRAPI_WEBHOOK_PATH, DEFAULT_STRAPI_WEBHOOK_SECRET_HEADER, resolveStrapiConfig, } from "./config.js";
12
12
  export type { ResolvedStrapiConfig, StrapiIntegrationInput, StrapiWebhookChange, StrapiWebhookOptions, } from "./config.js";
13
13
  export { getStrapiImageProps } from "./image.js";
14
- export type { StrapiImageOptions, StrapiImageProps, StrapiMediaAsset, StrapiMediaFormat, } from "./image.js";
14
+ export type { StrapiImageOptions, StrapiImageProps, StrapiMediaAsset, StrapiMediaFile, StrapiMediaFormat, } from "./image.js";
15
15
  export { createStrapiCollection } from "./query.js";
16
16
  export type { StrapiDocument, StrapiQueryParams, TypedStrapiCollection } from "./query.js";
17
+ export type { GeneratedStrapiCollection, StrapiComponent, StrapiContentTypeDefinition, StrapiDynamicZone, StrapiGeneratedDocument, StrapiGeneratedDocumentMetadata, StrapiGeneratedQuery, StrapiGeneratedResource, StrapiMedia, StrapiPopulateField, StrapiRelation, StrapiUnknownPopulate, } from "./schema-types.js";
17
18
  export { applyStrapiWebhookChange, createStrapiWebhookRoute } from "./webhook.js";
18
19
  export type { StrapiWebhookInvalidation, StrapiWebhookRouteOptions } from "./webhook.js";
19
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC;AAGrB,wBAAgB,MAAM,CAAC,KAAK,GAAE,sBAA2B;;;;;;;mDAuBxD;AAED,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,2BAA2B,EAC3B,oCAAoC,EACpC,mBAAmB,GACpB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,oBAAoB,EACpB,sBAAsB,EACtB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,YAAY,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,GAClB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,YAAY,EAAE,cAAc,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAC3F,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAClF,YAAY,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC;AAGrB,wBAAgB,MAAM,CAAC,KAAK,GAAE,sBAA2B;;;;;;;mDAuBxD;AAED,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EACL,2BAA2B,EAC3B,oCAAoC,EACpC,mBAAmB,GACpB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,oBAAoB,EACpB,sBAAsB,EACtB,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,YAAY,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,iBAAiB,GAClB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,YAAY,EAAE,cAAc,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAC3F,YAAY,EACV,yBAAyB,EACzB,eAAe,EACf,2BAA2B,EAC3B,iBAAiB,EACjB,uBAAuB,EACvB,+BAA+B,EAC/B,oBAAoB,EACpB,uBAAuB,EACvB,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,qBAAqB,GACtB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAClF,YAAY,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC"}
package/dist/query.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { API, StrapiClient } from "@strapi/client";
2
+ import type { GeneratedStrapiCollection, StrapiGeneratedResource } from "./schema-types.js";
2
3
  export type StrapiQueryParams = API.BaseQueryParams;
3
4
  export type StrapiDocument = API.Document;
4
5
  export interface TypedStrapiCollection<TDocument extends StrapiDocument> {
@@ -10,5 +11,7 @@ export interface TypedStrapiCollection<TDocument extends StrapiDocument> {
10
11
  * unwraps the REST `data` envelope. Use the returned methods inside
11
12
  * `createServerQuery` so provider credentials remain on the server.
12
13
  */
13
- export declare function createStrapiCollection<TDocument extends StrapiDocument = StrapiDocument>(client: StrapiClient, resource: string): TypedStrapiCollection<TDocument>;
14
+ export declare function createStrapiCollection<const TResource extends StrapiGeneratedResource>(client: StrapiClient, resource: TResource): GeneratedStrapiCollection<TResource>;
15
+ export declare function createStrapiCollection<TDocument extends StrapiDocument>(client: StrapiClient, resource: string): TypedStrapiCollection<TDocument>;
16
+ export declare function createStrapiCollection(client: StrapiClient, resource: string): TypedStrapiCollection<StrapiDocument>;
14
17
  //# sourceMappingURL=query.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAExD,MAAM,MAAM,iBAAiB,GAAG,GAAG,CAAC,eAAe,CAAC;AACpD,MAAM,MAAM,cAAc,GAAG,GAAG,CAAC,QAAQ,CAAC;AAE1C,MAAM,WAAW,qBAAqB,CAAC,SAAS,SAAS,cAAc;IACrE,IAAI,CAAC,KAAK,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IACtD,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CAC5E;AA4BD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,SAAS,cAAc,GAAG,cAAc,EACtF,MAAM,EAAE,YAAY,EACpB,QAAQ,EAAE,MAAM,GACf,qBAAqB,CAAC,SAAS,CAAC,CAsBlC"}
1
+ {"version":3,"file":"query.d.ts","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5F,MAAM,MAAM,iBAAiB,GAAG,GAAG,CAAC,eAAe,CAAC;AACpD,MAAM,MAAM,cAAc,GAAG,GAAG,CAAC,QAAQ,CAAC;AAE1C,MAAM,WAAW,qBAAqB,CAAC,SAAS,SAAS,cAAc;IACrE,IAAI,CAAC,KAAK,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IACtD,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CAC5E;AA4BD;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,CAAC,SAAS,SAAS,uBAAuB,EACpF,MAAM,EAAE,YAAY,EACpB,QAAQ,EAAE,SAAS,GAClB,yBAAyB,CAAC,SAAS,CAAC,CAAC;AACxC,wBAAgB,sBAAsB,CAAC,SAAS,SAAS,cAAc,EACrE,MAAM,EAAE,YAAY,EACpB,QAAQ,EAAE,MAAM,GACf,qBAAqB,CAAC,SAAS,CAAC,CAAC;AACpC,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,YAAY,EACpB,QAAQ,EAAE,MAAM,GACf,qBAAqB,CAAC,cAAc,CAAC,CAAC"}
package/dist/query.js CHANGED
@@ -15,11 +15,6 @@ function assertDocument(value, operation) {
15
15
  throw new TypeError(`${operation} received a response without a Strapi document`);
16
16
  }
17
17
  }
18
- /**
19
- * Adds an application-owned document type to the official Strapi manager and
20
- * unwraps the REST `data` envelope. Use the returned methods inside
21
- * `createServerQuery` so provider credentials remain on the server.
22
- */
23
18
  export function createStrapiCollection(client, resource) {
24
19
  assertResourceName(resource);
25
20
  const manager = client.collection(resource);
@@ -0,0 +1,97 @@
1
+ import type { API } from "@strapi/client";
2
+ import type { StrapiMediaFile } from "./image.js";
3
+ declare global {
4
+ namespace FarmJS {
5
+ /** Extended by declarations generated from a local Strapi project. */
6
+ interface StrapiContentTypes {
7
+ }
8
+ }
9
+ }
10
+ export interface StrapiContentTypeDefinition<TFields extends object = object, TPopulate extends Record<string, StrapiPopulateField> = Record<never, never>> {
11
+ fields: TFields;
12
+ populate: TPopulate;
13
+ }
14
+ export interface StrapiRelation<TResource extends string, TMany extends boolean = false> {
15
+ kind: "relation";
16
+ resource: TResource;
17
+ many: TMany;
18
+ }
19
+ export interface StrapiMedia<TMany extends boolean = false> {
20
+ kind: "media";
21
+ many: TMany;
22
+ }
23
+ export interface StrapiComponent<TValue, TMany extends boolean = false> {
24
+ kind: "component";
25
+ value: TValue;
26
+ many: TMany;
27
+ }
28
+ export interface StrapiDynamicZone<TValue> {
29
+ kind: "dynamic-zone";
30
+ value: TValue;
31
+ }
32
+ export interface StrapiUnknownPopulate<TMany extends boolean = false> {
33
+ kind: "unknown";
34
+ many: TMany;
35
+ }
36
+ export type StrapiPopulateField = StrapiRelation<string, boolean> | StrapiMedia<boolean> | StrapiComponent<unknown, boolean> | StrapiDynamicZone<unknown> | StrapiUnknownPopulate<boolean>;
37
+ export interface StrapiGeneratedDocumentMetadata {
38
+ id?: number;
39
+ documentId: string;
40
+ createdAt: string;
41
+ updatedAt: string;
42
+ publishedAt?: string | null;
43
+ locale?: string | null;
44
+ }
45
+ type StrapiContentTypes = FarmJS.StrapiContentTypes;
46
+ export type StrapiGeneratedResource = Extract<keyof StrapiContentTypes, string>;
47
+ type DefinitionFor<TResource extends StrapiGeneratedResource> = StrapiContentTypes[TResource] extends StrapiContentTypeDefinition<infer TFields, infer TPopulate> ? StrapiContentTypeDefinition<TFields, TPopulate> : never;
48
+ type FieldsFor<TResource extends StrapiGeneratedResource> = DefinitionFor<TResource>["fields"];
49
+ type PopulateFor<TResource extends StrapiGeneratedResource> = DefinitionFor<TResource>["populate"];
50
+ type FieldName<TResource extends StrapiGeneratedResource> = Extract<keyof FieldsFor<TResource>, string>;
51
+ type PopulateName<TResource extends StrapiGeneratedResource> = Extract<keyof PopulateFor<TResource>, string>;
52
+ type PopulatePath<TResource extends StrapiGeneratedResource> = PopulateName<TResource> | `${PopulateName<TResource>}.${string}`;
53
+ export type StrapiGeneratedQuery<TResource extends StrapiGeneratedResource> = Omit<API.BaseQueryParams, "fields" | "populate"> & {
54
+ fields?: readonly FieldName<TResource>[];
55
+ populate?: "*" | PopulatePath<TResource> | readonly PopulatePath<TResource>[] | Partial<Record<PopulateName<TResource>, unknown>>;
56
+ };
57
+ type SelectedFields<TResource extends StrapiGeneratedResource, TQuery> = TQuery extends {
58
+ fields: infer TFields extends readonly FieldName<TResource>[];
59
+ } ? number extends TFields["length"] ? Partial<Pick<FieldsFor<TResource>, TFields[number]>> : Pick<FieldsFor<TResource>, TFields[number]> : "fields" extends keyof TQuery ? Partial<FieldsFor<TResource>> : FieldsFor<TResource>;
60
+ type HasNestedPopulateOptions<TValue> = unknown extends TValue ? true : TValue extends object ? true : false;
61
+ type RelationValue<TResource extends string> = TResource extends StrapiGeneratedResource ? StrapiGeneratedDocument<TResource> : unknown;
62
+ type PopulateValue<TField extends StrapiPopulateField, TPopulateValue> = HasNestedPopulateOptions<TPopulateValue> extends true ? unknown : TField extends StrapiRelation<infer TResource, infer TMany> ? TMany extends true ? RelationValue<TResource>[] : RelationValue<TResource> | null : TField extends StrapiMedia<infer TMany> ? TMany extends true ? StrapiMediaFile[] : StrapiMediaFile | null : TField extends StrapiComponent<infer TValue, infer TMany> ? TMany extends true ? TValue[] : TValue | null : TField extends StrapiDynamicZone<infer TValue> ? TValue[] : TField extends StrapiUnknownPopulate<infer TMany> ? TMany extends true ? unknown[] : unknown : never;
63
+ type PopulateResult<TResource extends StrapiGeneratedResource, TName extends PopulateName<TResource>, TPopulateValue> = {
64
+ [TKey in TName]: PopulateValue<PopulateFor<TResource>[TKey], TPopulateValue>;
65
+ };
66
+ type DefinitelyEnabled<TValue> = unknown extends TValue ? false : Extract<TValue, false | null | undefined> extends never ? true : false;
67
+ type PossibleObjectPopulateNames<TResource extends StrapiGeneratedResource, TPopulate extends object> = {
68
+ [TName in keyof TPopulate]-?: [TPopulate[TName]] extends [false | null | undefined] ? never : TName;
69
+ }[keyof TPopulate] & PopulateName<TResource>;
70
+ type RequiredObjectPopulateNames<TResource extends StrapiGeneratedResource, TPopulate extends object> = {
71
+ [TName in keyof TPopulate]-?: {} extends Pick<TPopulate, TName> ? never : DefinitelyEnabled<TPopulate[TName]> extends true ? TName : never;
72
+ }[keyof TPopulate] & PopulateName<TResource>;
73
+ type ObjectPopulateResult<TResource extends StrapiGeneratedResource, TPopulate extends object> = {
74
+ [TName in RequiredObjectPopulateNames<TResource, TPopulate>]: PopulateValue<PopulateFor<TResource>[TName], TPopulate[TName]>;
75
+ } & Partial<{
76
+ [TName in Exclude<PossibleObjectPopulateNames<TResource, TPopulate>, RequiredObjectPopulateNames<TResource, TPopulate>>]: PopulateValue<PopulateFor<TResource>[TName], TPopulate[TName]>;
77
+ }>;
78
+ type StringPopulateResult<TResource extends StrapiGeneratedResource, TPopulate extends PopulatePath<TResource>> = TPopulate extends unknown ? TPopulate extends PopulateName<TResource> ? PopulateResult<TResource, TPopulate, true> : TPopulate extends `${infer TName}.${string}` ? PopulateResult<TResource, Extract<TName, PopulateName<TResource>>, {
79
+ populate: unknown;
80
+ }> : never : never;
81
+ type DeepArrayPopulateNames<TResource extends StrapiGeneratedResource, TPopulate extends readonly unknown[]> = TPopulate[number] extends infer TPath ? TPath extends `${infer TName}.${string}` ? Extract<TName, PopulateName<TResource>> : never : never;
82
+ type ArrayPopulateResult<TResource extends StrapiGeneratedResource, TPopulate extends readonly unknown[]> = PopulateResult<TResource, Exclude<Extract<TPopulate[number], PopulateName<TResource>>, DeepArrayPopulateNames<TResource, TPopulate>>, true> & PopulateResult<TResource, DeepArrayPopulateNames<TResource, TPopulate>, {
83
+ populate: unknown;
84
+ }>;
85
+ type PopulateSelection<TResource extends StrapiGeneratedResource, TPopulate> = TPopulate extends "*" ? PopulateResult<TResource, PopulateName<TResource>, true> : TPopulate extends PopulatePath<TResource> ? StringPopulateResult<TResource, TPopulate> : TPopulate extends readonly unknown[] ? number extends TPopulate["length"] ? Partial<ArrayPopulateResult<TResource, TPopulate>> : ArrayPopulateResult<TResource, TPopulate> : TPopulate extends object ? ObjectPopulateResult<TResource, TPopulate> : object;
86
+ type SelectedPopulate<TResource extends StrapiGeneratedResource, TQuery> = TQuery extends {
87
+ populate: infer TPopulate;
88
+ } ? PopulateSelection<TResource, TPopulate> : "populate" extends keyof TQuery ? Partial<Record<PopulateName<TResource>, unknown>> : object;
89
+ export type StrapiGeneratedDocument<TResource extends StrapiGeneratedResource, TQuery = undefined> = StrapiGeneratedDocumentMetadata & SelectedFields<TResource, TQuery> & SelectedPopulate<TResource, TQuery>;
90
+ export interface GeneratedStrapiCollection<TResource extends StrapiGeneratedResource> {
91
+ find(): Promise<StrapiGeneratedDocument<TResource>[]>;
92
+ find<const TQuery extends StrapiGeneratedQuery<TResource>>(query: TQuery): Promise<StrapiGeneratedDocument<TResource, TQuery>[]>;
93
+ findOne(documentId: string): Promise<StrapiGeneratedDocument<TResource>>;
94
+ findOne<const TQuery extends StrapiGeneratedQuery<TResource>>(documentId: string, query: TQuery): Promise<StrapiGeneratedDocument<TResource, TQuery>>;
95
+ }
96
+ export {};
97
+ //# sourceMappingURL=schema-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-types.d.ts","sourceRoot":"","sources":["../src/schema-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM,CAAC;QACf,sEAAsE;QACtE,UAAU,kBAAkB;SAAG;KAChC;CACF;AAED,MAAM,WAAW,2BAA2B,CAC1C,OAAO,SAAS,MAAM,GAAG,MAAM,EAC/B,SAAS,SAAS,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC;IAE5E,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED,MAAM,WAAW,cAAc,CAAC,SAAS,SAAS,MAAM,EAAE,KAAK,SAAS,OAAO,GAAG,KAAK;IACrF,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,KAAK,CAAC;CACb;AAED,MAAM,WAAW,WAAW,CAAC,KAAK,SAAS,OAA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uB,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IACtD,IAAI,CAAC,KAAK,CAAC,MAAM,SAAS,oBAAoB,CAAC,SAAS,CAAC,EACvD,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,uBAAuB,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IACzD,OAAO,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,SAAS,CAAC,CAAC,CAAC;IACzE,OAAO,CAAC,KAAK,CAAC,MAAM,SAAS,oBAAoB,CAAC,SAAS,CAAC,EAC1D,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,uBAAuB,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;CACxD"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ export interface GenerateStrapiTypesOptions {
2
+ /** Directory containing the Strapi application's `src` directory. */
3
+ strapiRoot: string;
4
+ /** Declaration file to create. Relative paths are resolved from the current directory. */
5
+ outFile: string;
6
+ /** Verify the output without writing it. */
7
+ check?: boolean;
8
+ }
9
+ export interface GenerateStrapiTypesResult {
10
+ changed: boolean;
11
+ contentTypes: number;
12
+ components: number;
13
+ outFile: string;
14
+ }
15
+ export declare class StrapiTypesStaleError extends Error {
16
+ constructor(outFile: string);
17
+ }
18
+ export declare function generateStrapiTypes(options: GenerateStrapiTypesOptions): Promise<GenerateStrapiTypesResult>;
19
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAiCA,MAAM,WAAW,0BAA0B;IACzC,qEAAqE;IACrE,UAAU,EAAE,MAAM,CAAC;IACnB,0FAA0F;IAC1F,OAAO,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,yBAAyB;IACxC,OAAO,EAAE,OAAO,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,qBAAsB,SAAQ,KAAK;gBAClC,OAAO,EAAE,MAAM;CAI5B;AA6QD,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,yBAAyB,CAAC,CAmDpC"}
package/dist/schema.js ADDED
@@ -0,0 +1,302 @@
1
+ import { readFile, readdir, stat, writeFile, mkdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ export class StrapiTypesStaleError extends Error {
4
+ constructor(outFile) {
5
+ super(`Generated Strapi types are stale or missing: ${outFile}`);
6
+ this.name = "StrapiTypesStaleError";
7
+ }
8
+ }
9
+ async function readJson(file) {
10
+ let source;
11
+ try {
12
+ source = await readFile(file, "utf8");
13
+ }
14
+ catch (error) {
15
+ throw new Error(`Could not read Strapi schema ${file}`, { cause: error });
16
+ }
17
+ try {
18
+ const value = JSON.parse(source);
19
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
20
+ throw new TypeError("expected a JSON object");
21
+ }
22
+ return value;
23
+ }
24
+ catch (error) {
25
+ throw new Error(`Could not parse Strapi schema ${file}`, { cause: error });
26
+ }
27
+ }
28
+ async function filesNamed(root, name) {
29
+ let entries;
30
+ try {
31
+ entries = await readdir(root, { withFileTypes: true });
32
+ }
33
+ catch (error) {
34
+ if (error.code === "ENOENT")
35
+ return [];
36
+ throw error;
37
+ }
38
+ const files = [];
39
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
40
+ const entryPath = path.join(root, entry.name);
41
+ if (entry.isSymbolicLink())
42
+ continue;
43
+ if (entry.isDirectory())
44
+ files.push(...(await filesNamed(entryPath, name)));
45
+ else if (entry.isFile() && entry.name === name)
46
+ files.push(entryPath);
47
+ }
48
+ return files;
49
+ }
50
+ async function componentFiles(root) {
51
+ let entries;
52
+ try {
53
+ entries = await readdir(root, { withFileTypes: true });
54
+ }
55
+ catch (error) {
56
+ if (error.code === "ENOENT")
57
+ return [];
58
+ throw error;
59
+ }
60
+ const files = [];
61
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
62
+ const entryPath = path.join(root, entry.name);
63
+ if (entry.isSymbolicLink())
64
+ continue;
65
+ if (entry.isDirectory())
66
+ files.push(...(await componentFiles(entryPath)));
67
+ else if (entry.isFile() && entry.name.endsWith(".json"))
68
+ files.push(entryPath);
69
+ }
70
+ return files;
71
+ }
72
+ function contentTypeUid(file) {
73
+ const segments = file.split(path.sep);
74
+ const contentTypesIndex = segments.lastIndexOf("content-types");
75
+ const apiIndex = segments.lastIndexOf("api");
76
+ if (apiIndex < 0 || contentTypesIndex <= apiIndex + 1 || !segments[contentTypesIndex + 1]) {
77
+ throw new Error(`Unsupported Strapi content type path: ${file}`);
78
+ }
79
+ return `api::${segments[apiIndex + 1]}.${segments[contentTypesIndex + 1]}`;
80
+ }
81
+ function componentUid(root, file) {
82
+ return path
83
+ .relative(root, file)
84
+ .replace(/\.json$/i, "")
85
+ .split(path.sep)
86
+ .join(".");
87
+ }
88
+ function typeName(uid) {
89
+ const value = uid
90
+ .split(/[^A-Za-z0-9]+/)
91
+ .filter(Boolean)
92
+ .map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`)
93
+ .join("");
94
+ return `StrapiComponent${value || "Value"}`;
95
+ }
96
+ function property(name) {
97
+ return JSON.stringify(name);
98
+ }
99
+ function nullable(type, required) {
100
+ return required ? type : `${type} | null`;
101
+ }
102
+ function scalarType(attribute) {
103
+ switch (attribute.type) {
104
+ case "string":
105
+ case "text":
106
+ case "richtext":
107
+ case "email":
108
+ case "uid":
109
+ case "date":
110
+ case "time":
111
+ case "datetime":
112
+ case "timestamp":
113
+ return "string";
114
+ case "integer":
115
+ case "float":
116
+ case "decimal":
117
+ return "number";
118
+ case "biginteger":
119
+ return "string";
120
+ case "boolean":
121
+ return "boolean";
122
+ case "json":
123
+ return "unknown";
124
+ case "blocks":
125
+ return "unknown[]";
126
+ case "enumeration":
127
+ return attribute.enum?.length
128
+ ? attribute.enum.map((value) => JSON.stringify(value)).join(" | ")
129
+ : "string";
130
+ case "password":
131
+ case "relation":
132
+ case "media":
133
+ case "component":
134
+ case "dynamiczone":
135
+ return undefined;
136
+ default:
137
+ return "unknown";
138
+ }
139
+ }
140
+ function renderScalarFields(attributes, indentation = 0) {
141
+ const indent = " ".repeat(indentation);
142
+ const lines = Object.entries(attributes)
143
+ .filter(([, attribute]) => !attribute.private && attribute.type !== "password")
144
+ .map(([name, attribute]) => {
145
+ const value = scalarType(attribute);
146
+ return value
147
+ ? `${indent} ${property(name)}: ${nullable(value, attribute.required)};`
148
+ : undefined;
149
+ })
150
+ .filter((line) => !!line);
151
+ return lines.length ? `{\n${lines.join("\n")}\n${indent}}` : "Record<never, never>";
152
+ }
153
+ function relationIsMany(relation) {
154
+ return (relation === "oneToMany" ||
155
+ relation === "manyToMany" ||
156
+ relation === "manyWay" ||
157
+ relation === "morphToMany");
158
+ }
159
+ function renderPopulateFields(attributes, resourcesByUid, componentNames, indentation = 0) {
160
+ const indent = " ".repeat(indentation);
161
+ const lines = [];
162
+ for (const [name, attribute] of Object.entries(attributes)) {
163
+ if (attribute.private)
164
+ continue;
165
+ let value;
166
+ if (attribute.type === "relation") {
167
+ const resource = attribute.target ? resourcesByUid.get(attribute.target) : undefined;
168
+ value = resource
169
+ ? `StrapiRelation<${JSON.stringify(resource)}, ${relationIsMany(attribute.relation)}>`
170
+ : `StrapiUnknownPopulate<${relationIsMany(attribute.relation)}>`;
171
+ }
172
+ else if (attribute.type === "media") {
173
+ value = `StrapiMedia<${attribute.multiple === true}>`;
174
+ }
175
+ else if (attribute.type === "component") {
176
+ const componentName = attribute.component
177
+ ? componentNames.get(attribute.component)
178
+ : undefined;
179
+ if (!componentName) {
180
+ throw new Error(`Strapi component ${JSON.stringify(attribute.component)} referenced by ${JSON.stringify(name)} was not found`);
181
+ }
182
+ value = `StrapiComponent<${componentName}, ${attribute.repeatable === true}>`;
183
+ }
184
+ else if (attribute.type === "dynamiczone") {
185
+ const members = (attribute.components ?? []).map((uid) => {
186
+ const componentName = componentNames.get(uid);
187
+ if (!componentName) {
188
+ throw new Error(`Strapi dynamic-zone component ${JSON.stringify(uid)} was not found`);
189
+ }
190
+ return `(${componentName} & { __component: ${JSON.stringify(uid)} })`;
191
+ });
192
+ value = `StrapiDynamicZone<${members.length ? members.join(" | ") : "never"}>`;
193
+ }
194
+ if (value)
195
+ lines.push(`${indent} ${property(name)}: ${value};`);
196
+ }
197
+ return lines.length ? `{\n${lines.join("\n")}\n${indent}}` : "Record<never, never>";
198
+ }
199
+ function renderOutput(contentTypes, components) {
200
+ const componentNames = new Map();
201
+ const usedNames = new Map();
202
+ for (const component of components) {
203
+ const name = typeName(component.uid);
204
+ const previous = usedNames.get(name);
205
+ if (previous) {
206
+ throw new Error(`Strapi components ${JSON.stringify(previous)} and ${JSON.stringify(component.uid)} generate the same type name ${name}`);
207
+ }
208
+ usedNames.set(name, component.uid);
209
+ componentNames.set(component.uid, name);
210
+ }
211
+ const resourcesByUid = new Map();
212
+ const usedResources = new Map();
213
+ for (const contentType of contentTypes) {
214
+ if (contentType.schema.kind !== "collectionType")
215
+ continue;
216
+ const resource = contentType.schema.info?.pluralName;
217
+ if (!resource) {
218
+ throw new Error(`Strapi collection schema ${contentType.file} has no info.pluralName`);
219
+ }
220
+ const previous = usedResources.get(resource);
221
+ if (previous) {
222
+ throw new Error(`Strapi schemas ${JSON.stringify(previous)} and ${JSON.stringify(contentType.uid)} use the same plural name ${JSON.stringify(resource)}`);
223
+ }
224
+ usedResources.set(resource, contentType.uid);
225
+ resourcesByUid.set(contentType.uid, resource);
226
+ }
227
+ const imports = [
228
+ "StrapiComponent",
229
+ "StrapiContentTypeDefinition",
230
+ "StrapiDynamicZone",
231
+ "StrapiMedia",
232
+ "StrapiRelation",
233
+ "StrapiUnknownPopulate",
234
+ ];
235
+ const lines = [
236
+ "// Generated by @farm.js/strapi. Do not edit by hand.",
237
+ `import type { ${imports.join(", ")} } from "@farm.js/strapi";`,
238
+ "",
239
+ ];
240
+ for (const component of components) {
241
+ lines.push(`type ${componentNames.get(component.uid)} = { id: number } & ${renderScalarFields(component.schema.attributes ?? {})};`, "");
242
+ }
243
+ lines.push("declare global {", " namespace FarmJS {", " interface StrapiContentTypes {");
244
+ for (const contentType of contentTypes) {
245
+ const resource = resourcesByUid.get(contentType.uid);
246
+ if (!resource)
247
+ continue;
248
+ const attributes = contentType.schema.attributes ?? {};
249
+ lines.push(` ${property(resource)}: StrapiContentTypeDefinition<`, ` ${renderScalarFields(attributes, 8)},`, ` ${renderPopulateFields(attributes, resourcesByUid, componentNames, 8)}`, " >;");
250
+ }
251
+ lines.push(" }", " }", "}", "", "export {};", "");
252
+ return lines.join("\n");
253
+ }
254
+ export async function generateStrapiTypes(options) {
255
+ const strapiRoot = path.resolve(options.strapiRoot);
256
+ const outFile = path.resolve(options.outFile);
257
+ const sourceDirectory = path.join(strapiRoot, "src");
258
+ try {
259
+ if (!(await stat(sourceDirectory)).isDirectory())
260
+ throw new Error("not a directory");
261
+ }
262
+ catch (error) {
263
+ throw new Error(`Strapi source directory was not found: ${sourceDirectory}`, { cause: error });
264
+ }
265
+ const contentRoot = path.join(sourceDirectory, "api");
266
+ const componentRoot = path.join(sourceDirectory, "components");
267
+ const contentFiles = (await filesNamed(contentRoot, "schema.json")).filter((file) => file.split(path.sep).includes("content-types"));
268
+ if (contentFiles.length === 0) {
269
+ throw new Error(`No Strapi content type schemas were found under ${contentRoot}`);
270
+ }
271
+ const componentsFiles = await componentFiles(componentRoot);
272
+ const contentTypes = await Promise.all(contentFiles.map(async (file) => ({
273
+ file,
274
+ uid: contentTypeUid(file),
275
+ schema: await readJson(file),
276
+ })));
277
+ const components = await Promise.all(componentsFiles.map(async (file) => ({
278
+ file,
279
+ uid: componentUid(componentRoot, file),
280
+ schema: await readJson(file),
281
+ })));
282
+ const output = renderOutput(contentTypes, components);
283
+ const current = await readFile(outFile, "utf8").catch((error) => {
284
+ if (error.code === "ENOENT")
285
+ return undefined;
286
+ throw error;
287
+ });
288
+ const changed = current !== output;
289
+ if (options.check && changed)
290
+ throw new StrapiTypesStaleError(outFile);
291
+ if (!options.check && changed) {
292
+ await mkdir(path.dirname(outFile), { recursive: true });
293
+ await writeFile(outFile, output, "utf8");
294
+ }
295
+ return {
296
+ changed,
297
+ contentTypes: contentTypes.filter((contentType) => contentType.schema.kind === "collectionType")
298
+ .length,
299
+ components: components.length,
300
+ outFile,
301
+ };
302
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farm.js/strapi",
3
- "version": "0.1.72",
3
+ "version": "0.1.74",
4
4
  "description": "Strapi CMS integration for Farm.js",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -8,6 +8,9 @@
8
8
  "url": "https://github.com/farming-labs/farm.js",
9
9
  "directory": "packages/farm-strapi"
10
10
  },
11
+ "bin": {
12
+ "farm-strapi": "./dist/cli.js"
13
+ },
11
14
  "files": [
12
15
  "dist"
13
16
  ],
@@ -19,14 +22,18 @@
19
22
  ".": {
20
23
  "types": "./dist/index.d.ts",
21
24
  "import": "./dist/index.js"
25
+ },
26
+ "./schema": {
27
+ "types": "./dist/schema.d.ts",
28
+ "import": "./dist/schema.js"
22
29
  }
23
30
  },
24
31
  "publishConfig": {
25
32
  "access": "public"
26
33
  },
27
34
  "dependencies": {
28
- "@farm.js/integration-utils": "0.1.72",
29
- "@farm.js/core": "0.1.72"
35
+ "@farm.js/integration-utils": "0.1.74",
36
+ "@farm.js/core": "0.1.74"
30
37
  },
31
38
  "devDependencies": {
32
39
  "@strapi/client": "^1.6.2",