@pikku/cli 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/bin/pikku-all.ts +10 -3
  3. package/bin/pikku-rpc.ts +28 -0
  4. package/bin/pikku.ts +4 -0
  5. package/cli.schema.json +4 -0
  6. package/dist/bin/pikku-all.js +7 -3
  7. package/dist/bin/pikku-rpc.d.ts +4 -0
  8. package/dist/bin/pikku-rpc.js +19 -0
  9. package/dist/bin/pikku.js +4 -0
  10. package/dist/src/pikku-cli-config.d.ts +3 -0
  11. package/dist/src/pikku-cli-config.js +15 -4
  12. package/dist/src/serialize-import-map.js +62 -1
  13. package/dist/src/serialize-pikku-types.js +77 -5
  14. package/dist/src/utils.js +24 -2
  15. package/dist/src/wirings/functions/pikku-command-function-types.js +2 -2
  16. package/dist/src/wirings/functions/pikku-command-functions.d.ts +0 -4
  17. package/dist/src/wirings/functions/pikku-command-functions.js +10 -31
  18. package/dist/src/wirings/functions/pikku-command-services.js +1 -1
  19. package/dist/src/wirings/functions/pikku-function-types.js +2 -2
  20. package/dist/src/wirings/functions/serialize-function-imports.d.ts +6 -0
  21. package/dist/src/wirings/functions/serialize-function-imports.js +59 -0
  22. package/dist/src/wirings/rpc/pikku-command-rpc-client.js +2 -2
  23. package/dist/src/wirings/rpc/pikku-command-rpc-map.d.ts +2 -1
  24. package/dist/src/wirings/rpc/pikku-command-rpc-map.js +9 -3
  25. package/dist/src/wirings/rpc/pikku-command-rpc.js +7 -2
  26. package/dist/src/wirings/rpc/serialize-typed-rpc-map.d.ts +1 -2
  27. package/dist/src/wirings/rpc/serialize-typed-rpc-map.js +2 -1
  28. package/dist/tsconfig.tsbuildinfo +1 -1
  29. package/package.json +3 -3
  30. package/src/pikku-cli-config.ts +35 -5
  31. package/src/serialize-import-map.ts +67 -2
  32. package/src/serialize-pikku-types.ts +77 -5
  33. package/src/utils.ts +31 -2
  34. package/src/wirings/functions/pikku-command-function-types.ts +6 -2
  35. package/src/wirings/functions/pikku-command-functions.ts +28 -64
  36. package/src/wirings/functions/pikku-command-services.ts +1 -1
  37. package/src/wirings/functions/pikku-function-types.ts +6 -2
  38. package/src/wirings/functions/serialize-function-imports.ts +97 -0
  39. package/src/wirings/rpc/pikku-command-rpc-client.ts +8 -4
  40. package/src/wirings/rpc/pikku-command-rpc-map.ts +27 -4
  41. package/src/wirings/rpc/pikku-command-rpc.ts +16 -6
  42. package/src/wirings/rpc/serialize-typed-rpc-map.ts +4 -5
  43. package/dist/src/wirings/functions/pikku-functions.d.ts +0 -6
  44. package/dist/src/wirings/functions/pikku-functions.js +0 -35
  45. package/dist/src/wirings/rpc/pikku-rpc.d.ts +0 -2
  46. package/dist/src/wirings/rpc/pikku-rpc.js +0 -6
  47. package/src/wirings/functions/pikku-functions.ts +0 -84
  48. package/src/wirings/rpc/pikku-rpc.ts +0 -22
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @pikku/cli
2
2
 
3
+ ## 0.9.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 92c1926: feat: adding rpc and websocket client cli commands
8
+ - c18800d: feat: adding queue and scheduledTask to interactions
9
+ - Updated dependencies [c18800d]
10
+ - @pikku/core@0.9.4
11
+
12
+ ## 0.9.3
13
+
14
+ ### Patch Changes
15
+
16
+ - 9691aba: fix: add-functions should support both functions only and objects
17
+ - 2ab0278: refactor: no longer import ALL functions, only the ones used by rpcs
18
+ - 81005ba: feat: creating a smaller meta file for functions to reduce size
19
+ - b3c2829: fix (using ai): generating custom types broke imports.. this fixes it, but needs more robust training
20
+ - Updated dependencies [9691aba]
21
+ - Updated dependencies [2ab0278]
22
+ - Updated dependencies [81005ba]
23
+ - Updated dependencies [b3c2829]
24
+ - @pikku/inspector@0.9.3
25
+ - @pikku/core@0.9.3
26
+
3
27
  ## 0.9.2
4
28
 
5
29
  ### Patch Changes
package/bin/pikku-all.ts CHANGED
@@ -17,7 +17,10 @@ import chokidar from 'chokidar'
17
17
  import { pikkuFunctions } from '../src/wirings/functions/pikku-command-functions.js'
18
18
  import { pikkuServices } from '../src/wirings/functions/pikku-command-services.js'
19
19
  import { pikkuRPC } from '../src/wirings/rpc/pikku-command-rpc.js'
20
- import { pikkuRPCMap } from '../src/wirings/rpc/pikku-command-rpc-map.js'
20
+ import {
21
+ pikkuRPCExposedMap,
22
+ pikkuRPCInternalMap,
23
+ } from '../src/wirings/rpc/pikku-command-rpc-map.js'
21
24
  import { pikkuQueue } from '../src/wirings/queue/pikku-command-queue.js'
22
25
  import { pikkuQueueMap } from '../src/wirings/queue/pikku-command-queue-map.js'
23
26
  import { pikkuFetch } from '../src/wirings/fetch/index.js'
@@ -39,7 +42,10 @@ const generateBootstrapFile = async (
39
42
  schemas?: boolean
40
43
  ) => {
41
44
  // Common imports that every bootstrap file needs
42
- const commonImports = [cliConfig.functionsMetaFile, cliConfig.functionsFile]
45
+ const commonImports = [
46
+ cliConfig.functionsMetaMinFile,
47
+ cliConfig.functionsFile,
48
+ ]
43
49
 
44
50
  // Add schema if it exists
45
51
  if (schemas) {
@@ -106,7 +112,8 @@ const runAll = async (
106
112
  await pikkuServices(logger, cliConfig, visitState)
107
113
 
108
114
  await pikkuRPC(logger, cliConfig, visitState)
109
- await pikkuRPCMap(logger, cliConfig, visitState)
115
+ await pikkuRPCInternalMap(logger, cliConfig, visitState)
116
+ await pikkuRPCExposedMap(logger, cliConfig, visitState)
110
117
  await pikkuRPCClient(logger, cliConfig)
111
118
  allImports.push(cliConfig.rpcWiringMetaFile)
112
119
 
@@ -0,0 +1,28 @@
1
+ import { Command } from 'commander'
2
+ import { CLILogger, PikkuCLIOptions } from '../src/utils.js'
3
+ import { getPikkuCLIConfig } from '../src/pikku-cli-config.js'
4
+ import { pikkuRPCClient } from '../src/wirings/rpc/pikku-command-rpc-client.js'
5
+
6
+ export const action = async (options: PikkuCLIOptions): Promise<void> => {
7
+ const logger = new CLILogger({ logLogo: true })
8
+
9
+ const cliConfig = await getPikkuCLIConfig(
10
+ options.config,
11
+ ['rootDir', 'schemaDirectory', 'configDir', 'fetchFile'],
12
+ {
13
+ tags: options.tags,
14
+ types: options.types,
15
+ directories: options.directories,
16
+ },
17
+ true
18
+ )
19
+ await pikkuRPCClient(logger, cliConfig)
20
+ }
21
+
22
+ export const rpc = (program: Command): void => {
23
+ program
24
+ .command('rpc')
25
+ .description('generate rpc wrapper')
26
+ .option('-c | --config <string>', 'The path to pikku cli config file')
27
+ .action(action)
28
+ }
package/bin/pikku.ts CHANGED
@@ -5,6 +5,8 @@ import { nextjs } from './pikku-nextjs.js'
5
5
  import { all } from './pikku-all.js'
6
6
  import { fetch } from './pikku-fetch.js'
7
7
  import { queue } from './pikku-queue-service.js'
8
+ import { websocket } from './pikku-websocket.js'
9
+ import { rpc } from './pikku-rpc.js'
8
10
 
9
11
  const program = new Command('pikku')
10
12
  program.usage('[command]')
@@ -12,6 +14,8 @@ program.usage('[command]')
12
14
  all(program)
13
15
  schemas(program)
14
16
  nextjs(program)
17
+ websocket(program)
18
+ rpc(program)
15
19
  fetch(program)
16
20
  queue(program)
17
21
 
package/cli.schema.json CHANGED
@@ -199,6 +199,9 @@
199
199
  "functionsMetaFile": {
200
200
  "type": "string"
201
201
  },
202
+ "functionsMetaMinFile": {
203
+ "type": "string"
204
+ },
202
205
  "httpMapDeclarationFile": {
203
206
  "type": "string"
204
207
  },
@@ -316,6 +319,7 @@
316
319
  "filters",
317
320
  "functionsFile",
318
321
  "functionsMetaFile",
322
+ "functionsMetaMinFile",
319
323
  "httpMapDeclarationFile",
320
324
  "httpWiringMetaFile",
321
325
  "httpWiringsFile",
@@ -11,7 +11,7 @@ import chokidar from 'chokidar';
11
11
  import { pikkuFunctions } from '../src/wirings/functions/pikku-command-functions.js';
12
12
  import { pikkuServices } from '../src/wirings/functions/pikku-command-services.js';
13
13
  import { pikkuRPC } from '../src/wirings/rpc/pikku-command-rpc.js';
14
- import { pikkuRPCMap } from '../src/wirings/rpc/pikku-command-rpc-map.js';
14
+ import { pikkuRPCExposedMap, pikkuRPCInternalMap, } from '../src/wirings/rpc/pikku-command-rpc-map.js';
15
15
  import { pikkuQueue } from '../src/wirings/queue/pikku-command-queue.js';
16
16
  import { pikkuQueueMap } from '../src/wirings/queue/pikku-command-queue-map.js';
17
17
  import { pikkuFetch } from '../src/wirings/fetch/index.js';
@@ -26,7 +26,10 @@ import { pikkuMCPJSON } from '../src/wirings/mcp/pikku-command-mcp-json.js';
26
26
  import { pikkuNext } from '../src/runtimes/nextjs/pikku-command-nextjs.js';
27
27
  const generateBootstrapFile = async (logger, cliConfig, bootstrapFile, specificImports, schemas) => {
28
28
  // Common imports that every bootstrap file needs
29
- const commonImports = [cliConfig.functionsMetaFile, cliConfig.functionsFile];
29
+ const commonImports = [
30
+ cliConfig.functionsMetaMinFile,
31
+ cliConfig.functionsFile,
32
+ ];
30
33
  // Add schema if it exists
31
34
  if (schemas) {
32
35
  commonImports.push(`${cliConfig.schemaDirectory}/register.gen.ts`);
@@ -61,7 +64,8 @@ const runAll = async (logger, cliConfig, options) => {
61
64
  // Generate services map
62
65
  await pikkuServices(logger, cliConfig, visitState);
63
66
  await pikkuRPC(logger, cliConfig, visitState);
64
- await pikkuRPCMap(logger, cliConfig, visitState);
67
+ await pikkuRPCInternalMap(logger, cliConfig, visitState);
68
+ await pikkuRPCExposedMap(logger, cliConfig, visitState);
65
69
  await pikkuRPCClient(logger, cliConfig);
66
70
  allImports.push(cliConfig.rpcWiringMetaFile);
67
71
  const schemas = await pikkuSchemas(logger, cliConfig, visitState);
@@ -0,0 +1,4 @@
1
+ import { Command } from 'commander';
2
+ import { PikkuCLIOptions } from '../src/utils.js';
3
+ export declare const action: (options: PikkuCLIOptions) => Promise<void>;
4
+ export declare const rpc: (program: Command) => void;
@@ -0,0 +1,19 @@
1
+ import { CLILogger } from '../src/utils.js';
2
+ import { getPikkuCLIConfig } from '../src/pikku-cli-config.js';
3
+ import { pikkuRPCClient } from '../src/wirings/rpc/pikku-command-rpc-client.js';
4
+ export const action = async (options) => {
5
+ const logger = new CLILogger({ logLogo: true });
6
+ const cliConfig = await getPikkuCLIConfig(options.config, ['rootDir', 'schemaDirectory', 'configDir', 'fetchFile'], {
7
+ tags: options.tags,
8
+ types: options.types,
9
+ directories: options.directories,
10
+ }, true);
11
+ await pikkuRPCClient(logger, cliConfig);
12
+ };
13
+ export const rpc = (program) => {
14
+ program
15
+ .command('rpc')
16
+ .description('generate rpc wrapper')
17
+ .option('-c | --config <string>', 'The path to pikku cli config file')
18
+ .action(action);
19
+ };
package/dist/bin/pikku.js CHANGED
@@ -5,11 +5,15 @@ import { nextjs } from './pikku-nextjs.js';
5
5
  import { all } from './pikku-all.js';
6
6
  import { fetch } from './pikku-fetch.js';
7
7
  import { queue } from './pikku-queue-service.js';
8
+ import { websocket } from './pikku-websocket.js';
9
+ import { rpc } from './pikku-rpc.js';
8
10
  const program = new Command('pikku');
9
11
  program.usage('[command]');
10
12
  all(program);
11
13
  schemas(program);
12
14
  nextjs(program);
15
+ websocket(program);
16
+ rpc(program);
13
17
  fetch(program);
14
18
  queue(program);
15
19
  program.parse(process.argv);
@@ -7,12 +7,15 @@ export interface PikkuCLICoreOutputFiles {
7
7
  typesDeclarationFile: string;
8
8
  functionsFile: string;
9
9
  functionsMetaFile: string;
10
+ functionsMetaMinFile: string;
10
11
  httpWiringsFile: string;
11
12
  httpWiringMetaFile: string;
12
13
  httpMapDeclarationFile: string;
13
14
  channelsWiringFile: string;
14
15
  channelsWiringMetaFile: string;
15
16
  channelsMapDeclarationFile: string;
17
+ rpcInternalWiringMetaFile: string;
18
+ rpcInternalMapDeclarationFile: string;
16
19
  rpcWiringMetaFile: string;
17
20
  rpcMapDeclarationFile: string;
18
21
  schedulersWiringFile: string;
@@ -61,7 +61,8 @@ const _getPikkuCLIConfig = async (configFile = undefined, requiredFields, filter
61
61
  const functionDir = join(result.outDir, 'function');
62
62
  const httpDir = join(result.outDir, 'http');
63
63
  const channelDir = join(result.outDir, 'channel');
64
- const rpcDir = join(result.outDir, 'rpc');
64
+ const internalRPCDirectory = join(result.outDir, 'rpc-internal');
65
+ const externalRPCDirectory = join(result.outDir, 'rpc');
65
66
  const schedulerDir = join(result.outDir, 'scheduler');
66
67
  const queueDir = join(result.outDir, 'queue');
67
68
  const mcpDir = join(result.outDir, 'mcp');
@@ -76,6 +77,9 @@ const _getPikkuCLIConfig = async (configFile = undefined, requiredFields, filter
76
77
  if (!result.functionsMetaFile) {
77
78
  result.functionsMetaFile = join(functionDir, 'pikku-functions-meta.gen.ts');
78
79
  }
80
+ if (!result.functionsMetaMinFile) {
81
+ result.functionsMetaMinFile = join(functionDir, 'pikku-functions-meta.min.gen.ts');
82
+ }
79
83
  if (!result.typesDeclarationFile) {
80
84
  result.typesDeclarationFile = join(result.outDir, 'pikku-types.gen.ts');
81
85
  }
@@ -99,12 +103,19 @@ const _getPikkuCLIConfig = async (configFile = undefined, requiredFields, filter
99
103
  if (!result.channelsMapDeclarationFile) {
100
104
  result.channelsMapDeclarationFile = join(channelDir, 'pikku-channels-map.gen.d.ts');
101
105
  }
102
- // RPC
106
+ // Internal
107
+ if (!result.rpcInternalWiringMetaFile) {
108
+ result.rpcInternalWiringMetaFile = join(internalRPCDirectory, 'pikku-rpc-wirings-meta.internal.gen.ts');
109
+ }
110
+ if (!result.rpcInternalMapDeclarationFile) {
111
+ result.rpcInternalMapDeclarationFile = join(internalRPCDirectory, 'pikku-rpc-wirings-map.internal.gen.d.ts');
112
+ }
113
+ // External
103
114
  if (!result.rpcWiringMetaFile) {
104
- result.rpcWiringMetaFile = join(rpcDir, 'pikku-rpc-wirings-meta.gen.ts');
115
+ result.rpcWiringMetaFile = join(externalRPCDirectory, 'pikku-rpc-wirings-meta.gen.ts');
105
116
  }
106
117
  if (!result.rpcMapDeclarationFile) {
107
- result.rpcMapDeclarationFile = join(rpcDir, 'pikku-rpc-wirings-map.gen.d.ts');
118
+ result.rpcMapDeclarationFile = join(externalRPCDirectory, 'pikku-rpc-wirings-map.gen.d.ts');
108
119
  }
109
120
  // Scheduler
110
121
  if (!result.schedulersWiringFile) {
@@ -2,7 +2,68 @@ import { getFileImportRelativePath } from './utils.js';
2
2
  export const serializeImportMap = (relativeToPath, packageMappings, typesMap, requiredTypes) => {
3
3
  const paths = new Map();
4
4
  Array.from(requiredTypes).forEach((requiredType) => {
5
- const { originalName, uniqueName, path } = typesMap.getTypeMeta(requiredType);
5
+ let originalName, uniqueName, path;
6
+ try {
7
+ const typeMeta = typesMap.getTypeMeta(requiredType);
8
+ originalName = typeMeta.originalName;
9
+ uniqueName = typeMeta.uniqueName;
10
+ path = typeMeta.path;
11
+ }
12
+ catch (e) {
13
+ // Handle missing types by trying to find a suitable import path
14
+ // Look through all existing types in the map to find a path that might contain this type
15
+ let foundPath = null;
16
+ // Get all unique paths from the typesMap
17
+ const allPaths = new Set();
18
+ typesMap.customTypes.forEach(({ type, references }) => {
19
+ references.forEach((ref) => {
20
+ try {
21
+ const refMeta = typesMap.getTypeMeta(ref);
22
+ if (refMeta.path) {
23
+ allPaths.add(refMeta.path);
24
+ }
25
+ }
26
+ catch {
27
+ // Continue
28
+ }
29
+ });
30
+ });
31
+ // Also check direct types in the map
32
+ try {
33
+ const mapEntries = typesMap.map?.entries?.() || [];
34
+ for (const [_, typeMeta] of mapEntries) {
35
+ if (typeMeta.path) {
36
+ allPaths.add(typeMeta.path);
37
+ }
38
+ }
39
+ }
40
+ catch {
41
+ // Continue
42
+ }
43
+ // For PascalCase types, prefer paths that look like type definition files
44
+ if (/^[A-Z]/.test(requiredType)) {
45
+ for (const candidatePath of allPaths) {
46
+ if (candidatePath.includes('types') ||
47
+ candidatePath.includes('.d.')) {
48
+ foundPath = candidatePath;
49
+ break;
50
+ }
51
+ }
52
+ // If no types file found, use the first available path
53
+ if (!foundPath && allPaths.size > 0) {
54
+ foundPath = Array.from(allPaths)[0] || null;
55
+ }
56
+ }
57
+ if (foundPath) {
58
+ originalName = requiredType;
59
+ uniqueName = requiredType;
60
+ path = foundPath;
61
+ }
62
+ else {
63
+ // No suitable path found, skip
64
+ return;
65
+ }
66
+ }
6
67
  if (!path) {
7
68
  // This is a custom type that exists in file, so we don't need to import it
8
69
  return;
@@ -6,7 +6,7 @@ export const serializePikkuTypes = (userSessionTypeImport, userSessionTypeName,
6
6
  * This is used to provide the application types in the typescript project
7
7
  */
8
8
 
9
- import { CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuMiddleware, addHTTPMiddleware } from '@pikku/core'
9
+ import { CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuMiddleware, addHTTPMiddleware, addMiddleware, addMiddlewareForTags, addPermission } from '@pikku/core'
10
10
  import { CorePikkuFunction, CorePikkuFunctionSessionless } from '@pikku/core/function'
11
11
  import { CoreHTTPFunctionWiring, AssertHTTPWiringParams, wireHTTP as wireHTTPCore } from '@pikku/core/http'
12
12
  import { CoreScheduledTask, wireScheduler as wireSchedulerCore } from '@pikku/core/scheduler'
@@ -51,7 +51,7 @@ type PikkuFunctionSessionless<
51
51
  Out = never,
52
52
  ChannelData = null, // null means optional channel
53
53
  MCPData = null, // null means optional MCP
54
- RequiredServices extends Services = Services &
54
+ RequiredServices extends Services = Omit<Services, 'rpc'> &
55
55
  { rpc: TypedPikkuRPC } & (
56
56
  [ChannelData] extends [null]
57
57
  ? { channel?: PikkuChannel<unknown, Out> } // Optional channel
@@ -77,7 +77,7 @@ type PikkuFunction<
77
77
  Out = never,
78
78
  ChannelData = null, // null means optional channel
79
79
  MCPData = null, // null means optional MCP
80
- RequiredServices extends Services = Services &
80
+ RequiredServices extends Services = Omit<Services, 'rpc'> &
81
81
  { rpc: TypedPikkuRPC } & (
82
82
  [ChannelData] extends [null]
83
83
  ? { channel?: PikkuChannel<unknown, Out> } // Optional channel
@@ -111,7 +111,7 @@ type ChannelWiring<ChannelData, Channel extends string> = CoreChannel<ChannelDat
111
111
  * Type definition for scheduled tasks that run at specified intervals.
112
112
  * These are sessionless functions that execute based on cron expressions.
113
113
  */
114
- type SchedulerWiring = CoreScheduledTask<PikkuFunctionSessionless<void, void>>
114
+ type SchedulerWiring = CoreScheduledTask<PikkuFunctionSessionless<void, void>, PikkuMiddleware>
115
115
 
116
116
  /**
117
117
  * Type definition for queue workers that process background jobs.
@@ -194,7 +194,7 @@ export const pikkuFunc = <In, Out = unknown>(
194
194
  export const pikkuSessionlessFunc = <In, Out = unknown>(
195
195
  func:
196
196
  | PikkuFunctionSessionless<In, Out>
197
- | CorePikkuFunctionConfig<PikkuFunctionSessionless<In, Out>, PikkuPermission<In>>
197
+ | CorePikkuFunctionConfig<PikkuFunctionSessionless<In, Out>, PikkuPermission<In>, PikkuMiddleware>
198
198
  ) => {
199
199
  return typeof func === 'function' ? func : func.func
200
200
  }
@@ -344,6 +344,78 @@ export const wireChannel = <ChannelData, Channel extends string>(
344
344
  */
345
345
  export { addHTTPMiddleware }
346
346
 
347
+ /**
348
+ * Adds global middleware for a specific tag.
349
+ *
350
+ * This function allows you to register middleware that will be applied to
351
+ * any wiring (HTTP, Channel, Queue, Scheduler, MCP) that includes the matching tag.
352
+ *
353
+ * @param tag - The tag that the middleware should apply to.
354
+ * @param middleware - The middleware array to apply for the specified tag.
355
+ *
356
+ * @throws Error if middleware for the tag already exists.
357
+ *
358
+ * @example
359
+ * \`\`\`typescript
360
+ * // Add admin middleware for admin endpoints
361
+ * addMiddleware('admin', [adminMiddleware])
362
+ *
363
+ * // Add authentication middleware for auth endpoints
364
+ * addMiddleware('auth', [authMiddleware])
365
+ *
366
+ * // Add logging middleware for all API endpoints
367
+ * addMiddleware('api', [loggingMiddleware])
368
+ * \`\`\`
369
+ */
370
+ export { addMiddleware }
371
+
372
+ /**
373
+ * Combines tag-based middleware with wiring-specific middleware.
374
+ *
375
+ * This helper function gets middleware for tags and combines it with any
376
+ * wiring-specific middleware, avoiding the need for manual spreading.
377
+ *
378
+ * @param wiringMiddleware - Wiring-specific middleware.
379
+ * @param tags - Array of tags to look up middleware for.
380
+ * @returns Combined array of tag-based and wiring-specific middleware.
381
+ *
382
+ * @example
383
+ * \`\`\`typescript
384
+ * // Instead of:
385
+ * const taggedMiddleware = getMiddlewareForTags(tags)
386
+ * const combined = [...taggedMiddleware, ...(middleware || [])]
387
+ *
388
+ * // Use:
389
+ * const combined = addMiddlewareForTags(middleware, tags)
390
+ * \`\`\`
391
+ */
392
+ export { addMiddlewareForTags }
393
+
394
+ /**
395
+ * Adds global permissions for a specific tag.
396
+ *
397
+ * This function allows you to register permissions that will be applied to
398
+ * any wiring (HTTP, Channel, Queue, Scheduler, MCP) that includes the matching tag.
399
+ *
400
+ * @param tag - The tag that the permissions should apply to.
401
+ * @param permissions - The permissions array to apply for the specified tag.
402
+ *
403
+ * @throws Error if permissions for the tag already exist.
404
+ *
405
+ * @example
406
+ * \`\`\`typescript
407
+ * // Add admin permissions for admin endpoints
408
+ * addPermission('admin', [adminPermission])
409
+ *
410
+ * // Add authentication permissions for auth endpoints
411
+ * addPermission('auth', [authPermission])
412
+ *
413
+ * // Add read permissions for all API endpoints
414
+ * addPermission('api', [readPermission])
415
+ * \`\`\`
416
+ */
417
+ export { addPermission }
418
+
347
419
  /**
348
420
  * Registers an HTTP wiring with the Pikku framework.
349
421
  *
package/dist/src/utils.js CHANGED
@@ -206,8 +206,30 @@ export function generateCustomTypes(typesMap, requiredTypes) {
206
206
  ${Array.from(typesMap.customTypes.entries())
207
207
  .map(([name, { type, references }]) => {
208
208
  references.forEach((name) => {
209
- const originalName = typesMap.getTypeMeta(name).originalName;
210
- requiredTypes.add(originalName);
209
+ requiredTypes.add(name);
210
+ });
211
+ // Extract type names from the type string that might not be in references
212
+ const typeString = type;
213
+ // Use regex to extract potential type names (PascalCase identifiers)
214
+ const typeNameRegex = /\b[A-Z][a-zA-Z0-9]*\b/g;
215
+ const potentialTypes = typeString.match(typeNameRegex) || [];
216
+ potentialTypes.forEach((typeName) => {
217
+ // Skip string literals and common keywords
218
+ if (typeString.includes(`"${typeName}"`) ||
219
+ ['Pick', 'Omit', 'Partial', 'Required', 'Record', 'Readonly'].includes(typeName)) {
220
+ return;
221
+ }
222
+ // Try to find this type in the typesMap and add it if found
223
+ try {
224
+ const typeMeta = typesMap.getTypeMeta(typeName);
225
+ if (typeMeta.path) {
226
+ requiredTypes.add(typeName);
227
+ }
228
+ }
229
+ catch (e) {
230
+ // Type not found in map, but add it anyway for fallback resolution
231
+ requiredTypes.add(typeName);
232
+ }
211
233
  });
212
234
  return `export type ${name} = ${type}`;
213
235
  })
@@ -1,13 +1,13 @@
1
1
  import { getFileImportRelativePath, getPikkuFilesAndMethods, logCommandInfoAndTime, writeFileInDir, } from '../../utils.js';
2
2
  import { serializePikkuTypes } from '../../serialize-pikku-types.js';
3
- export const pikkuFunctionTypes = async (logger, { typesDeclarationFile: typesFile, packageMappings, rpcMapDeclarationFile }, visitState, options = {}) => {
3
+ export const pikkuFunctionTypes = async (logger, { typesDeclarationFile: typesFile, packageMappings, rpcInternalMapDeclarationFile, }, visitState, options = {}) => {
4
4
  return await logCommandInfoAndTime(logger, 'Creating api types', 'Created api types', [false], async () => {
5
5
  const { userSessionType, sessionServicesType, singletonServicesType } = await getPikkuFilesAndMethods(logger, visitState, packageMappings, typesFile, options, {
6
6
  userSessionType: true,
7
7
  sessionServiceType: true,
8
8
  singletonServicesType: true,
9
9
  });
10
- const content = serializePikkuTypes(`import type { ${userSessionType.type} } from '${getFileImportRelativePath(typesFile, userSessionType.typePath, packageMappings)}'`, userSessionType.type, `import type { ${singletonServicesType.type} } from '${getFileImportRelativePath(typesFile, singletonServicesType.typePath, packageMappings)}'`, singletonServicesType.type, `import type { ${sessionServicesType.type} } from '${getFileImportRelativePath(typesFile, sessionServicesType.typePath, packageMappings)}'`, `import type { TypedPikkuRPC } from '${getFileImportRelativePath(typesFile, rpcMapDeclarationFile, packageMappings)}'`);
10
+ const content = serializePikkuTypes(`import type { ${userSessionType.type} } from '${getFileImportRelativePath(typesFile, userSessionType.typePath, packageMappings)}'`, userSessionType.type, `import type { ${singletonServicesType.type} } from '${getFileImportRelativePath(typesFile, singletonServicesType.typePath, packageMappings)}'`, singletonServicesType.type, `import type { ${sessionServicesType.type} } from '${getFileImportRelativePath(typesFile, sessionServicesType.typePath, packageMappings)}'`, `import type { TypedPikkuRPC } from '${getFileImportRelativePath(typesFile, rpcInternalMapDeclarationFile, packageMappings)}'`);
11
11
  await writeFileInDir(logger, typesFile, content);
12
12
  });
13
13
  };
@@ -1,6 +1,2 @@
1
1
  import { PikkuCommand } from '../../types.js';
2
- export declare const serializeFunctionImports: (outputPath: string, functionsMap: Map<string, {
3
- path: string;
4
- exportedName: string;
5
- }>, packageMappings?: Record<string, string>) => string;
6
2
  export declare const pikkuFunctions: PikkuCommand;
@@ -1,35 +1,14 @@
1
- import { getFileImportRelativePath, logCommandInfoAndTime, writeFileInDir, } from '../../utils.js';
2
- export const serializeFunctionImports = (outputPath, functionsMap, packageMappings = {}) => {
3
- const serializedImports = [
4
- `/* Import and register RPCs */`,
5
- `import { addFunction } from '@pikku/core'`,
6
- ];
7
- const serializedRegistrations = [];
8
- // Sort by function name for consistent output
9
- const sortedEntries = Array.from(functionsMap.entries()).sort((a, b) => a[0].localeCompare(b[0]));
10
- for (const [name, { path, exportedName }] of sortedEntries) {
11
- const filePath = getFileImportRelativePath(outputPath, path, packageMappings);
12
- // For directly exported functions, we can just import and register them
13
- if (name === exportedName) {
14
- serializedImports.push(`import { ${exportedName} } from '${filePath}'`);
15
- serializedRegistrations.push(`addFunction('${name}', { func: ${exportedName} })`);
16
- }
17
- // For renamed functions, we need to import and alias them
18
- else {
19
- serializedImports.push(`import { ${exportedName} as ${name} } from '${filePath}'`);
20
- serializedRegistrations.push(`addFunction('${name}', ${name})`);
21
- }
22
- }
23
- // Add a blank line between imports and registrations
24
- if (serializedImports.length > 0 && serializedRegistrations.length > 0) {
25
- serializedImports.push('');
26
- }
27
- // Combine the imports and registrations
28
- return [...serializedImports, ...serializedRegistrations].join('\n');
29
- };
30
- export const pikkuFunctions = async (logger, { functionsMetaFile, functionsFile, packageMappings }, { functions }) => {
1
+ import { logCommandInfoAndTime, writeFileInDir } from '../../utils.js';
2
+ import { generateRuntimeMeta, serializeFunctionImports, } from './serialize-function-imports.js';
3
+ export const pikkuFunctions = async (logger, { functionsMetaFile, functionsMetaMinFile, functionsFile, packageMappings }, { functions, rpc }) => {
31
4
  return await logCommandInfoAndTime(logger, 'Serializing Pikku functions', 'Serialized Pikku functions', [false], async () => {
32
- await writeFileInDir(logger, functionsFile, serializeFunctionImports(functionsFile, functions.files, packageMappings));
5
+ // Generate full metadata
33
6
  await writeFileInDir(logger, functionsMetaFile, `import { pikkuState } from '@pikku/core'\npikkuState('function', 'meta', ${JSON.stringify(functions.meta, null, 2)})`);
7
+ // Generate minimal metadata (runtime)
8
+ const runtimeMeta = generateRuntimeMeta(functions.meta);
9
+ await writeFileInDir(logger, functionsMetaMinFile, `import { pikkuState } from '@pikku/core'\npikkuState('function', 'meta', ${JSON.stringify(runtimeMeta, null, 2)})`);
10
+ if (rpc.exposedFiles.size > 0 || rpc.internalFiles.size > 0) {
11
+ await writeFileInDir(logger, functionsFile, serializeFunctionImports(functionsFile, rpc.internalFiles, functions.meta, packageMappings));
12
+ }
34
13
  });
35
14
  };
@@ -60,7 +60,7 @@ export const serializeServicesMap = (functionsMetaData, middlewareServices = [],
60
60
  return code;
61
61
  };
62
62
  export const pikkuServices = async (logger, cliConfig, visitState) => {
63
- return await logCommandInfoAndTime(logger, 'Generating Pikku services map', 'Generated Pikku services map', [visitState.functions.files.size === 0], async () => {
63
+ return await logCommandInfoAndTime(logger, 'Generating Pikku services map', 'Generated Pikku services map', [false], async () => {
64
64
  const { sessionServicesType, singletonServicesType } = await getPikkuFilesAndMethods(logger, visitState, cliConfig.packageMappings, cliConfig.typesDeclarationFile, {}, {
65
65
  sessionServiceType: true,
66
66
  singletonServicesType: true,
@@ -1,13 +1,13 @@
1
1
  import { getFileImportRelativePath, getPikkuFilesAndMethods, logCommandInfoAndTime, writeFileInDir, } from '../../utils.js';
2
2
  import { serializePikkuTypes } from '../../serialize-pikku-types.js';
3
- export const pikkuFunctionTypes = async (logger, { typesDeclarationFile: typesFile, packageMappings, rpcMapDeclarationFile }, visitState, options = {}) => {
3
+ export const pikkuFunctionTypes = async (logger, { typesDeclarationFile: typesFile, packageMappings, rpcInternalMapDeclarationFile, }, visitState, options = {}) => {
4
4
  return await logCommandInfoAndTime(logger, 'Creating api types', 'Created api types', [false], async () => {
5
5
  const { userSessionType, sessionServicesType, singletonServicesType } = await getPikkuFilesAndMethods(logger, visitState, packageMappings, typesFile, options, {
6
6
  userSessionType: true,
7
7
  sessionServiceType: true,
8
8
  singletonServicesType: true,
9
9
  });
10
- const content = serializePikkuTypes(`import type { ${userSessionType.type} } from '${getFileImportRelativePath(typesFile, userSessionType.typePath, packageMappings)}'`, userSessionType.type, `import type { ${singletonServicesType.type} } from '${getFileImportRelativePath(typesFile, singletonServicesType.typePath, packageMappings)}'`, singletonServicesType.type, `import type { ${sessionServicesType.type} } from '${getFileImportRelativePath(typesFile, sessionServicesType.typePath, packageMappings)}'`, `import type { TypedPikkuRPC } from '${getFileImportRelativePath(typesFile, rpcMapDeclarationFile, packageMappings)}'`);
10
+ const content = serializePikkuTypes(`import type { ${userSessionType.type} } from '${getFileImportRelativePath(typesFile, userSessionType.typePath, packageMappings)}'`, userSessionType.type, `import type { ${singletonServicesType.type} } from '${getFileImportRelativePath(typesFile, singletonServicesType.typePath, packageMappings)}'`, singletonServicesType.type, `import type { ${sessionServicesType.type} } from '${getFileImportRelativePath(typesFile, sessionServicesType.typePath, packageMappings)}'`, `import type { TypedPikkuRPC } from '${getFileImportRelativePath(typesFile, rpcInternalMapDeclarationFile, packageMappings)}'`);
11
11
  await writeFileInDir(logger, typesFile, content);
12
12
  });
13
13
  };
@@ -0,0 +1,6 @@
1
+ import { FunctionsMeta, FunctionsRuntimeMeta } from '@pikku/core';
2
+ export declare const serializeFunctionImports: (outputPath: string, functionsMap: Map<string, {
3
+ path: string;
4
+ exportedName: string;
5
+ }>, functionsMeta: FunctionsMeta, packageMappings?: Record<string, string>) => string;
6
+ export declare const generateRuntimeMeta: (functions: FunctionsMeta) => FunctionsRuntimeMeta;