@sanity/blueprints 0.3.0 → 0.4.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 CHANGED
@@ -8,26 +8,35 @@ Helper methods for building valid Sanity Blueprints.
8
8
  ## Usage
9
9
 
10
10
  ```ts
11
- import {defineBlueprint, defineDocumentFunction, defineResource} from '@sanity/blueprints'
11
+ import {
12
+ defineBlueprint,
13
+ defineDocumentFunction,
14
+ defineDocumentWebhook
15
+ } from '@sanity/blueprints'
12
16
 
13
17
  export default defineBlueprint({
14
18
  resources: [
15
19
  defineDocumentFunction({
16
- name: 'Create Fancy Report',
20
+ name: 'fancy-report-function',
17
21
  src: 'functions/create-fancy-report',
18
22
  memory: 2,
19
23
  timeout: 360,
20
24
  event: {
21
- on: ['publish'],
25
+ on: ['create', 'update'],
22
26
  filter: "_type == 'customer'",
23
- projection: "totalSpend, lastOrderDate",
27
+ projection: "{totalSpend, lastOrderDate}",
24
28
  },
25
29
  env: {
26
30
  currency: 'USD',
27
31
  },
28
32
  }),
29
33
 
30
- defineResource({name: 'test-resource', type: 'test'}),
34
+ const webhookResource = defineDocumentWebhook({
35
+ name: 'notification-webhook',
36
+ url: 'http://api.yourdomain.com/notifications/sanity',
37
+ on: ['create'],
38
+ dataset: 'production',
39
+ })
31
40
  ],
32
41
  })
33
42
  ```
@@ -0,0 +1,2 @@
1
+ import type { Blueprint, BlueprintModule, BlueprintsApiConfig } from '../types.js';
2
+ export declare function defineBlueprint(blueprintConfig: Partial<Blueprint> & Partial<BlueprintsApiConfig>): BlueprintModule;
@@ -0,0 +1,19 @@
1
+ export function defineBlueprint(blueprintConfig) {
2
+ const { organizationId, projectId, stackId, blueprintVersion, resources, values, outputs } = blueprintConfig;
3
+ if (resources && !Array.isArray(resources))
4
+ throw new Error('`resources` must be an array');
5
+ function blueprint() {
6
+ return {
7
+ $schema: 'https://schemas.sanity.io/blueprints/v2024-10-01/blueprint.schema.json',
8
+ blueprintVersion: blueprintVersion ?? '2024-10-01',
9
+ resources,
10
+ values,
11
+ outputs,
12
+ };
13
+ }
14
+ blueprint.organizationId = organizationId;
15
+ blueprint.projectId = projectId;
16
+ blueprint.stackId = stackId;
17
+ return blueprint;
18
+ }
19
+ //# sourceMappingURL=blueprints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blueprints.js","sourceRoot":"","sources":["../../src/definers/blueprints.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,eAAe,CAAC,eAAkE;IAChG,MAAM,EAAC,cAAc,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAC,GAAG,eAAe,CAAA;IAE1G,IAAI,SAAS,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;IAE3F,SAAS,SAAS;QAChB,OAAO;YACL,OAAO,EAAE,wEAAwE;YACjF,gBAAgB,EAAE,gBAAgB,IAAI,YAAY;YAClD,SAAS;YACT,MAAM;YACN,OAAO;SACR,CAAA;IACH,CAAC;IAED,SAAS,CAAC,cAAc,GAAG,cAAc,CAAA;IACzC,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC/B,SAAS,CAAC,OAAO,GAAG,OAAO,CAAA;IAE3B,OAAO,SAAS,CAAA;AAClB,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { BlueprintCorsOriginConfig, BlueprintCorsOriginResource } from '../types';
2
+ export declare function defineCorsOrigin(parameters: BlueprintCorsOriginConfig): BlueprintCorsOriginResource;
@@ -0,0 +1,19 @@
1
+ export function defineCorsOrigin(parameters) {
2
+ const errors = [];
3
+ if (!parameters.name || parameters.name.trim() === '') {
4
+ errors.push('CORS Origin name is required');
5
+ }
6
+ if (!parameters.origin || parameters.origin.trim() === '') {
7
+ errors.push('CORS Origin URL is required');
8
+ }
9
+ if (errors.length > 0) {
10
+ const message = errors.join('\n');
11
+ throw new Error(message);
12
+ }
13
+ return {
14
+ ...parameters,
15
+ allowCredentials: parameters.allowCredentials || false,
16
+ type: 'sanity.project.cors',
17
+ };
18
+ }
19
+ //# sourceMappingURL=cors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.js","sourceRoot":"","sources":["../../src/definers/cors.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,gBAAgB,CAAC,UAAqC;IACpE,MAAM,MAAM,GAAa,EAAE,CAAA;IAE3B,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACtD,MAAM,CAAC,IAAI,CAAC,8BAA8B,CAAC,CAAA;IAC7C,CAAC;IAED,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,UAAU,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QAC1D,MAAM,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAA;IAC5C,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACjC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAA;IAC1B,CAAC;IAED,OAAO;QACL,GAAG,UAAU;QACb,gBAAgB,EAAE,UAAU,CAAC,gBAAgB,IAAI,KAAK;QACtD,IAAI,EAAE,qBAAqB;KAC5B,CAAA;AACH,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { BlueprintBaseFunctionResource, BlueprintDocumentFunctionResource, BlueprintDocumentFunctionResourceEvent, BlueprintMediaLibraryAssetFunctionResource, BlueprintMediaLibraryFunctionResourceEvent } from '../types.js';
2
+ export declare function defineDocumentFunction(functionConfig: Partial<BlueprintDocumentFunctionResource>): BlueprintDocumentFunctionResource;
3
+ /** @deprecated Define event properties under the 'event' key instead of specifying them at the top level */
4
+ export declare function defineDocumentFunction(functionConfig: Partial<BlueprintDocumentFunctionResource> & Partial<BlueprintDocumentFunctionResourceEvent>): BlueprintDocumentFunctionResource;
5
+ export declare function defineMediaLibraryAssetFunction(functionConfig: Partial<BlueprintMediaLibraryAssetFunctionResource> & Pick<BlueprintMediaLibraryAssetFunctionResource, 'event'> & Partial<BlueprintMediaLibraryFunctionResourceEvent>): BlueprintMediaLibraryAssetFunctionResource;
6
+ export declare function defineFunction(functionConfig: Partial<BlueprintBaseFunctionResource>): BlueprintBaseFunctionResource;
@@ -1,40 +1,19 @@
1
- export function defineBlueprint(blueprintConfig) {
2
- const { organizationId, projectId, stackId, blueprintVersion, resources, values, outputs } = blueprintConfig;
3
- if (resources && !Array.isArray(resources))
4
- throw new Error('`resources` must be an array');
5
- function blueprint() {
6
- return {
7
- $schema: 'https://schemas.sanity.io/blueprints/v2024-10-01/blueprint.schema.json',
8
- blueprintVersion: blueprintVersion ?? '2024-10-01',
9
- resources,
10
- values,
11
- outputs,
12
- };
13
- }
14
- blueprint.organizationId = organizationId;
15
- blueprint.projectId = projectId;
16
- blueprint.stackId = stackId;
17
- return blueprint;
18
- }
19
- const EVENT_KEYS = new Set(['on', 'filter', 'includeDrafts', 'includeAllVersions', 'projection', 'resource']);
1
+ const BASE_EVENT_KEYS = new Set(['on', 'filter', 'projection']);
2
+ const DOCUMENT_EVENT_KEYS = new Set([
3
+ 'includeDrafts',
4
+ 'includeAllVersions',
5
+ 'resource',
6
+ ...BASE_EVENT_KEYS.values(),
7
+ ]);
8
+ const MEDIA_LIBRARY_EVENT_KEYS = new Set(['resource', ...BASE_EVENT_KEYS.values()]);
20
9
  export function defineDocumentFunction(functionConfig) {
21
10
  let { name, src, event, timeout, memory, env, type, ...maybeEvent } = functionConfig;
22
- if (!name)
23
- throw new Error('`name` is required');
24
- // defaults
25
- if (!src)
26
- src = `functions/${name}`;
27
11
  if (!type)
28
12
  type = 'sanity.function.document';
29
- // type validation
30
- if (memory && typeof memory !== 'number')
31
- throw new Error('`memory` must be a number');
32
- if (timeout && typeof timeout !== 'number')
33
- throw new Error('`timeout` must be a number');
34
13
  // event validation
35
14
  if (event) {
36
15
  // `event` was specified, but event keys (aggregated in `maybeEvent`) were also specified at the top level. ambiguous and deprecated usage.
37
- const duplicateKeys = Object.keys(maybeEvent).filter((k) => EVENT_KEYS.has(k));
16
+ const duplicateKeys = Object.keys(maybeEvent).filter((k) => DOCUMENT_EVENT_KEYS.has(k));
38
17
  if (duplicateKeys.length > 0) {
39
18
  throw new Error(`\`event\` properties should be specified under the \`event\` key - specifying them at the top level is deprecated. The following keys were specified at the top level: ${duplicateKeys.map((k) => `\`${k}\``).join(', ')}`);
40
19
  }
@@ -46,29 +25,58 @@ export function defineDocumentFunction(functionConfig) {
46
25
  console.warn('⚠️ Deprecated usage of `defineDocumentFunction`: prefer to put `event` properties under the `event` key rather than at the top level.');
47
26
  }
48
27
  return {
28
+ ...defineFunction({
29
+ name,
30
+ src,
31
+ timeout,
32
+ memory,
33
+ env,
34
+ }),
49
35
  type,
50
- name,
51
- src,
52
36
  event,
53
- timeout,
54
- memory,
55
- env,
56
37
  };
57
38
  }
58
- export function defineResource(resourceConfig) {
59
- const { name, type } = resourceConfig;
39
+ export function defineMediaLibraryAssetFunction(functionConfig) {
40
+ let { name, src, event, timeout, memory, env, type } = functionConfig;
41
+ if (!type)
42
+ type = 'sanity.function.media-library.asset';
43
+ return {
44
+ ...defineFunction({
45
+ name,
46
+ src,
47
+ timeout,
48
+ memory,
49
+ env,
50
+ }),
51
+ type,
52
+ event: validateMediaLibraryFunctionEvent(event),
53
+ };
54
+ }
55
+ export function defineFunction(functionConfig) {
56
+ let { name, src, timeout, memory, env, type } = functionConfig;
60
57
  if (!name)
61
58
  throw new Error('`name` is required');
59
+ // defaults
60
+ if (!src)
61
+ src = `functions/${name}`;
62
62
  if (!type)
63
- throw new Error('`type` is required');
63
+ type = 'sanity.function.document';
64
+ // type validation
65
+ if (memory && typeof memory !== 'number')
66
+ throw new Error('`memory` must be a number');
67
+ if (timeout && typeof timeout !== 'number')
68
+ throw new Error('`timeout` must be a number');
64
69
  return {
65
- ...resourceConfig,
66
70
  type,
67
71
  name,
72
+ src,
73
+ timeout,
74
+ memory,
75
+ env,
68
76
  };
69
77
  }
70
78
  function validateDocumentFunctionEvent(event) {
71
- const cleanEvent = Object.fromEntries(Object.entries(event).filter(([key]) => EVENT_KEYS.has(key)));
79
+ const cleanEvent = Object.fromEntries(Object.entries(event).filter(([key]) => DOCUMENT_EVENT_KEYS.has(key)));
72
80
  const fullEvent = {
73
81
  on: cleanEvent.on || ['publish'],
74
82
  ...cleanEvent,
@@ -83,4 +91,14 @@ function validateDocumentFunctionEvent(event) {
83
91
  }
84
92
  return fullEvent;
85
93
  }
86
- //# sourceMappingURL=definers.js.map
94
+ function validateMediaLibraryFunctionEvent(event) {
95
+ const cleanEvent = Object.fromEntries(Object.entries(event).filter(([key]) => MEDIA_LIBRARY_EVENT_KEYS.has(key)));
96
+ const fullEvent = {
97
+ on: cleanEvent.on || ['publish'],
98
+ ...cleanEvent,
99
+ };
100
+ if (!Array.isArray(fullEvent.on))
101
+ throw new Error('`event.on` must be an array');
102
+ return fullEvent;
103
+ }
104
+ //# sourceMappingURL=functions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions.js","sourceRoot":"","sources":["../../src/definers/functions.ts"],"names":[],"mappings":"AAUA,MAAM,eAAe,GAAG,IAAI,GAAG,CAAuB,CAAC,IAAI,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAA;AAErF,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAA2B;IAC5D,eAAe;IACf,oBAAoB;IACpB,UAAU;IACV,GAAG,eAAe,CAAC,MAAM,EAAE;CAC5B,CAAC,CAAA;AAEF,MAAM,wBAAwB,GAAG,IAAI,GAAG,CAA+B,CAAC,UAAU,EAAE,GAAG,eAAe,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;AASjH,MAAM,UAAU,sBAAsB,CACpC,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,SAAS,CAAC,EAAE,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;IAChF,IAAI,SAAS,CAAC,QAAQ,EAAE,CAAC;QACvB,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI,SAAS,CAAC,QAAQ,CAAC,IAAI,KAAK,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAA;QACjI,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,IAAI,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC;YACzE,MAAM,IAAI,KAAK,CAAC,qEAAqE,CAAC,CAAA;IAC1F,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC;AAED,SAAS,iCAAiC,CAAC,KAAiD;IAC1F,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CACnC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,wBAAwB,CAAC,GAAG,CAAC,GAAmC,CAAC,CAAC,CAC7D,CAAA;IAE/C,MAAM,SAAS,GAAG;QAChB,EAAE,EAAE,UAAU,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC;QAChC,GAAG,UAAU;KACd,CAAA;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;IAChF,OAAO,SAAS,CAAA;AAClB,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { BlueprintResource } from '../types.js';
2
+ export declare function defineResource(resourceConfig: Partial<BlueprintResource>): BlueprintResource;
@@ -0,0 +1,13 @@
1
+ export function defineResource(resourceConfig) {
2
+ const { name, type } = resourceConfig;
3
+ if (!name)
4
+ throw new Error('`name` is required');
5
+ if (!type)
6
+ throw new Error('`type` is required');
7
+ return {
8
+ ...resourceConfig,
9
+ type,
10
+ name,
11
+ };
12
+ }
13
+ //# sourceMappingURL=resources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../src/definers/resources.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,cAAc,CAAC,cAA0C;IACvE,MAAM,EAAC,IAAI,EAAE,IAAI,EAAC,GAAG,cAAc,CAAA;IACnC,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAA;IAChD,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAA;IAEhD,OAAO;QACL,GAAG,cAAc;QACjB,IAAI;QACJ,IAAI;KACL,CAAA;AACH,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { BlueprintDocumentWebhookConfig, BlueprintDocumentWebhookResource } from '../types';
2
+ export declare function defineDocumentWebhook(parameters: BlueprintDocumentWebhookConfig): BlueprintDocumentWebhookResource;
@@ -0,0 +1,71 @@
1
+ export function defineDocumentWebhook(parameters) {
2
+ const errors = [];
3
+ if (!parameters.name || parameters.name.trim() === '') {
4
+ errors.push('Webhook name is required');
5
+ }
6
+ if (parameters.displayName) {
7
+ if (parameters.displayName.length > 100) {
8
+ errors.push('Display name must be 100 characters or less');
9
+ }
10
+ }
11
+ else {
12
+ parameters.displayName = parameters.name?.substring(0, 100);
13
+ }
14
+ if (!parameters.url || parameters.url.trim() === '') {
15
+ errors.push('Webhook URL is required');
16
+ }
17
+ // Validate URL format
18
+ try {
19
+ new URL(parameters.url);
20
+ }
21
+ catch {
22
+ errors.push('Webhook URL must be a valid URL');
23
+ }
24
+ if (!parameters.on || parameters.on.length === 0) {
25
+ errors.push('At least one event type must be specified in the "on" field');
26
+ }
27
+ // Validate event types
28
+ const validEvents = ['create', 'update', 'delete'];
29
+ if (parameters.on) {
30
+ const invalidEvents = parameters.on.filter((event) => !validEvents.includes(event));
31
+ if (invalidEvents.length > 0) {
32
+ errors.push(`Invalid event types: ${invalidEvents.join(', ')}. Valid events are: ${validEvents.join(', ')}`);
33
+ }
34
+ }
35
+ // Validate dataset pattern
36
+ if (!parameters.dataset || !/^[a-z0-9-_]+$/.test(parameters.dataset)) {
37
+ errors.push('Dataset must match pattern: ^[a-z0-9-_]+$');
38
+ }
39
+ // Validate HTTP method
40
+ if (parameters.httpMethod) {
41
+ const validMethods = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET'];
42
+ if (!validMethods.includes(parameters.httpMethod)) {
43
+ errors.push(`Invalid HTTP method: ${parameters.httpMethod}. Valid methods are: ${validMethods.join(', ')}`);
44
+ }
45
+ }
46
+ // Validate status
47
+ if (parameters.status && !['enabled', 'disabled'].includes(parameters.status)) {
48
+ errors.push('Status must be either "enabled" or "disabled"');
49
+ }
50
+ // Validate headers pattern
51
+ if (parameters.headers) {
52
+ const headerNamePattern = /^[a-zA-Z][a-zA-Z0-9-_]*$/;
53
+ for (const [key, value] of Object.entries(parameters.headers)) {
54
+ if (!headerNamePattern.test(key)) {
55
+ errors.push(`Header key "${key}" must match pattern: ${headerNamePattern.source}`);
56
+ }
57
+ if (typeof value !== 'string') {
58
+ errors.push(`Header value for "${key}" must be a string`);
59
+ }
60
+ }
61
+ }
62
+ if (errors.length > 0) {
63
+ const message = errors.join('\n');
64
+ throw new Error(message);
65
+ }
66
+ return {
67
+ ...parameters,
68
+ type: 'sanity.project.webhook',
69
+ };
70
+ }
71
+ //# sourceMappingURL=webhooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhooks.js","sourceRoot":"","sources":["../../src/definers/webhooks.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,qBAAqB,CAAC,UAA0C;IAC9E,MAAM,MAAM,GAAa,EAAE,CAAA;IAE3B,IAAI,CAAC,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACtD,MA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AC,MAAM,EAAE,CAAC,CAAA;YACpF,CAAC;YACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC9B,MAAM,CAAC,IAAI,CAAC,qBAAqB,GAAG,oBAAoB,CAAC,CAAA;YAC3D,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACjC,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAA;IAC1B,CAAC;IAED,OAAO;QACL,GAAG,UAAU;QACb,IAAI,EAAE,wBAAwB;KAC/B,CAAA;AACH,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,6 @@
1
1
  export * from './types.js';
2
- export * from './definers.js';
2
+ export * from './definers/blueprints.js';
3
+ export * from './definers/cors.js';
4
+ export * from './definers/functions.js';
5
+ export * from './definers/resources.js';
6
+ export * from './definers/webhooks.js';
package/dist/index.js CHANGED
@@ -1,3 +1,7 @@
1
1
  export * from './types.js';
2
- export * from './definers.js';
2
+ export * from './definers/blueprints.js';
3
+ export * from './definers/cors.js';
4
+ export * from './definers/functions.js';
5
+ export * from './definers/resources.js';
6
+ export * from './definers/webhooks.js';
3
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA;AAC1B,cAAc,0BAA0B,CAAA;AACxC,cAAc,oBAAoB,CAAA;AAClC,cAAc,yBAAyB,CAAA;AACvC,cAAc,yBAAyB,CAAA;AACvC,cAAc,wBAAwB,CAAA"}
package/dist/types.d.ts CHANGED
@@ -2,30 +2,70 @@ export interface BlueprintResource {
2
2
  type: string;
3
3
  name: string;
4
4
  }
5
- export interface BlueprintFunctionResourceEvent {
5
+ export interface BlueprintCorsOriginResource extends BlueprintResource {
6
+ type: 'sanity.project.cors';
7
+ project?: string;
8
+ origin: string;
9
+ allowCredentials: boolean;
10
+ }
11
+ export type BlueprintCorsOriginConfig = Omit<BlueprintCorsOriginResource, 'type' | 'allowCredentials'> & {
12
+ allowCredentials?: boolean;
13
+ };
14
+ export interface BlueprintFunctionBaseResourceEvent {
6
15
  on?: [BlueprintFunctionResourceEventName, ...BlueprintFunctionResourceEventName[]];
7
16
  filter?: string;
17
+ projection?: string;
18
+ }
19
+ export interface BlueprintDocumentFunctionResourceEvent extends BlueprintFunctionBaseResourceEvent {
8
20
  includeDrafts?: boolean;
9
21
  includeAllVersions?: boolean;
10
- projection?: string;
11
- /** @description The resource event source for function triggers. Only datasets are supported... for now. */
12
- resource?: BlueprintFunctionResourceEventResource;
22
+ resource?: BlueprintFunctionResourceEventResourceDataset;
23
+ }
24
+ export interface BlueprintMediaLibraryFunctionResourceEvent extends BlueprintFunctionBaseResourceEvent {
25
+ resource: BlueprintFunctionResourceEventResourceMediaLibrary;
13
26
  }
14
- export type BlueprintFunctionResourceEventResource = BlueprintFunctionResourceEventResourceDataset;
15
- export interface BlueprintFunctionResourceEventResourceDataset {
27
+ export type BlueprintFunctionResourceEvent = BlueprintDocumentFunctionResourceEvent | BlueprintMediaLibraryFunctionResourceEvent;
28
+ interface BlueprintFunctionResourceEventResourceDataset {
16
29
  type: 'dataset';
17
30
  /** @description A dataset ID in the format <projectId>.<datasetName>. <datasetName> can be `*` to signify "all datasets in project with ID <projectId>." */
18
31
  id: string;
19
32
  }
33
+ interface BlueprintFunctionResourceEventResourceMediaLibrary {
34
+ type: 'media-library';
35
+ id: string;
36
+ }
20
37
  type BlueprintFunctionResourceEventName = 'publish' | 'create' | 'delete' | 'update';
21
- export interface BlueprintFunctionResource extends BlueprintResource {
22
- type: 'sanity.function.document';
38
+ export interface BlueprintBaseFunctionResource extends BlueprintResource {
23
39
  src: string;
24
- event: BlueprintFunctionResourceEvent;
25
40
  timeout?: number;
26
41
  memory?: number;
27
42
  env?: Record<string, string>;
28
43
  }
44
+ export interface BlueprintDocumentFunctionResource extends BlueprintBaseFunctionResource {
45
+ type: 'sanity.function.document';
46
+ event: BlueprintDocumentFunctionResourceEvent;
47
+ }
48
+ export interface BlueprintMediaLibraryAssetFunctionResource extends BlueprintBaseFunctionResource {
49
+ type: 'sanity.function.media-library.asset';
50
+ event: BlueprintMediaLibraryFunctionResourceEvent;
51
+ }
52
+ export interface BlueprintDocumentWebhookResource extends BlueprintResource {
53
+ type: 'sanity.project.webhook';
54
+ project?: string;
55
+ displayName?: string;
56
+ description?: string | null;
57
+ url: string;
58
+ on: string[];
59
+ filter?: string | null;
60
+ projection?: string | null;
61
+ status?: 'enabled' | 'disabled';
62
+ httpMethod?: 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'GET';
63
+ headers?: Record<string, string>;
64
+ includeDrafts?: boolean;
65
+ secret?: string | null;
66
+ dataset?: string;
67
+ }
68
+ export type BlueprintDocumentWebhookConfig = Omit<BlueprintDocumentWebhookResource, 'type'>;
29
69
  export interface BlueprintOutput {
30
70
  name: string;
31
71
  value: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/blueprints",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Helper methods and type definitions for Sanity Blueprints",
5
5
  "keywords": [
6
6
  "sanity",
@@ -38,10 +38,10 @@
38
38
  "coverage": "vitest --coverage",
39
39
  "lint": "biome check .",
40
40
  "lint:write": "biome check --write .",
41
- "prepublishOnly": "npm run build",
41
+ "posttest": "npm run lint",
42
+ "prepare": "npm run build",
42
43
  "pretest": "npm run typecheck",
43
44
  "test": "vitest run --typecheck --reporter=verbose",
44
- "posttest": "npm run lint",
45
45
  "test:watch": "vitest --typecheck --reporter=verbose",
46
46
  "typecheck": "tsc --noEmit --project tsconfig.test.json"
47
47
  },
@@ -0,0 +1,23 @@
1
+ import type {Blueprint, BlueprintModule, BlueprintsApiConfig} from '../types.js'
2
+
3
+ export function defineBlueprint(blueprintConfig: Partial<Blueprint> & Partial<BlueprintsApiConfig>): BlueprintModule {
4
+ const {organizationId, projectId, stackId, blueprintVersion, resources, values, outputs} = blueprintConfig
5
+
6
+ if (resources && !Array.isArray(resources)) throw new Error('`resources` must be an array')
7
+
8
+ function blueprint(): Blueprint {
9
+ return {
10
+ $schema: 'https://schemas.sanity.io/blueprints/v2024-10-01/blueprint.schema.json',
11
+ blueprintVersion: blueprintVersion ?? '2024-10-01',
12
+ resources,
13
+ values,
14
+ outputs,
15
+ }
16
+ }
17
+
18
+ blueprint.organizationId = organizationId
19
+ blueprint.projectId = projectId
20
+ blueprint.stackId = stackId
21
+
22
+ return blueprint
23
+ }
@@ -0,0 +1,24 @@
1
+ import type {BlueprintCorsOriginConfig, BlueprintCorsOriginResource} from '../types'
2
+
3
+ export function defineCorsOrigin(parameters: BlueprintCorsOriginConfig): BlueprintCorsOriginResource {
4
+ const errors: string[] = []
5
+
6
+ if (!parameters.name || parameters.name.trim() === '') {
7
+ errors.push('CORS Origin name is required')
8
+ }
9
+
10
+ if (!parameters.origin || parameters.origin.trim() === '') {
11
+ errors.push('CORS Origin URL is required')
12
+ }
13
+
14
+ if (errors.length > 0) {
15
+ const message = errors.join('\n')
16
+ throw new Error(message)
17
+ }
18
+
19
+ return {
20
+ ...parameters,
21
+ allowCredentials: parameters.allowCredentials || false,
22
+ type: 'sanity.project.cors',
23
+ }
24
+ }
@@ -0,0 +1,138 @@
1
+ import type {
2
+ BlueprintBaseFunctionResource,
3
+ BlueprintDocumentFunctionResource,
4
+ BlueprintDocumentFunctionResourceEvent,
5
+ BlueprintFunctionBaseResourceEvent,
6
+ BlueprintMediaLibraryAssetFunctionResource,
7
+ BlueprintMediaLibraryFunctionResourceEvent,
8
+ } from '../types.js'
9
+
10
+ type BaseFunctionEventKey = keyof BlueprintFunctionBaseResourceEvent
11
+ const BASE_EVENT_KEYS = new Set<BaseFunctionEventKey>(['on', 'filter', 'projection'])
12
+ type DocumentFunctionEventKey = keyof BlueprintDocumentFunctionResourceEvent
13
+ const DOCUMENT_EVENT_KEYS = new Set<DocumentFunctionEventKey>([
14
+ 'includeDrafts',
15
+ 'includeAllVersions',
16
+ 'resource',
17
+ ...BASE_EVENT_KEYS.values(),
18
+ ])
19
+ type MediaLibraryFunctionEventKey = keyof BlueprintMediaLibraryFunctionResourceEvent
20
+ const MEDIA_LIBRARY_EVENT_KEYS = new Set<MediaLibraryFunctionEventKey>(['resource', ...BASE_EVENT_KEYS.values()])
21
+
22
+ export function defineDocumentFunction(functionConfig: Partial<BlueprintDocumentFunctionResource>): BlueprintDocumentFunctionResource
23
+
24
+ /** @deprecated Define event properties under the 'event' key instead of specifying them at the top level */
25
+ export function defineDocumentFunction(
26
+ functionConfig: Partial<BlueprintDocumentFunctionResource> & Partial<BlueprintDocumentFunctionResourceEvent>,
27
+ ): BlueprintDocumentFunctionResource
28
+
29
+ export function defineDocumentFunction(
30
+ functionConfig: Partial<BlueprintDocumentFunctionResource> & Partial<BlueprintDocumentFunctionResourceEvent>,
31
+ ): BlueprintDocumentFunctionResource {
32
+ let {name, src, event, timeout, memory, env, type, ...maybeEvent} = functionConfig
33
+ if (!type) type = 'sanity.function.document'
34
+
35
+ // event validation
36
+ if (event) {
37
+ // `event` was specified, but event keys (aggregated in `maybeEvent`) were also specified at the top level. ambiguous and deprecated usage.
38
+ const duplicateKeys = Object.keys(maybeEvent).filter((k) => DOCUMENT_EVENT_KEYS.has(k as DocumentFunctionEventKey))
39
+ if (duplicateKeys.length > 0) {
40
+ throw new Error(
41
+ `\`event\` properties should be specified under the \`event\` key - specifying them at the top level is deprecated. The following keys were specified at the top level: ${duplicateKeys.map((k) => `\`${k}\``).join(', ')}`,
42
+ )
43
+ }
44
+ event = validateDocumentFunctionEvent(event)
45
+ } else {
46
+ event = validateDocumentFunctionEvent(maybeEvent)
47
+ // deprecated usage of putting event properties at the top level, warn about this.
48
+ console.warn(
49
+ '⚠️ Deprecated usage of `defineDocumentFunction`: prefer to put `event` properties under the `event` key rather than at the top level.',
50
+ )
51
+ }
52
+
53
+ return {
54
+ ...defineFunction({
55
+ name,
56
+ src,
57
+ timeout,
58
+ memory,
59
+ env,
60
+ }),
61
+ type,
62
+ event,
63
+ }
64
+ }
65
+
66
+ export function defineMediaLibraryAssetFunction(
67
+ functionConfig: Partial<BlueprintMediaLibraryAssetFunctionResource> &
68
+ Pick<BlueprintMediaLibraryAssetFunctionResource, 'event'> &
69
+ Partial<BlueprintMediaLibraryFunctionResourceEvent>,
70
+ ): BlueprintMediaLibraryAssetFunctionResource {
71
+ let {name, src, event, timeout, memory, env, type} = functionConfig
72
+ if (!type) type = 'sanity.function.media-library.asset'
73
+
74
+ return {
75
+ ...defineFunction({
76
+ name,
77
+ src,
78
+ timeout,
79
+ memory,
80
+ env,
81
+ }),
82
+ type,
83
+ event: validateMediaLibraryFunctionEvent(event),
84
+ }
85
+ }
86
+ export function defineFunction(functionConfig: Partial<BlueprintBaseFunctionResource>): BlueprintBaseFunctionResource {
87
+ let {name, src, timeout, memory, env, type} = functionConfig
88
+
89
+ if (!name) throw new Error('`name` is required')
90
+
91
+ // defaults
92
+ if (!src) src = `functions/${name}`
93
+ if (!type) type = 'sanity.function.document'
94
+
95
+ // type validation
96
+ if (memory && typeof memory !== 'number') throw new Error('`memory` must be a number')
97
+ if (timeout && typeof timeout !== 'number') throw new Error('`timeout` must be a number')
98
+
99
+ return {
100
+ type,
101
+ name,
102
+ src,
103
+ timeout,
104
+ memory,
105
+ env,
106
+ }
107
+ }
108
+
109
+ function validateDocumentFunctionEvent(event: Partial<BlueprintDocumentFunctionResourceEvent>): BlueprintDocumentFunctionResourceEvent {
110
+ const cleanEvent = Object.fromEntries(
111
+ Object.entries(event).filter(([key]) => DOCUMENT_EVENT_KEYS.has(key as DocumentFunctionEventKey)),
112
+ ) as Partial<BlueprintDocumentFunctionResourceEvent>
113
+
114
+ const fullEvent = {
115
+ on: cleanEvent.on || ['publish'],
116
+ ...cleanEvent,
117
+ }
118
+ if (!Array.isArray(fullEvent.on)) throw new Error('`event.on` must be an array')
119
+ if (fullEvent.resource) {
120
+ if (!fullEvent.resource.type || fullEvent.resource.type !== 'dataset') throw new Error('`event.resource.type` must be "dataset"')
121
+ if (!fullEvent.resource.id || fullEvent.resource.id.split('.').length !== 2)
122
+ throw new Error('`event.resource.id` must be in the format <projectId>.<datasetName>')
123
+ }
124
+ return fullEvent
125
+ }
126
+
127
+ function validateMediaLibraryFunctionEvent(event: BlueprintMediaLibraryFunctionResourceEvent): BlueprintMediaLibraryFunctionResourceEvent {
128
+ const cleanEvent = Object.fromEntries(
129
+ Object.entries(event).filter(([key]) => MEDIA_LIBRARY_EVENT_KEYS.has(key as MediaLibraryFunctionEventKey)),
130
+ ) as BlueprintMediaLibraryFunctionResourceEvent
131
+
132
+ const fullEvent = {
133
+ on: cleanEvent.on || ['publish'],
134
+ ...cleanEvent,
135
+ }
136
+ if (!Array.isArray(fullEvent.on)) throw new Error('`event.on` must be an array')
137
+ return fullEvent
138
+ }
@@ -0,0 +1,13 @@
1
+ import type {BlueprintResource} from '../types.js'
2
+
3
+ export function defineResource(resourceConfig: Partial<BlueprintResource>): BlueprintResource {
4
+ const {name, type} = resourceConfig
5
+ if (!name) throw new Error('`name` is required')
6
+ if (!type) throw new Error('`type` is required')
7
+
8
+ return {
9
+ ...resourceConfig,
10
+ type,
11
+ name,
12
+ }
13
+ }
@@ -0,0 +1,82 @@
1
+ import type {BlueprintDocumentWebhookConfig, BlueprintDocumentWebhookResource} from '../types'
2
+
3
+ export function defineDocumentWebhook(parameters: BlueprintDocumentWebhookConfig): BlueprintDocumentWebhookResource {
4
+ const errors: string[] = []
5
+
6
+ if (!parameters.name || parameters.name.trim() === '') {
7
+ errors.push('Webhook name is required')
8
+ }
9
+
10
+ if (parameters.displayName) {
11
+ if (parameters.displayName.length > 100) {
12
+ errors.push('Display name must be 100 characters or less')
13
+ }
14
+ } else {
15
+ parameters.displayName = parameters.name?.substring(0, 100)
16
+ }
17
+
18
+ if (!parameters.url || parameters.url.trim() === '') {
19
+ errors.push('Webhook URL is required')
20
+ }
21
+
22
+ // Validate URL format
23
+ try {
24
+ new URL(parameters.url)
25
+ } catch {
26
+ errors.push('Webhook URL must be a valid URL')
27
+ }
28
+
29
+ if (!parameters.on || parameters.on.length === 0) {
30
+ errors.push('At least one event type must be specified in the "on" field')
31
+ }
32
+
33
+ // Validate event types
34
+ const validEvents = ['create', 'update', 'delete']
35
+ if (parameters.on) {
36
+ const invalidEvents = parameters.on.filter((event: string) => !validEvents.includes(event))
37
+ if (invalidEvents.length > 0) {
38
+ errors.push(`Invalid event types: ${invalidEvents.join(', ')}. Valid events are: ${validEvents.join(', ')}`)
39
+ }
40
+ }
41
+
42
+ // Validate dataset pattern
43
+ if (!parameters.dataset || !/^[a-z0-9-_]+$/.test(parameters.dataset)) {
44
+ errors.push('Dataset must match pattern: ^[a-z0-9-_]+$')
45
+ }
46
+
47
+ // Validate HTTP method
48
+ if (parameters.httpMethod) {
49
+ const validMethods = ['POST', 'PUT', 'PATCH', 'DELETE', 'GET']
50
+ if (!validMethods.includes(parameters.httpMethod)) {
51
+ errors.push(`Invalid HTTP method: ${parameters.httpMethod}. Valid methods are: ${validMethods.join(', ')}`)
52
+ }
53
+ }
54
+
55
+ // Validate status
56
+ if (parameters.status && !['enabled', 'disabled'].includes(parameters.status)) {
57
+ errors.push('Status must be either "enabled" or "disabled"')
58
+ }
59
+
60
+ // Validate headers pattern
61
+ if (parameters.headers) {
62
+ const headerNamePattern = /^[a-zA-Z][a-zA-Z0-9-_]*$/
63
+ for (const [key, value] of Object.entries(parameters.headers)) {
64
+ if (!headerNamePattern.test(key)) {
65
+ errors.push(`Header key "${key}" must match pattern: ${headerNamePattern.source}`)
66
+ }
67
+ if (typeof value !== 'string') {
68
+ errors.push(`Header value for "${key}" must be a string`)
69
+ }
70
+ }
71
+ }
72
+
73
+ if (errors.length > 0) {
74
+ const message = errors.join('\n')
75
+ throw new Error(message)
76
+ }
77
+
78
+ return {
79
+ ...parameters,
80
+ type: 'sanity.project.webhook',
81
+ }
82
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,6 @@
1
1
  export * from './types.js'
2
- export * from './definers.js'
2
+ export * from './definers/blueprints.js'
3
+ export * from './definers/cors.js'
4
+ export * from './definers/functions.js'
5
+ export * from './definers/resources.js'
6
+ export * from './definers/webhooks.js'
package/src/types.ts CHANGED
@@ -3,33 +3,75 @@ export interface BlueprintResource {
3
3
  name: string
4
4
  }
5
5
 
6
- export interface BlueprintFunctionResourceEvent {
6
+ export interface BlueprintCorsOriginResource extends BlueprintResource {
7
+ type: 'sanity.project.cors'
8
+ project?: string
9
+ origin: string
10
+ allowCredentials: boolean
11
+ }
12
+ export type BlueprintCorsOriginConfig = Omit<BlueprintCorsOriginResource, 'type' | 'allowCredentials'> & {
13
+ allowCredentials?: boolean
14
+ }
15
+
16
+ export interface BlueprintFunctionBaseResourceEvent {
7
17
  on?: [BlueprintFunctionResourceEventName, ...BlueprintFunctionResourceEventName[]]
8
18
  filter?: string
19
+ projection?: string
20
+ }
21
+ export interface BlueprintDocumentFunctionResourceEvent extends BlueprintFunctionBaseResourceEvent {
9
22
  includeDrafts?: boolean
10
23
  includeAllVersions?: boolean
11
- projection?: string
12
- /** @description The resource event source for function triggers. Only datasets are supported... for now. */
13
- resource?: BlueprintFunctionResourceEventResource
24
+ resource?: BlueprintFunctionResourceEventResourceDataset
14
25
  }
26
+ export interface BlueprintMediaLibraryFunctionResourceEvent extends BlueprintFunctionBaseResourceEvent {
27
+ resource: BlueprintFunctionResourceEventResourceMediaLibrary
28
+ }
29
+ export type BlueprintFunctionResourceEvent = BlueprintDocumentFunctionResourceEvent | BlueprintMediaLibraryFunctionResourceEvent
15
30
 
16
- export type BlueprintFunctionResourceEventResource = BlueprintFunctionResourceEventResourceDataset
17
- export interface BlueprintFunctionResourceEventResourceDataset {
31
+ interface BlueprintFunctionResourceEventResourceDataset {
18
32
  type: 'dataset'
19
33
  /** @description A dataset ID in the format <projectId>.<datasetName>. <datasetName> can be `*` to signify "all datasets in project with ID <projectId>." */
20
34
  id: string
21
35
  }
36
+ interface BlueprintFunctionResourceEventResourceMediaLibrary {
37
+ type: 'media-library'
38
+ id: string
39
+ }
22
40
 
23
41
  type BlueprintFunctionResourceEventName = 'publish' | 'create' | 'delete' | 'update'
24
42
 
25
- export interface BlueprintFunctionResource extends BlueprintResource {
26
- type: 'sanity.function.document'
43
+ export interface BlueprintBaseFunctionResource extends BlueprintResource {
27
44
  src: string
28
- event: BlueprintFunctionResourceEvent
29
45
  timeout?: number
30
46
  memory?: number
31
47
  env?: Record<string, string>
32
48
  }
49
+ export interface BlueprintDocumentFunctionResource extends BlueprintBaseFunctionResource {
50
+ type: 'sanity.function.document'
51
+ event: BlueprintDocumentFunctionResourceEvent
52
+ }
53
+ export interface BlueprintMediaLibraryAssetFunctionResource extends BlueprintBaseFunctionResource {
54
+ type: 'sanity.function.media-library.asset'
55
+ event: BlueprintMediaLibraryFunctionResourceEvent
56
+ }
57
+
58
+ export interface BlueprintDocumentWebhookResource extends BlueprintResource {
59
+ type: 'sanity.project.webhook'
60
+ project?: string
61
+ displayName?: string
62
+ description?: string | null
63
+ url: string
64
+ on: string[]
65
+ filter?: string | null
66
+ projection?: string | null
67
+ status?: 'enabled' | 'disabled'
68
+ httpMethod?: 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'GET'
69
+ headers?: Record<string, string>
70
+ includeDrafts?: boolean
71
+ secret?: string | null
72
+ dataset?: string
73
+ }
74
+ export type BlueprintDocumentWebhookConfig = Omit<BlueprintDocumentWebhookResource, 'type'>
33
75
 
34
76
  export interface BlueprintOutput {
35
77
  name: string
@@ -1,6 +0,0 @@
1
- import type { Blueprint, BlueprintFunctionResource, BlueprintFunctionResourceEvent, BlueprintModule, BlueprintResource, BlueprintsApiConfig } from './types.js';
2
- export declare function defineBlueprint(blueprintConfig: Partial<Blueprint> & Partial<BlueprintsApiConfig>): BlueprintModule;
3
- export declare function defineDocumentFunction(functionConfig: Partial<BlueprintFunctionResource>): BlueprintFunctionResource;
4
- /** @deprecated Define event properties under the 'event' key instead of specifying them at the top level */
5
- export declare function defineDocumentFunction(functionConfig: Partial<BlueprintFunctionResource> & Partial<BlueprintFunctionResourceEvent>): BlueprintFunctionResource;
6
- export declare function defineResource(resourceConfig: Partial<BlueprintResource>): BlueprintResource;
@@ -1 +0,0 @@
1
- {"version":3,"file":"definers.js","sourceRoot":"","sources":["../src/definers.ts"],"names":[],"mappings":"AASA,MAAM,UAAU,eAAe,CAAC,eAAkE;IAChG,MAAM,EAAC,cAAc,EAAE,SAAS,EAAE,OAAO,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAC,GAAG,eAAe,CAAA;IAE1G,IAAI,SAAS,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;IAE3F,SAAS,SAAS;QAChB,OAAO;YACL,OAAO,EAAE,wEAAwE;YACjF,gBAAgB,EAAE,gBAAgB,IAAI,YAAY;YAClD,SAAS;YACT,MAAM;YACN,OAAO;SACR,CAAA;IACH,CAAC;IAED,SAAS,CAAC,cAAc,GAAG,cAAc,CAAA;IACzC,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA;IAC/B,SAAS,CAAC,OAAO,GAAG,OAAO,CAAA;IAE3B,OAAO,SAAS,CAAA;AAClB,CAAC;AAGD,MAAM,UAAU,GAAG,IAAI,GAAG,CAAW,CAAC,IAAI,EAAE,QAAQ,EAAE,eAAe,EAAE,oBAAoB,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC,CAAA;AASvH,MAAM,UAAU,sBAAsB,CACpC,cAA4F;IAE5F,IAAI,EAAC,IAAI,EAAE,GA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CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC"}
package/src/definers.ts DELETED
@@ -1,114 +0,0 @@
1
- import type {
2
- Blueprint,
3
- BlueprintFunctionResource,
4
- BlueprintFunctionResourceEvent,
5
- BlueprintModule,
6
- BlueprintResource,
7
- BlueprintsApiConfig,
8
- } from './types.js'
9
-
10
- export function defineBlueprint(blueprintConfig: Partial<Blueprint> & Partial<BlueprintsApiConfig>): BlueprintModule {
11
- const {organizationId, projectId, stackId, blueprintVersion, resources, values, outputs} = blueprintConfig
12
-
13
- if (resources && !Array.isArray(resources)) throw new Error('`resources` must be an array')
14
-
15
- function blueprint(): Blueprint {
16
- return {
17
- $schema: 'https://schemas.sanity.io/blueprints/v2024-10-01/blueprint.schema.json',
18
- blueprintVersion: blueprintVersion ?? '2024-10-01',
19
- resources,
20
- values,
21
- outputs,
22
- }
23
- }
24
-
25
- blueprint.organizationId = organizationId
26
- blueprint.projectId = projectId
27
- blueprint.stackId = stackId
28
-
29
- return blueprint
30
- }
31
-
32
- type EventKey = keyof BlueprintFunctionResourceEvent
33
- const EVENT_KEYS = new Set<EventKey>(['on', 'filter', 'includeDrafts', 'includeAllVersions', 'projection', 'resource'])
34
-
35
- export function defineDocumentFunction(functionConfig: Partial<BlueprintFunctionResource>): BlueprintFunctionResource
36
-
37
- /** @deprecated Define event properties under the 'event' key instead of specifying them at the top level */
38
- export function defineDocumentFunction(
39
- functionConfig: Partial<BlueprintFunctionResource> & Partial<BlueprintFunctionResourceEvent>,
40
- ): BlueprintFunctionResource
41
-
42
- export function defineDocumentFunction(
43
- functionConfig: Partial<BlueprintFunctionResource> & Partial<BlueprintFunctionResourceEvent>,
44
- ): BlueprintFunctionResource {
45
- let {name, src, event, timeout, memory, env, type, ...maybeEvent} = functionConfig
46
-
47
- if (!name) throw new Error('`name` is required')
48
-
49
- // defaults
50
- if (!src) src = `functions/${name}`
51
- if (!type) type = 'sanity.function.document'
52
-
53
- // type validation
54
- if (memory && typeof memory !== 'number') throw new Error('`memory` must be a number')
55
- if (timeout && typeof timeout !== 'number') throw new Error('`timeout` must be a number')
56
-
57
- // event validation
58
- if (event) {
59
- // `event` was specified, but event keys (aggregated in `maybeEvent`) were also specified at the top level. ambiguous and deprecated usage.
60
- const duplicateKeys = Object.keys(maybeEvent).filter((k) => EVENT_KEYS.has(k as EventKey))
61
- if (duplicateKeys.length > 0) {
62
- throw new Error(
63
- `\`event\` properties should be specified under the \`event\` key - specifying them at the top level is deprecated. The following keys were specified at the top level: ${duplicateKeys.map((k) => `\`${k}\``).join(', ')}`,
64
- )
65
- }
66
- event = validateDocumentFunctionEvent(event)
67
- } else {
68
- event = validateDocumentFunctionEvent(maybeEvent)
69
- // deprecated usage of putting event properties at the top level, warn about this.
70
- console.warn(
71
- '⚠️ Deprecated usage of `defineDocumentFunction`: prefer to put `event` properties under the `event` key rather than at the top level.',
72
- )
73
- }
74
-
75
- return {
76
- type,
77
- name,
78
- src,
79
- event,
80
- timeout,
81
- memory,
82
- env,
83
- }
84
- }
85
-
86
- export function defineResource(resourceConfig: Partial<BlueprintResource>): BlueprintResource {
87
- const {name, type} = resourceConfig
88
- if (!name) throw new Error('`name` is required')
89
- if (!type) throw new Error('`type` is required')
90
-
91
- return {
92
- ...resourceConfig,
93
- type,
94
- name,
95
- }
96
- }
97
-
98
- function validateDocumentFunctionEvent(event: Partial<BlueprintFunctionResourceEvent>): BlueprintFunctionResourceEvent {
99
- const cleanEvent = Object.fromEntries(
100
- Object.entries(event).filter(([key]) => EVENT_KEYS.has(key as EventKey)),
101
- ) as Partial<BlueprintFunctionResourceEvent>
102
-
103
- const fullEvent = {
104
- on: cleanEvent.on || ['publish'],
105
- ...cleanEvent,
106
- }
107
- if (!Array.isArray(fullEvent.on)) throw new Error('`event.on` must be an array')
108
- if (fullEvent.resource) {
109
- if (!fullEvent.resource.type || fullEvent.resource.type !== 'dataset') throw new Error('`event.resource.type` must be "dataset"')
110
- if (!fullEvent.resource.id || fullEvent.resource.id.split('.').length !== 2)
111
- throw new Error('`event.resource.id` must be in the format <projectId>.<datasetName>')
112
- }
113
- return fullEvent
114
- }